NumPy's Random module

Source: Internet
Author: User
Tags shuffle

Documents translated from the official website. Transfer from http://www.mamicode.com/info-detail-507676.html

Random Sampling (Numpy.random) Simple Random data

Rand (D0, D1, ..., DN)

Random values

>>> Np.random.rand (3,2) Array ([[0.14022471,  0.96360618],  #random       [0.37601032,  0.25528411],  #random       [0.49313049,  0.94909878]]) #random

randn (d0 ,  D1, ..., DN)

Returns a sample with a standard normal distribution.

notes

For random samples from , and use:

 sigma * NP.RANDOM.RANDN (...) + mu 
P class= "Rubric" >examples

 >>> np.random.randn () 2.1923875335537315 #random 

Two-by-four Array of samples from N (3, 6.25):

 >>> 2.5 * NP.RANDOM.RANDN (2, 4) + 3array ([[-4.49401501, 4.00950034,-1 .81814867, 7.29718677], #random [0.39924804, 4.68456316, 4.99394529, 4.84057254]]) #random 

Randint (low[, high, size])

Returns a random integer that is located in the half open interval [low, high].

>>> Np.random.randint (2, size=10) array ([1, 0, 0, 0, 1, 1, 0, 0, 1, 0]) >>> np.random.randint (1, size=10) a Rray ([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

Generate a 2 x 4 array of ints between 0 and 4, inclusive:

>>> Np.random.randint (5, Size= (2, 4)) array ([[[4, 0, 2, 1],       [3, 2, 2, 0]])

random_integers (low[, high, size])

Returns a random integer in the closed interval [low, high].

Notes

To sample from N evenly spaced floating-point numbers between A and B, use:

A + (b-a) * (Np.random.random_integers (N)-1)/(N-1.)

Examples

>>> np.random.random_integers (5) 4>>> type (Np.random.random_integers (5)) <type ' int ' >> >> np.random.random_integers (5, Size= (3.,2.)) Array ([[5, 4],       [3, 3],       [4, 5]])

Choose five random numbers from the set of five evenly-spaced numbers between 0 and 2.5, inclusive (i.e., from th E set):

>>> 2.5 * (Np.random.random_integers (5, size= (5,))-1)/4.array ([0.625,  1.25,  0.625,  0.625,  2.5  ])

Roll six sided dice and sum the results:

>>> D1 = np.random.random_integers (1, 6, +) >>> D2 = Np.random.random_integers (1, 6, +) >>& Gt dsums = D1 + d2

Display results as a histogram:

>>> Import Matplotlib.pyplot as plt>>> count, bins, ignored = plt.hist (Dsums, one, normed=true) >>& Gt Plt.show ()

random_sample ([size])

Returns a random floating-point number in the half-open interval [0.0, 1.0].

To sample  multiply the output of Random_sample  by  (b-a)  and add a :

 (b-a) * Random_sample () + a 

Examples

 >>> np.random.random_sample () 0.47108547995356098>>> type (np.random.random_sample ()) <type ' float ' >>>> np.random.random_ Sample ((5,)) array ([0.30220482, 0.86820401, 0.1654503, 0.11659149, 0.54323428]) 

Three-by-two array of random Numbers from [ -5, 0):

 >>> 5 * np.random.random_sample ((3, 2))-5array ([[-3.99149989,-0.52338984], [ -2.99091858, -0.79479508], [ -1.23204345, -1.75224494]]) 

 

Random ([size])

Returns the random floating-point number in the half-open interval [0.0, 1.0].

(The official Website example is exactly the same as Random_sample)

ranf ([size])

Returns the random floating-point number in the half-open interval [0.0, 1.0].

(The official Website example is exactly the same as Random_sample)

Sample ([size])

Returns the random floating-point number in the half-open interval [0.0, 1.0].

(The official Website example is exactly the same as Random_sample)

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

Generate a random sample from a given one-dimensional array

Examples

Generate a uniform random sample from Np.arange (5) of size 3:

>>> Np.random.choice (5, 3) array ([0, 3, 4]) >>> #This is equivalent to Np.random.randint (0,5,3)

Generate a non-uniform random sample from Np.arange (5) of size 3:

>>> Np.random.choice (5, 3, p=[0.1, 0, 0.3, 0.6, 0]) array ([3, 3, 0])

Generate a uniform random sample from Np.arange (5) of size 3 without replacement:

>>> Np.random.choice (5, 3, Replace=false) array ([3,1,0]) >>> #This is equivalent to Np.random.permutation (Np.arange (5)) [: 3]

Generate a non-uniform random sample from Np.arange (5) of size 3 without replacement:

>>> Np.random.choice (5, 3, Replace=false, p=[0.1, 0, 0.3, 0.6, 0]) array ([2, 3, 0])

Any of the above can is repeated with an arbitrary array-like instead of just integers. For instance:

>>> Aa_milne_arr = [' Pooh ', ' Rabbit ', ' piglet ', ' Christopher ']>>> np.random.choice (Aa_milne_arr, 5, p =[0.5, 0.1, 0.1, 0.3]) array ([' Pooh ', ' Pooh ', ' Pooh ', ' Christopher ', ' Piglet '],      dtype= ' | S11 ')

bytes (length)

Returns a random byte.

>>> np.random.bytes ' eh\x85\x022sz\xbf\xa4 ' #random

Arranged

shuffle (x

Modifies the sequence in the field and changes its contents. (Similar shuffle, scrambled order)

 >>> arr = np.arange (+) >>> np.random.shuffle (arr) >>> arr[1 7 5 2 9 4 3 6 0 8] 

 

This function is only shuffles the array along the first index of a multi-dimensional array:

       >>> arr = np.arange (9). Reshape ((3, 3)) >>> np.random.shuffle (arr) >>> Arrarray ([[3, 4, 5], [6, 7, 8], [0, 1, 2]]) 

 

permutation (x)

Returns a random arrangement

>>> np.random.permutation (+) array ([1, 7, 4, 3, 0, 9, 2, 5, 8, 6])
>>> np.random.permutation ([1, 4, 9, A, a]) array ([,  1,  9,  4, 12])
>>> arr = np.arange (9). Reshape ((3, 3)) >>> np.random.permutation (arr) array ([[[6, 7, 8],       [0, 1, 2],< C6/>[3, 4, 5]])

Distribution

Beta (A, b[, size])

Beta distribution sample, within [0, 1] .

binomial (n, p[, size])

Sample of two distributions.

Chisquare (df[, size])

Chi-square distribution samples.

Dirichlet (alpha[, size])

Dirichlet distribution samples.

exponential ([scale, size])

Exponential distribution

F (Dfnum, dfden[, size])

F Distribution Sample.

Gamma (shape[, scale, size])

Gamma distribution

Geometric (p[, size])

Geometric distribution

Gumbel ([Loc, scale, size])

Gumbel distribution.

hypergeometric (Ngood, Nbad, nsample[, size])

hypergeometric distribution Sample.

Laplace ([Loc, scale, size])

Laplace or double exponential distribution sample

Logistic ([Loc, scale, size])

Logistic Distribution Sample

lognormal ([Mean, Sigma, size])

Logarithmic normal distribution

logseries (p[, size])

The distribution of the number of levels.

multinomial (n, pvals[, size])

Multi-item Distribution

Multivariate_normal (mean, cov[, size])

Multivariate normal distribution.

>>> mean = [0,0]>>> cov = [[1,0],[0,100]] # diagonal covariance, points lie on X or Y-axis
>>> Import Matplotlib.pyplot as plt>>> x, y = np.random.multivariate_normal (mean, cov, 5000). T>>> plt.plot (x, Y, ' X '); Plt.axis (' equal '); Plt.show ()

negative_binomial (n, p[, size])

Negative two-item distribution

Noncentral_chisquare (DF, nonc[, size])

Non-central Chi-square distribution

Noncentral_f (Dfnum, Dfden, nonc[, size])

Non-center F distribution

Normal ([Loc, scale, size])

Normal (Gaussian) distribution

Notes

The probability density for the Gaussian distribution is

The where is the mean and the standard deviation. The square of the deviation, is called the variance.

The function has a peak at the mean, and its ' spread ' increases with the standard deviation (the function reaches 0.607 Times its maximum at and [R217]).

Examples

Draw samples from the distribution:

>>> mu, sigma = 0, 0.1 # mean and standard deviation>>> s = Np.random.normal (Mu, Sigma, 1000)

Verify the mean and the variance:

>>> ABS (Mu-np.mean (s)) < 0.01true>>> ABS (SIGMA-NP.STD (S, ddof=1)) < 0.01True

Display the histogram of the samples, along with the probability density function:

>>> Import Matplotlib.pyplot as plt>>> count, bins, ignored = plt.hist (s, A, normed=true) >>> p Lt.plot (bins, 1/(Sigma * NP.SQRT (2 * np.pi)) * ...                Np.exp (-(BINS-MU) **2/(2 * sigma**2)),...          linewidth=2, color= ' R ') >>> Plt.show ()

Pareto (a[, size])

Pareto (Lomax) distribution

Poisson ([Lam, size])

Poisson distribution

Power (a[, size])

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

Rayleigh ([scale, size])

Rayleigh distribution

Standard_cauchy ([size])

Standard Cauchy distribution

standard_exponential ([size])

The standard exponential distribution

Standard_gamma (shape[, size])

Standard Gamma distribution

Standard_normal ([size])

Standard normal distribution (mean=0, stdev=1).

standard_t (df[, size])

Standard Student's t distribution with DF degrees of freedom.

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

Triangular distribution

Uniform ([Low, high, size])

Evenly distributed

vonmises (MU, kappa[, size])

von Mises Distribution

Wald (mean, scale[, size])

Wald (inverse Gaussian) distribution

Weibull (a[, size])

Weibull distribution

Zipf (a[, size])

Zipf distribution
Random number generator

Randomstate

Container for the Mersenne Twister pseudo-random number generator.

seed ([seed])

Seed the generator.

get_state ()

Return a tuple representing the internal state of the generator.

set_state (state)

Set the internal state of the generator from a tuple.

NumPy's Random module

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.