numpy.random模塊中提供啦大量的隨機數相關的函數。python
1 numpy中產生隨機數的方法數組
1)rand() 產生[0,1]的浮點隨機數,括號裏面的參數能夠指定產生數組的形狀dom
2)randn() 產生標準正太分佈隨機數,參數含義與random相同函數
3)randint() 產生指定範圍的隨機數,最後一個參數是元祖,他肯定數組的形狀orm
import numpy as np from numpy import random as nr #只顯示小數點後兩位 np.set_printoptions(precision = 2) r1 = nr.rand(3,4) r2 = nr.randn(5,4) r3 = nr.randint(0,10,size = (4,3)) print r1 print r2 print r3
[[ 0.34 0.51 0.65 0.57] [ 0.97 0.16 0.62 0.37] [ 0.23 0.78 0.77 0.46]] [[-0.69 -1.24 -0.32 1.07] [ 0.05 -1.97 1.01 -1.59] [ 1.51 -1.21 1.02 -0.19] [ 1.49 -0.42 0.64 0.07] [-0.1 1.11 0.24 -0.18]] [[9 6 7] [1 9 7] [4 9 6] [3 9 0]] (Pdb)
2 經常使用分佈blog
1)normal() 正太分佈ip
2)uniform() 均勻分佈utf-8
3)poisson() 泊松分佈ci
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import numpy as np from numpy import random as nr #只顯示小數點後兩位 np.set_printoptions(precision = 2) #第一個參數是均值,第二個參數是標準差 r1 = nr.normal(100,10,size = (3,4)) print r1 #前兩個參數分別是區間的初始值和終值 r2 = nr.uniform(0,10,size = (3,4)) print r2 #第一個參數爲指定的lanbda係數 r3 = nr.poisson(2.0,size = (3,4)) print r3
[[ 100.67 98.39 99.36 103.37] [ 98.23 95.11 107.57 111.23] [ 97.26 75.21 110.4 112.53]] [[ 2.42 6.81 9.96 3.15] [ 9.28 4.4 7.87 5.19] [ 3.47 2.92 4.5 2.58]] [[3 1 5 0] [1 0 4 3] [3 1 2 1]] (Pdb)
3 亂序和隨機抽取it
permutation()隨機生成一個亂序數組,當參數是n時,返回[0,n)的亂序,他返回一個新數組。而shuffle()則直接將原數組打亂。choice()是從指定的樣本中隨機抽取。
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import numpy as np from numpy import random as nr #只顯示小數點後兩位 np.set_printoptions(precision = 2) #返回打亂數組,原數組不變 r1 = nr.randint(10,100,size = (3,4)) print r1 print nr.permutation(r1) print r1 print nr.permutation(5) # 使用shuffle打亂數組順序 x = np.arange(10) nr.shuffle(x) print x #xhoice()函數從指定數組中隨機抽取樣本 #size參數用於指定輸出數組的大小 #replace參數爲True時,進行可重複抽取,而False表示進行不可重複的抽取。默認爲True x = np.array(10) c1 = nr.choice(x,size = (2,3)) print c1 c2 = nr.choice(x,5,replace = False) print c2
[[78 22 43 70] [46 87 12 32] [11 56 89 79]] [[11 56 89 79] [78 22 43 70] [46 87 12 32]] [[78 22 43 70] [46 87 12 32] [11 56 89 79]] [4 1 2 0 3] [3 4 9 5 8 2 7 0 6 1] [[4 7 9] [9 1 7]] [5 3 2 8 4] (Pdb)