gpt4 book ai didi

python - Numpy 概率

转载 作者:行者123 更新时间:2023-12-01 07:24:05 27 4
gpt4 key购买 nike

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

27 4 0
文章推荐: jquery - 使用 map 限制 jquery ui 自动完成结果的正确方法
文章推荐: jenkins - 我可以在共享库中定义和参数化整个声明性管道吗?
文章推荐: jquery - 从