python中random(numpy.random)隨機數的使用


基礎知識(maybe is boring,but it's fundamental):

(一)random

(1)實值分布

random.random()

  返回 [0.0, 1.0) 范圍內的下一個隨機浮點數。

random.uniform(a, b)

  返回一個隨機浮點數 N ,當 a <= b 時 a <= N <= b ,當 b < a 時 b <= N <= a 。

取決於等式 a + (b-a) * random() 中的浮點舍入,終點 b 可以包括或不包括在該范圍內。

random.triangular(low, high, mode)

  返回一個隨機浮點數 N ,使得 low <= N <= high 並在這些邊界之間使用指定的 mode  low  high 邊界默認為零和一。 mode 參數默認為邊界之間的中點,給出對稱分布。

random.betavariate(alpha, beta)

  Beta 分布。 參數的條件是 alpha > 0 和 beta > 0。 返回值的范圍介於 0 和 1 之間。

random.expovariate(lambd)

  指數分布。 lambd  1.0 除以所需的平均值,它應該是非零的。 (該參數本應命名為 “lambda” ,但這是 Python 中的保留字。)如果 lambd 為正,則返回值的范圍為 0 到正無窮大;如果 lambd 為負,則返回值從負無窮大到 0。

random.gammavariate(alpha, beta)

  Gamma 分布。 ( 不是 gamma 函數! ) 參數的條件是 alpha > 0 和 beta > 0

random.gauss(mu, sigma)

  高斯分布。 mu 是平均值,sigma 是標准差。 這比下面定義的 normalvariate() 函數略快。

random.lognormvariate(mu, sigma)

  對數正態分布。 如果你采用這個分布的自然對數,你將得到一個正態分布,平均值為 mu 和標准差為 sigma  mu 可以是任何值,sigma 必須大於零。

random.normalvariate(mu, sigma)

  正態分布。 mu 是平均值,sigma 是標准差。

random.vonmisesvariate(mu, kappa)

  馮·米塞斯分布。 mu 是平均角度,以弧度表示,介於0和 2*pi 之間,kappa 是濃度參數,必須大於或等於零。 如果 kappa 等於零,則該分布在 0 到 2*pi 的范圍內減小到均勻的隨機角度。

random.paretovariate(alpha)

  帕累托分布。 alpha 是形狀參數。

random.weibullvariate(alpha, beta)

  威布爾分布。 alpha 是比例參數,beta 是形狀參數。

(2)序列用函數

random.choice(seq)

  從非空序列 seq 返回一個隨機元素。

random.shuffle(x[, random])

  將序列 x 隨機打亂位置。

random.sample(population, k)

  返回從總體序列或集合中選擇的唯一元素的 k 長度列表。 用於無重復的隨機抽樣。

(3)整數用函數

random.randrange(stop)

random.randrange(start, stop[, step])

  從 range(start, stop, step) 返回一個隨機選擇的元素。 這相當於 choice(range(start, stop, step)) ,但實際上並沒有構建一個 range 對象。

random.randint(a, b)

  返回隨機整數 N 滿足<= N <= b。相當於 randrange(a, b+1)。

 random.seed()用法

當seed()沒有參數時,每次生成的隨機數是不一樣的,而當seed()有參數時,每次生成的隨機數是一樣的,同時選擇不同的參數生成的隨機數也不一樣。

(二)numpy(.random.)

beta(a, b[, size])

Draw samples from a Beta distribution.  Beta分布

binomial(n, p[, size])

Draw samples from a binomial distribution.  二項分布  

bytes(length)

Return random bytes.  隨機字節

chisquare(df[, size])

Draw samples from a chi-square distribution.

choice(a[, size, replace, p])

Generates a random sample from a given 1-D array   一維數組生成隨機樣本

dirichlet(alpha[, size])

Draw samples from the Dirichlet distribution.  狄里克萊分布

exponential([scale, size])

Draw samples from an exponential distribution.  指數分布

f(dfnum, dfden[, size])

Draw samples from an F distribution.  F分布

gamma(shape[, scale, size])

Draw samples from a Gamma distribution.  伽馬分布

geometric(p[, size])

Draw samples from the geometric distribution.  幾何分布

get_state()

Return a tuple representing the internal state of the generator.

gumbel([loc, scale, size])

Draw samples from a Gumbel distribution.

hypergeometric(ngood, nbad, nsample[, size])

Draw samples from a Hypergeometric distribution.  超幾何分布

laplace([loc, scale, size])

Draw samples from the Laplace or double exponential distribution with specified location (or mean) and scale (decay).  拉普拉斯或雙指數分布

logistic([loc, scale, size])

Draw samples from a logistic distribution.  Logistic分布

lognormal([mean, sigma, size])

Draw samples from a log-normal distribution.  對數正態分布

logseries(p[, size])

Draw samples from a logarithmic series distribution.

multinomial(n, pvals[, size])

Draw samples from a multinomial distribution.  多項分布

multivariate_normal(mean, cov[, size, …])

Draw random samples from a multivariate normal distribution.  多元正態分布

negative_binomial(n, p[, size])

Draw samples from a negative binomial distribution.  負二項分布

noncentral_chisquare(df, nonc[, size])

Draw samples from a noncentral chi-square distribution.

noncentral_f(dfnum, dfden, nonc[, size])

Draw samples from the noncentral F distribution.

normal([loc, scale, size])

Draw random samples from a normal (Gaussian) distribution.  正態(高斯)分布

pareto(a[, size])

Draw samples from a Pareto II or Lomax distribution with specified shape.

permutation(x)

Randomly permute a sequence, or return a permuted range.

poisson([lam, size])

Draw samples from a Poisson distribution.  泊松分布

power(a[, size])

Draws samples in [0, 1] from a power distribution with positive exponent a - 1.

rand(d0, d1, …, dn)

Random values in a given shape.

randint(low[, high, size, dtype])

Return random integers from low (inclusive) to high (exclusive).  “標准正態”分布

randn(d0, d1, …, dn)

Return a sample (or samples) from the “standard normal” distribution.

random([size])

Return random floats in the half-open interval [0.0, 1.0).

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).  在(0,1)內產生隨機數

