python - Numpy 概率

标签 python numpy

我只是想知道为什么运行下面的代码时出现错误。我正在尝试使用 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

最佳答案

根据 np.random.choice 的文档它接受一个一维数组或 int 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)

Sample Output

You loot Dynasty bow

关于python - Numpy 概率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57542651/

相关文章:

python - 静态方法和线程安全应用程序

python - 在 Python 中访问计算机麦克风的最简单方法是什么?

python - 停止 QTimer.singleShot() 计时器

python - 绘制 map : Rotating arrows for ocean surface currents

python - 2d 矩阵的 Numpy 矩阵乘法得到 3d 矩阵

python - 用 matplotlib 绘图 : TypeError: float() argument must be a string or a number

python - 隐式推荐系统的K折交叉验证优化

python - Julia >=1.3 和 Python 3.x 中的多线程模型比较

python - 如何在给定代码中运行 if 循环

python - 为什么Numpy的RGB图像阵列具有4层而不是3层?