Py-numpy的随机函数【转载】

转自:https://blog.csdn.net/u012149181/article/details/78913167 

1. numpy.random.rand()

numpy.random.rand(d0,d1,…,dn)

  • rand函数根据给定维度生成[0,1)之间的数据,包含0,不包含1
  • dn表格每个维度
  • 返回值为指定维度的array
>>> np.random.rand(2,2)
          
array([[0.70691613, 0.673804  ],
       [0.7999329 , 0.30363377]])

2.numpy.random.randn(d0,d1,…,dn)

  • randn函数返回一个或一组样本,具有标准正态分布
  • dn表格每个维度
  • 返回值为指定维度的array
>>> np.random.randn(2,2)
          
array([[-0.54880779,  0.03757687],
       [ 0.35608059, -0.16970511]])
>>> np.random.randn()
          
-0.5041373211552308

 

 其中n的意思就是normal,正态。μ=0,σ=1.

3 numpy.random.randint()

numpy.random.randint(low, high=None, size=None, dtype=’l’)

  • 返回随机整数,范围区间为[low,high),包含low,不包含high
  • 参数:low为最小值,high为最大值,size为数组维度大小,dtype为数据类型,默认的数据类型是np.int
  • high没有填写时,默认生成随机数的范围是[0,low)
>>> np.random.randint(0,2)
          
0
>>> np.random.randint(0,2,5)
          
array([1, 0, 0, 1, 0])
>>> np.random.randint(5,2)
          
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    np.random.randint(5,2)
  File "mtrand.pyx", line 993, in mtrand.RandomState.randint
ValueError: low >= high
>>> np.random.randint(low=5,size=2)
          
array([3, 2])

4 生成0-1之间的浮点数

>>> np.random.random((2,2))
          
array([[0.7066545 , 0.66002817],
       [0.79023509, 0.77658663]])
>>> np.random.sample((2,2))
          
array([[0.07203548, 0.54526898],
       [0.56429719, 0.74669749]]) 

6.numpy.random.seed()

  • np.random.seed()的作用:使得随机数据可预测。
  • 当我们设置相同的seed,每次生成的随机数相同。如果不设置seed,则每次会生成不同的随机数。
>>> np.random.seed(0)
          
>>> np.random.rand()
          
0.5488135039273248
>>> np.random.rand()
          
0.7151893663724195
>>> np.random.seed(0)
          
>>> np.random.rand()
          
0.5488135039273248
>>> np.random.rand()
          
0.7151893663724195

7.np.random.normal(loc=0.0scale=1.0size=None)

参数分别是高斯分布的:均值、方差、形状。

posted @ 2019-03-15 11:25  lypbendlf  阅读(1014)  评论(0编辑  收藏  举报