ranf()

This is an alias of random_sample.  (同上)

rayleigh([scale, size])

Draw samples from a Rayleigh distribution.

sample()

This is an alias of random_sample.  (同上)

seed(self[, seed])

Reseed a legacy MT19937 BitGenerator

set_state(state)

Set the internal state of the generator from a tuple.

shuffle(x)

Modify a sequence in-place by shuffling its contents.

standard_cauchy([size])

Draw samples from a standard Cauchy distribution with mode = 0.  標准指數

standard_exponential([size])

Draw samples from the standard exponential distribution.

standard_gamma(shape[, size])

Draw samples from a standard Gamma distribution.

standard_normal([size])

Draw samples from a standard Normal distribution (mean=0, stdev=1).  標准正態分布

standard_t(df[, size])

Draw samples from a standard Student’s t distribution with df degrees of freedom.

triangular(left, mode, right[, size])

Draw samples from the triangular distribution over the interval [left, right].

uniform([low, high, size])

Draw samples from a uniform distribution.

vonmises(mu, kappa[, size])

Draw samples from a von Mises distribution.

wald(mean, scale[, size])

Draw samples from a Wald, or inverse Gaussian, distribution.

weibull(a[, size])

Draw samples from a Weibull distribution.

zipf(a[, size])

Draw samples from a Zipf distribution.  齊夫分布

在自然語言的語料庫里,一個單詞出現的頻率與它在頻率表里的排名成反比

 

(轉自CSDN 的思維導圖)

(三)作圖實例

高斯正態分布

import numpy as np
import matplotlib.pyplot as plt
import math
u = 8782  # 均值μ
sig = math.sqrt(2800*2800) # 標准差δ
x = np.linspace(u - 3*sig, u + 3*sig, 500000)
y_sig = np.exp(-(x - u) ** 2 /(2* sig **2))/(math.sqrt(2*math.pi)*sig)
print(x)
print(len(x))
print("="*20)
print(y_sig)
plt.plot(x, y_sig, "r-", linewidth=2)
plt.grid(True)
plt.show()

對數正態分布

import numpy as np
import matplotlib.pyplot as plt
import math,sys
#np.seterr(divide = 'ignore')
u = 0  # 均值μ
sig =2/3 # 標准差δ
x = np.linspace(0.0001,10,100000)
y_sig = np.exp(-(np.log(x)-u) ** 2 /(2* sig **2))/(math.sqrt(2*math.pi)*sig*x)
print(x)
print(x*8000)
print(len(x))
print("="*20)
print(y_sig)
plt.plot(x*8000, y_sig, "r-", linewidth=2)
plt.grid(True)
plt.show()

import numpy as np #導入庫
random3 = np.random.randn(10000) #隨機生成10000個服從正態分布的隨機數
print(random3*8000)
print(len([a for a in random3*8000 if a<8000]))
import matplotlib.pyplot as plt
import seaborn as sns #使用seaborn 庫畫直方圖驗證結果
sns.set_palette("hls") #設置所有圖的顏色,使用hls色彩空間
sns.distplot(random3*8000,color="r",bins=4000,kde=True) #繪制直方圖,color設置顏色,bins設置直方圖的划分數
plt.show() #顯示驗證結果

import numpy as np #導入庫
random3 = np.random.lognormal(0,1/2,500000) #隨機生成服從對數正態分布的隨機數
print(random3*8000)
print(len([a for a in random3*8000 if a<8000]))
import matplotlib.pyplot as plt
import seaborn as sns #使用seaborn 庫畫直方圖驗證結果
sns.set_palette("hls") #設置所有圖的顏色,使用hls色彩空間
sns.distplot(random3*8000,color="r",bins=4000,kde=True) #繪制直方圖,color設置顏色,bins設置直方圖的划分數
plt.show() #顯示驗證結果

 

百度文庫 16種常見概率分布概率密度函數、意義及其應用 

可參考企參數的意義

 


免責聲明!

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



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