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


http://blog.csdn.net/pipisorry/article/details/39508417

隨機數種子

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) # 泊松分布

[概率與統計分析]

[class numpy.random.RandomState]

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.seed]

 

關於種子的介紹可參見[Java - 常用函數Random函數]

皮皮blog

 

 

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(low[, high, size]) Random integers of type np.int between low and high, inclusive.
random_sample([size]) Return random floats in the half-open interval [0.0, 1.0).
random([size]) 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).
sample([size]) 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 ]
[ numpy - 基本數據類型、多維數組ndarray及函數操作]

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]

 

from:http://blog.csdn.net/pipisorry/article/details/39508417

ref: Python模塊:生成隨機數模塊random


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM