numpy生成随机数的方法

开篇

这边主要记录一下

设置了seed的问题

设置了seed就可以保证每次生成的随机数都是一样的,在基本的机器学习入门代码里面最常会出现的就是seed

In [1]: import numpy as np

In [2]: np.random.seed(10)

In [3]: np.random.rand(8)
Out[3]: 
array([ 0.77132064,  0.02075195,  0.63364823,  0.74880388,  0.49850701,
        0.22479665,  0.19806286,  0.76053071])

In [4]: np.random.rand(8)
Out[4]: 
array([ 0.16911084,  0.08833981,  0.68535982,  0.95339335,  0.00394827,
        0.51219226,  0.81262096,  0.61252607])

In [5]: np.random.seed(10)

In [6]: np.random.rand(8)
Out[6]: 
array([ 0.77132064,  0.02075195,  0.63364823,  0.74880388,  0.49850701,
        0.22479665,  0.19806286,  0.76053071])

注意这边的seed和rand同时出现的时候才是能够生效的

后面的参数代表的是维度

In [7]: np.random.rand(2,3)
Out[7]: 
array([[ 0.16911084,  0.08833981,  0.68535982],
       [ 0.95339335,  0.00394827,  0.51219226]])

生成标准正太分布的随机数

In [8]: np.random.randn(2,3)
Out[8]: 
array([[ 0.43302619,  1.20303737, -0.96506567],
       [ 1.02827408,  0.22863013,  0.44513761]])

生成整数

In [10]: np.random.randint(2,10,size=(2,3))
Out[10]: 
array([[7, 5, 3],
       [8, 7, 6]])

生成[2,10)均匀分布的函数

In [11]: np.random.random_integers(2,10,size=(2,3))
/home/dave/anaconda3/bin/ipython:1: DeprecationWarning: This function is deprecated. Please call randint(2, 10 + 1) instead
  #!/home/dave/anaconda3/bin/python
Out[11]: 
array([[8, 3, 6],
       [4, 8, 9]])

猜你喜欢

转载自blog.csdn.net/ding_xiaofei/article/details/80891046