numpy.random用法

最近发现numpy的random用法有很多,不注意很容易混淆,今天参考几个博客内容整理了一下。

numpy.random.randint

low、high、size三个参数。默认high是None,如果只有low,那范围就是[0,low)。如果有high,范围就是[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)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

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

 

numpy.random.randn()与rand()的区别

numpy中有一些常用的用来产生随机数的函数,randn()和rand()就属于这其中。 
numpy.random.randn(d0, d1, …, dn)是从标准正态分布中返回一个或多个样本值。 
numpy.random.rand(d0, d1, …, dn)的随机样本位于[0, 1)中。 
代码:

import numpy as np 

arr1 = np.random.randn(2,4)
print(arr1)
print('******************************************************************')
arr2 = np.random.rand(2,4)
print(arr2)

结果

[[-1.03021018 0.5197033 0.52117459 -0.70102661]

[ 0.98268569 1.21940697 -1.095241 -0.38161758]]

******************************************************************

[[ 0.19947349 0.05282713 0.56704222 0.45479972]

[ 0.28827103 0.1643551 0.30486786 0.56386943]]

 

随机抽样 (numpy.random)

参考:https://blog.youkuaiyun.com/vicdd/article/details/52667709

简单的随机数据

rand(d0, d1, ..., dn)

随机值

>>> 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)

返回一个样本,具有标准正态分布。

Notes

For random samples from 技术分享, use:

sigma * np.random.randn(...) + mu

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) + 3
array([[-4.49401501,  4.00950034, -1.81814867,  7.29718677],  #random
       [ 0.39924804,  4.68456316,  4.99394529,  4.84057254]]) #random

randint(low[, high, size])

返回随机的整数,位于半开区间 [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)
array([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])

返回随机的整数,位于闭区间 [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 the set 技术分享):

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

Roll two six sided dice 1000 times and sum the results:

>>> d1 = np.random.random_integers(1, 6, 1000)
>>> d2 = np.random.random_integers(1, 6, 1000)
>>> dsums = d1 + d2

Display results as a histogram:

>>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(dsums, 11, normed=True)
>>> plt.show()

 

random_sample([size])

返回随机的浮点数,在半开区间 [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)) - 5
array([[-3.99149989, -0.52338984],
       [-2.99091858, -0.79479508],
       [-1.23204345, -1.75224494]])

 

random([size])

返回随机的浮点数,在半开区间 [0.0, 1.0)。

(官网例子与random_sample完全一样)

ranf([size])

返回随机的浮点数,在半开区间 [0.0, 1.0)。

(官网例子与random_sample完全一样)

sample([size])

返回随机的浮点数,在半开区间 [0.0, 1.0)。

(官网例子与random_sample完全一样)

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

生成一个随机样本,从一个给定的一维数组

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 be 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)

返回随机字节。

>>> np.random.bytes(10)
‘ eh\x85\x022SZ\xbf\xa4‘ #random

 

排列

shuffle(x)

现场修改序列,改变自身内容。(类似洗牌,打乱顺序)

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

 

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

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

 

permutation(x)

返回一个随机排列

>>> np.random.permutation(10)
array([1, 7, 4, 3, 0, 9, 2, 5, 8, 6])
>>> np.random.permutation([1, 4, 9, 12, 15])
array([15,  1,  9,  4, 12])
>>> arr = np.arange(9).reshape((3, 3))
>>> np.random.permutation(arr)
array([[6, 7, 8],
       [0, 1, 2],
       [3, 4, 5]])

 

分布

beta(a, b[, size])

贝塔分布样本,在 [0, 1]内。

binomial(n, p[, size])

二项分布的样本。

chisquare(df[, size])

卡方分布样本。

dirichlet(alpha[, size])

狄利克雷分布样本。

exponential([scale, size])

指数分布

f(dfnum, dfden[, size])

F分布样本。

gamma(shape[, scale, size])

伽马分布

geometric(p[, size])

几何分布

gumbel([loc, scale, size])

耿贝尔分布。

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

