1. 程式人生 > >numpy教程:隨機數模組numpy.random

numpy教程:隨機數模組numpy.random

隨機數種子

RandomState

RandomState exposes a number of methods for generating random numbersdrawn from a variety of probability distributions.

使用示例

prng = np.random.RandomState(123456789) # 定義區域性種子
prng.rand(2, 4)

prng.chisquare(1, size=(2, 2)) # 卡方分佈
prng.standard_t(1, size=(2, 3)) # t 分佈
prng.poisson(5, size=10) # 泊松分佈

random.seed()

random.seed(123456789) # 種子不同,產生的隨機數序列也不同,隨機數種子都是全域性種子

要每次產生隨機數相同就要設定種子,相同種子數的Random物件,相同次數生成的隨機數字是完全相同的;

random.seed(1)

這樣random.randint(0,6, (4,5))每次都產生一樣的4*5的隨機矩陣

This method is called when RandomState is initialized. It can be called again to re-seed the generator.

numpy.random模組

linspace(start, end, num): 如linspace(0,1,11)結果為[0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1];

arange(n): 產生一個從0到n-1的向量,如arange(4)結果為[0,1,2,3]

簡單隨機生成資料相關函式

rand(d0, d1, ..., dn)Random values in a given shape.
randn(d0, d1, ..., dn)Return a sample (or samples) from the “standard normal” distribution.
randint(low[, high, size, dtype])Return random integers from low (inclusive) to high (exclusive).
Random integers of type np.int between low
and high, inclusive.
Return random floats in the half-open interval [0.0, 1.0).
Return random floats in the half-open interval [0.0, 1.0).產生隨機矩陣,如random.random([2,3])產生一個2x3維的隨機數
ranf([size])Return random floats in the half-open interval [0.0, 1.0).
Return random floats in the half-open interval [0.0, 1.0).
choice(a[, size, replace, p])Generates a random sample from a given 1-D array
bytes(length)Return random bytes.

[Simple random data]

np.random模組使用示例

np.random.rand(a, b)

from numpy import random
x = random.rand(2, 3)
print(x)
[[ 0.1169922   0.08614147  0.17997144]
 [ 0.5694889   0.43067372  0.62135592]]
x, y = random.rand(2, 3)
print(x)
print(y)
[ 0.60527337  0.78765269  0.71884661]
[ 0.67420571  0.946359    0.7632273 ]
[]

np.random.randint(a, b, size=(c, d))

size : int or tuple of ints, optional
raw_user_item_mat = random.randint(0, 10, size=(3,4))     #指定生成隨機數範圍和生成的多維陣列大小
print(raw_user_item_mat)
[[3 6 2 8]
 [3 1 2 4]
 [9 4 5 0]]
[Random sampling (numpy.random)]

高階隨機生成資料函式

二項分佈函式

np.random.binomial(n,p,size=N),函式的返回值表示n中成功的次數,且以Cn^x*p^x*(1-p)^(n-x)的概率選擇成功x次
每一輪拋9枚硬幣:
outcome = np.random.binomial(9, 0.5, size=len(cash))
[二項分佈]

超幾何分佈

超幾何分佈是統計學上一種離散概率分佈。它描述了由有限個物件中抽出n個物件,成功抽出指定種類的物件的次數(不歸還)。
在產品質量的不放回抽檢中,若N件產品中有M件次品,抽檢n件時所得次品數X=k,則P(X=k)=C(M,k)·C(N-M,n-k)/C(N,n), C(a b)為古典概型的組合形式,a為下限,b為上限,此時我們稱隨機變數X服從超幾何分佈(hypergeometric distribution)。
(1)超幾何分佈的模型是不放回抽樣。
(2)超幾何分佈中的引數是M,N,n上述超幾何分佈記作X~H(N,n,M)。
NumPy random模組中的hypergeometric函式可以模擬這種分佈。
outcomes = np.random.hypergeometric(25, 1, 3, size=len(points))
#使用hypergeometric函式初始化遊戲的結果矩陣。該函式的第一個引數為罐中普通球的數量,第二個引數為“倒黴球”的數量,第三個引數為每次取樣(摸球)的數量。共進行超幾何分佈size次。返回size個抽樣結果,也就是普通球(正品)的數目。[超幾何分佈]

連續分佈

連續分佈可以用PDF(Probability Density Function,概率密度函式)來描述。隨機變數落在某一區間內的概率等於概率密度函式在該區間的曲線下方的面積。NumPy的random模組中有一系列連續分佈的函式——beta、chisquare、exponential、f、gamma、gumbel、laplace、lognormal、logistic、multivariate_normal、noncentral_chisquare、noncentral_f、normal等。
繪製正態分佈
隨機數可以從正態分佈中產生,它們的直方圖能夠直觀地刻畫正態分佈。
import numpy as np
import matplotlib.pyplot as plt
#使用NumPy random模組中的normal函式產生指定數量的隨機數。
N=10000

normal_values = np.random.normal(size=N)   #lz一般使用stats.norm.rvs(loc=0, scale=0.1, size=10)來生成高斯分佈隨機數[Scipy教程 - 統計函式庫scipy.stats]

#繪製分佈直方圖和理論上的概率密度函式(均值為0、方差為1的正態分佈)曲線。
dummy, bins, dummy = plt.hist(normal_values, np.sqrt(N), normed=True, lw=1)
sigma = 1
mu = 0

plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) * np.exp( - (bins -mu)**2 / (2 * sigma**2) ),lw=2) #lz提示,也可以使用scipy.stat.norm.pdf來生成非隨機的高斯分佈圖[Scipy教程 - 統計函式庫scipy.stats]

plt.show()
對數正態分佈
np.random.lognormal(size=N)

random應用例項

從大小為n的原始樣本集D中不放回得隨機選取n1個樣本點,得到樣本集D1和剩下的樣本集D1_left:
random_index = np.ones_like(class_labels, dtype=bool)
random_index[np.random.choice(range(len(data_arr)), n1, replace=False)] = False
D1 = data_arr[random_index]
D1_left = data_arr[~random_index]