【问题标题】:Numpy probabilities麻木概率
【发布时间】:2019-08-18 07:47:40
【问题描述】:

我只是想知道为什么运行下面的代码会出错。我正在尝试使用 numpy 为基于文本的游戏做概率。下面的代码不是游戏本身的代码。这仅用于测试目的和学习。提前感谢您的回答,请对我放轻松。

from numpy.random import choice

class container:

    def __init__(self):
        self.inv = {'common': ['blunt sword', 'blunt axe'], 'uncommon': ['Dynasty bow', 'Axe', 'Sword'], 'rare': ['Sharp axe'], 'epic': ['Great Sword']}
        self.probabilities = {"common": 50, 'uncommon':25, 'rare': 10, 'epic': 3}
        self.item = choice(self.inv(choice(self.probabilities.keys(), p=self.probabilities.values())))

    def open(self):
        return f'You loot {self.item}'


loot = container().open()
print(loot)

错误:

Traceback (most recent call last):
  File "mtrand.pyx", line 1115, in mtrand.RandomState.choice
TypeError: 'dict_keys' object cannot be interpreted as an integer

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "test.py", line 14, in <module>
    loot = container().open()
  File "test.py", line 8, in __init__
    self.item = choice(self.inv(choice(self.probabilities.keys(), p=self.probabilities.values())))
  File "mtrand.pyx", line 1117, in mtrand.RandomState.choice
ValueError: 'a' must be 1-dimensional or an integer

【问题讨论】:

  • 嗨,@Johny,如果您认为以下答案是合适的,我恳请您接受它作为经过验证的答案,因为它可以帮助其他可能在未来研究此问题的用户

标签: python numpy


【解决方案1】:

根据np.random.choice 的文档,它采用一维数组或整数a 和一个概率向量p,其长度等于a 的长度并且总和为1。在您的情况下,您正在喂养probabilities.keys()inv.keys(),它们的类型为dict_keys。此外,您的概率向量之和不等于 1。将概率向量转换为所需格式的一种方法是将其除以它的总和。我已经对代码进行了必要的更改

from numpy.random import choice

class container:

def __init__(self):
    self.inv = {'common': ['blunt sword', 'blunt axe'], 'uncommon': ['Dynasty bow', 'Axe', 'Sword'], 'rare': ['Sharp axe'], 'epic': ['Great Sword']}
    self.probabilities = {"common": 50, 'uncommon':25, 'rare': 10, 'epic': 3}
    self.convert_prob_vector()
    self.item = choice(self.inv[choice(list(self.probabilities.keys()), p=self.probabilities_new)])

def convert_prob_vector(self):
    self.probabilities_new = [x / sum(self.probabilities.values()) for x in self.probabilities.values()]
def open(self):
    return f'You loot {self.item}'


loot = container().open()
print(loot)

样本输出

你掠夺王朝弓

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-11
    • 1970-01-01
    • 2011-05-24
    相关资源
    最近更新 更多