【问题标题】:numpy, how to generate a normally distributed set of integersnumpy,如何生成一组正态分布的整数
【发布时间】:2016-01-14 14:38:00
【问题描述】:

numpy 生成一组正态分布整数的最佳方法是什么?我知道我可以用这样的东西得到花车:

In [31]: import numpy as np

In [32]: import matplotlib.pyplot as plt

In [33]: plt.hist(np.random.normal(250, 1, 100))
Out[33]: 
(array([  2.,   5.,   9.,  10.,  19.,  21.,  13.,  10.,   6.,   5.]),
 array([ 247.52972483,  247.9913017 ,  248.45287858,  248.91445546,
         249.37603233,  249.83760921,  250.29918608,  250.76076296,
         251.22233984,  251.68391671,  252.14549359]),
 <a list of 10 Patch objects>)

【问题讨论】:

  • 除非你真的需要高精度,否则我只会对浮点数进行四舍五入。
  • 好的,就像这样:np.random.normal(250, 1, 100).round(0)?
  • 如果您需要实际整数:np.random.normal(250, 1, 100).round().astype(np.int)。 (0 是 np.round 的默认值,顺便说一句。)
  • 你可以在浮点数之上绘制整数分布,看看你是否满意。
  • @Evert 在这种情况下,“高精度”意味着什么?根据定义,正态分布是连续的。

标签: python numpy statistics scipy


【解决方案1】:

很久以后才遇到这个问题,但是如果您想生成一组任意分布的整数,请使用逆 CDF(百分位数)作为关联分布,例如,scipy.stats 并从中统一绘制百分位数.然后只需转换为整数即可:

from scipy.stats import norm
import matplotlib.pyplot as plt
import numpy as np
# Generate 10000 normal random integers with specified mean (loc) and std (scale).
draw = norm.ppf(np.random.random(10000), loc=0, scale=100).astype(int)
plt.hist(draw, bins=20)

continuous distributions in scipy.stats can be found here列表,discrete distributions can be found here列表。

对于上面的示例,您可以直接从您想要的分布中提取并转换为整数,但是这种方法的好处(从 CDF 中统一采样百分位数)是它适用于任何分布,即使是你只能从数据中定义数字!

【讨论】:

    【解决方案2】:

    Binomial Distribution 是正态分布的良好离散近似值。即,

    Binomial(n, p) ~ Normal(n*p, sqrt(n*p*(1-p)))
    

    所以你可以这样做

    import numpy as np
    import matplotlib.pyplot as plt
    from math import sqrt
    
    bi = np.random.binomial(n=100, p=0.5, size=10000)
    n = np.random.normal(100*0.5, sqrt(100*0.5*0.5), size=10000)
    
    plt.hist(bi, bins=20, normed=True);
    plt.hist(n, alpha=0.5, bins=20, normed=True);
    plt.show();
    

    【讨论】:

    • 太好了,谢谢。我想这让我意识到我(此时)不太关心分布的细节,但更感兴趣的是如何获得一组符合除@提供的默认(均匀)分布之外的任何分布的整数987654326@
    • 这不会生成任何低于 30 和高于 70 的样本吗?
    猜你喜欢
    • 2016-09-21
    • 2016-09-13
    • 2021-10-13
    • 1970-01-01
    • 2017-08-21
    • 2010-11-21
    • 2014-11-06
    • 2016-07-12
    • 2020-06-18
    相关资源
    最近更新 更多