【问题标题】:Generating numbers with unequal probability以不等概率生成数字
【发布时间】:2015-01-25 06:52:25
【问题描述】:

事情就是这样。

我想以不同的概率生成两个值,1 和 -1。 当我运行这个脚本时,我收到消息“choice() got an unexpected keyword argument 'p'”

谁能告诉我为什么会发生这种情况以及如何解决它? 谢谢。

from scipy import *
import matplotlib.pyplot as plt
import random as r

def ruin_demo():


    tmax = 1000       #The number of game rounds
    Xi = 10           #The initial money the gambler has
    T = []
    M = []
    t = 1
    for N in linspace(0.3, 0.49, 100):     #The probability changing region

        meandeltaX = 1.0*N + (1-N)*(-1.0)  #The expected value for each game round
        M.append(meandeltaX)
        while (t < tmax and Xi > 0):

            deltaX  = r.choice((1, -1), p=[N, 1-N]) # The change of money during each game round
                #print deltaX
            Xi = Xi + deltaX
            t = t + 1
        T.append(t)
    plt.plot(M, T)
    plt.show()

ruin_demo()

【问题讨论】:

    标签: python python-2.7 random


    【解决方案1】:

    您收到消息TypeError: choice() got an unexpected keyword argument 'p' 是因为random.choice(Python 标准库函数)没有关键字参数p

    可能你的意思是numpy.random.choice

    >>> numpy.random.choice((1,-1), p=[0.2, 0.8])
    -1
    

    您可以通过将import random as r 更改为import numpy.random as r 来修复您的代码,但是使用非标准的单字母名称来引用一个重要的模块只会让事情变得更加混乱。常规缩写是

    import numpy as np
    

    之后np.random.choice 工作。


    现在诚然因为scipy 导入了numpy 的一部分,您可以通过它访问numpy.random,但是您的线路

    from scipy import *   # <-- don't do this! 
    

    应该避免。它使用行为不同的 numpy 版本破坏标准 Python 函数,并且在某些情况下给出相反的答案。

    【讨论】:

    • 感谢您的回答。我尝试在终端中运行 import numpy as np 和 numpy.random.choice((1,-1), p=[0.2, 0.8]) ,我收到消息“模块对象没有属性'选择”为什么会发生这种情况?
    • @epx 你的 numpy 版本是什么?
    • @skyline75489 谢谢。我之前的 numpy 版本是 1.6.1。我只是将它升级到 1.9.1,这就解决了问题。
    猜你喜欢
    • 2017-10-01
    • 2016-01-26
    • 1970-01-01
    • 2012-01-10
    • 2016-01-06
    • 1970-01-01
    • 2013-07-29
    • 2017-03-24
    • 2013-12-06
    相关资源
    最近更新 更多