numpy.random使用方法

https://www.sharpsightlabs.com/blog/numpy-random-normal/

Normal distrubution

The NumPy random normal function generates a sample of numbers drawn from the normal distribution(正态分布、常态分布), otherwise called the Gaussian distribution(高斯分布).

参考链接:维基百科

NUMPY RANDOM NORMAL GENERATES NORMALLY DISTRIBUTED NUMBERS

random normal函数可以让你创建一个包含正态分布数据的numpy数组。

下图是我们用直方图绘制数据:

rr1

正态分布数据,就像bell(钟、铃铛),所以经常被称为“钟形曲线”。

接下来我们看看语法。

THE SYNTAX OF NUMPY RANDOM NORMAL

不要忘了导入模块:

1
import numpy as np

rr2

np.random.normal()函数有3个参数:

  • loc
  • scale
  • size

THE PARAMETERS OF THE NP.RANDOM.NORMAL FUNCTION

loc:控制函数的平均值(Mean),默认值是0。

arr3

scale:控制正态分布的标准偏差,默认值是1。

arr4

size:控制输出的大小和形状。

If you provide a single integer, x, np.random.normal will provide x random normal values in a 1-dimensional NumPy array.

如果 size = x,那np.random.normal函数就会提供一个有x个正态分布数值的1维numpy数组。

For example, if you specify size = (2, 3), np.random.normal will produce a numpy array with 2 rows and 3 columns. It will be filled with numbers drawn from a random normal distribution.

例如,你指定 size = (2, 3),那就会产生一个2行3列的numpy数组。

THE NP.RANDOM.RANDN FUNCTION

还有一个类似的函数:np.random.randn()。

这个代码:

1
2
np.random.seed(1)
np.random.normal(loc = 0, scale = 1, size = (3,3))

等于下面这个:

1
2
np.random.seed(1)
np.random.randn(3, 3)

EXAMPLES: HOW TO USE THE NUMPY RANDOM NORMAL FUNCTION

DRAW A SINGLE NUMBER FROM THE NORMAL DISTRIBUTION

1
2
3
np.random.normal(1)

# 等于: np.random.normal(size = 1, loc = 0, scale = 1)

DRAW 5 NUMBERS FROM THE NORMAL DISTRIBUTION

1
np.random.normal(5)

CREATE A 2-DIMENSIONAL NUMPY ARRAY OF NORMALLY DISTRIBUTED VALUES

1
2
3
4
5
np.random.seed(42)
np.random.normal(size = (2, 3))

#array([[ 1.62434536, -0.61175641, -0.52817175],
# [-1.07296862, 0.86540763, -2.3015387 ]])

GENERATE NORMALLY DISTRIBUTED VALUES WITH A SPECIFIC MEAN

1
2
3
4
5
6
7
np.random.seed(42)
np.random.normal(size = 1000, loc = 50)

# array([ 50.49671415, 49.8617357 , 50.64768854, 51.52302986,
# 49.76584663, 49.76586304, 51.57921282, 50.76743473,
# 49.53052561, 50.54256004, 49.53658231, 49.53427025
# ...

GENERATE NORMALLY DISTRIBUTED VALUES WITH A SPECIFIC STANDARD DEVIATION

1
2
3
4
5
6
7
np.random.seed(42)
np.random.normal(size = 1000, scale = 100)

#array([ 4.96714153e+01, -1.38264301e+01, 6.47688538e+01,
# 1.52302986e+02, -2.34153375e+01, -2.34136957e+01,
# 1.57921282e+02, 7.67434729e+01, -4.69474386e+01
# ...

我们可以用std()方法去计算标准偏差:

1
2
3
4
np.random.seed(42)
np.random.normal(size = 1000, scale = 100).std()

# 99.695552529463015

HOW TO USE THE LOC AND SCALE PARAMETER IN NP.RANDOM.NORMAL

1
2
np.random.seed(42)
np.random.normal(size = 1000, loc = 50, scale = 100)

numpy.random.normal

https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.normal.html