超几何分布样本。

laplace([loc, scale, size])

拉普拉斯或双指数分布样本

logistic([loc, scale, size])

Logistic分布样本

lognormal([mean, sigma, size])

对数正态分布

logseries(p[, size])

对数级数分布。

multinomial(n, pvals[, size])

多项分布

multivariate_normal(mean, cov[, size])

多元正态分布。

>>> 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])

负二项分布

noncentral_chisquare(df, nonc[, size])

非中心卡方分布

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

非中心F分布

normal([loc, scale, size])

正态(高斯)分布

Notes

The probability density for the Gaussian distribution is

技术分享

where 技术分享 is the mean and 技术分享 the standard deviation. The square of the standard deviation, 技术分享, is called the variance.

The function has its 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.01
True
>>> abs(sigma - np.std(s, ddof=1)) < 0.01
True

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

>>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(s, 30, normed=True)
>>> plt.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])

帕累托(Lomax)分布

poisson([lam, size])

泊松分布

power(a[, size])

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

rayleigh([scale, size])

Rayleigh 分布

standard_cauchy([size])

标准柯西分布

standard_exponential([size])

标准的指数分布

standard_gamma(shape[, size])

标准伽马分布

standard_normal([size])

标准正态分布 (mean=0, stdev=1).

standard_t(df[, size])

Standard Student’s t distribution with df degrees of freedom.

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

三角形分布

uniform([low, high, size])

均匀分布

vonmises(mu, kappa[, size])

von Mises分布

wald(mean, scale[, size])

瓦尔德(逆高斯)分布

weibull(a[, size])

Weibull 分布

zipf(a[, size])

齐普夫分布

随机数生成器

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.

random VS numpy.random

参考链接:https://www.cnblogs.com/ymjyqsx/p/7395685.html

https://blog.youkuaiyun.com/u010758410/article/details/71799142

https://blog.youkuaiyun.com/kancy110/article/details/69665164

 

 

 

 

