【问题标题】:Using numpy.random.normal with arrays将 numpy.random.normal 与数组一起使用
【发布时间】:2018-08-17 08:34:12
【问题描述】:

假设我有以下两个具有均值和标准差的数组:

mu = np.array([2000, 3000, 5000, 1000])
sigma = np.array([250, 152, 397, 180])

然后:

a = np.random.normal(mu, sigma)

In [1]: a
Out[1]: array([1715.6903716 , 3028.54168667, 4731.34048645, 933.18903575])

但是,如果我要求对 mu、sigma 的每个元素进行 100 次抽奖:

a = np.random.normal(mu, sigma, 100)

a = np.random.normal(mu, sigma, 100)
Traceback (most recent call last):

File "<ipython-input-417-4aadd7d15875>", line 1, in <module>
a = np.random.normal(mu, sigma, 100)

File "mtrand.pyx", line 1652, in mtrand.RandomState.normal

File "mtrand.pyx", line 265, in mtrand.cont2_array

ValueError: shape mismatch: objects cannot be broadcast to a single shape

我也尝试过使用元组来表示大小:

s = (100, 100, 100, 100)
a = np.random.normal(mu, sigma, s)

我错过了什么?

【问题讨论】:

    标签: python arrays python-3.x numpy


    【解决方案1】:

    我不相信您可以在传递均值和标准值的列表/向量时控制大小参数。相反,您可以遍历每一对,然后连接:

    np.concatenate(
       [np.random.normal(m, s, 100) for m, s in zip(mu, sigma)]
    ) 
    

    这会给你一个(400, ) 数组。如果您想要一个(4, 100) 数组,请调用np.array 而不是np.concatenate

    【讨论】:

    • 谢谢。这也是我的猜测,因为文档对此并不清楚。我希望我可以避免使用 for 循环进行迭代。
    • @user177324 好吧,你可以“避免使用 for 循环”,是的:np.array(list(map(np.random.normal, mu, sigma, [100] * len(mu))))。但是如果你想知道如何避免多次调用该函数,我认为可能是不可能的。
    • 谢谢,这确实很有帮助。我只是有点担心,如果我必须这样做 10000 次 for 循环会慢得多。
    • @user177324 是的,如果你想生成 100 万个随机数,循环确实会很慢!
    【解决方案2】:

    如果您只想进行一次调用,则正态分布很容易在事后进行移动和重新调整。 (我正在从您的示例中组成一个 10000 长的 musigma 向量):

    mu = np.random.choice([2000., 3000., 5000., 1000.], 10000)               
    sigma = np.random.choice([250., 152., 397., 180.], 10000)
    
    a = np.random.normal(size=(10000, 100)) * sigma[:,None] + mu[:,None]
    

    这很好用。您可以决定速度是否是一个问题。在我的系统上,以下只是慢了 50%:

    a = np.array([np.random.normal(m, s, 100) for m,s in zip(mu, sigma)])
    

    【讨论】:

    • 这是一个很好的答案!添加一些关于为什么这样做的信息(数学上),这是一个完美的答案。
    猜你喜欢
    • 2017-03-19
    • 2015-10-05
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多