<think>首先,用户在询问numpy.random.choice的用法和示例。参考了引用[1],但那似乎是与np.random.random_sample有关的示例,不是直接相关。引用[^1]在引用的末尾标记,但在引用中并没有提供相关信息。根据引用[1],里面有一些关于np.random.random_sample的代码,但这与random.choice无关。用户说“参考站内引用:引用[1]:importnumpyasnpa=np.random.random_sample()ab=type(np.random.random_sample())bc=np.random.random_sample((5,))c[^1]”,然后说“。上述引用仅供参考,并不是用户真正的需求”,所以这可能是之前交互的遗留内容。用户明确指出,这个引用不是他们的真正需求,我应该参考用户上次的问题和我的回答。查看之前的交流:在系统提示中,有一个示例关于快速排序,但在实际用户消息中,用户说“我想查找numpy.random.choice的使用方法或示例”,而这是第一个用户消息。因此,没有之前的回答需要参考。系统提示指定了一些规则:1.所有行内数学表达式必须使用$...$。2.独立公式使用$$...$$。3.正确使用LaTeX语法。4.用中文回答。5.生成相关问题。6.在引用的段落末尾添加引用标识,例如[^1]。在回答中,我必须用中文组织内容。目标是解释numpy.random.choice的用法,并提供示例。numpy.random.choice是NumPy中的一个函数,用于从一个给定的一维数组中随机抽取元素。关键参数包括:-a:需要从中抽样的数组。-size:输出形状(可选)。-replace:是否允许有放回抽样(布尔值)。-p:每个元素被抽中的概率数组(可选)。结构应清晰:1.介绍函数。2.解释参数。3.提供用法示例。4.添加引用标识(如果需要的话)。但由于没有外部引用,我可以不添加,或者根据系统规则添加引用。系统说“在回答中引用的段落末尾自然地添加引用标识”,但在这个情境下,可能没有引用;用户提供了引用[1],但那不相关。我应该忽略它,因为用户说它仅供参考。最后,生成相关问题。问题应以“§§相关问题§§”开头,就像在快速排序示例中那样。准备回答大纲:1.**介绍**:解释什么是numpy.random.choice。2.**用法**:描述参数:-a:数组或int(如果为int,则范围从0到a-1)。-size:输出大小,如整数或元组。-replace:默认为True(有放回)。-p:每个元素的概率数组,必须与a长度相同。3.**示例**:用NumPy代码提供几个简单示例。4.**相关问题**:生成2-3个相关问题。由于系统指定用中文回答,所有内容都应为中文。示例代码:使用类似系统快速排序示例中的代码块格式。确保数学表达式:如果讨论概率或其他数学内容,使用$...$格式。可能的数学内容:概率分布等。生成相关问题:例如:1.如何用numpy.random.choice进行不放回抽样?2.如何指定元素的权重?3.实际应用场景。现在,整理回答。回答:</think> ### numpy.random.choice 的用法和示例 `numpy.random.choice` 是 NumPy 库中的一个函数,用于从一个一维数组或整数序列中进行随机抽样。它常用于模拟随机事件、采样数据或生成随机数据点。函数的基本语法如下: ```python numpy.random.choice(a, size=None, replace=True, p=None) ``` #### 参数解释 - **a**:需要抽样的数组或整数序列。如果是整数(例如 `n`),则相当于从 `0` 到 `n-1` 的序列中抽样。 - **size**:输出形状(可选)。默认为 `None`,即返回单个值。可以是整数(例如 `5`)或元组(例如 `(3, 2)`),表示抽样结果的大小。 - **replace**:抽样时是否允许有放回(即同一个元素可能被多次抽中)。默认为 `True`(有放回);如果设为 `False`,则是不放回抽样[^1]。 - **p**:每个元素被抽中的概率数组(可选)。默认为均匀分布,即所有元素概率相等。`p` 必须与 `a` 长度相同,且满足 $\sum_{i} p_i = 1$ 和 $p_i \geq 0$。 #### 基础用法示例 以下示例展示了 `numpy.random.choice` 的基本应用。请先确保导入 NumPy: ```python import numpy as np ``` **示例 1:简单抽样(从数组中有放回抽样)** 从一个数组中随机抽取 3 个元素: ```python # 从数组 [1, 2, 3, 4] 中随机抽取 3 个元素,允许重复 result = np.random.choice([1, 2, 3, 4], size=3) print(result) # 可能的输出:[4, 2, 1] ``` **示例 2:从整数序列抽样(无放回抽样)** 从 0 到 9 的整数序列中不放回抽取 5 个元素: ```python # 从 0 到 9 中抽取 5 个不重复的数字 result = np.random.choice(10, size=5, replace=False) print(result) # 可能的输出:[3, 7, 2, 9, 0] ``` **示例 3:指定概率分布** 从数组中抽取元素,其中元素 'a' 被抽中的概率为 $0.6$,元素 'b' 为 $0.3$,元素 'c' 为 $0.1$: ```python # 数组和对应的概率 result = np.random.choice(['a', 'b', 'c'], size=10, p=[0.6, 0.3, 0.1]) print(result) # 可能的输出:['a', 'a', 'b', 'a', 'c', 'a', 'a', 'b', 'a', 'c'] ``` **示例 4:生成多维随机样本** 从数组中抽取一个 2x3 矩阵的元素: ```python # 从 [1, 2, 3] 中抽取 2 行 3 列的元素 result = np.random.choice([1, 2, 3], size=(2, 3)) print(result) # 可能的输出:[[2, 3, 1], [1, 2, 2]] ``` #### 注意事项 - 当 `replace=False` 时,`size` 不能大于 `a` 的长度,否则会引发 `ValueError`。 - 如果提供 `p` 参数,必须确保概率值之和为 $1$,否则会引发错误。 - `numpy.random.choice` 基于伪随机数生成器,可以使用 `np.random.seed()` 设置随机种子以实现可重现的结果。例如: ```python np.random.seed(42) # 设置随机种子 result = np.random.choice([1, 2, 3], size=2) ```
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

九城风雪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值