gpt4 book ai didi

Python numpy.random.choice : ValueError: Fewer non-zero entries in p than size

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

我想根据给定行的 prob 指定的概率分布随机选择样本点。但是,当我调用np.random.choice时,我收到错误ValueError:p中非零条目少于大小size 到底是什么意思?我还看了implementation但我不明白。谢谢你的帮助!!

import numpy as np

# prob is a numpy array of shape (14, 6890)
all_zero = np.where(prob.max(1) < 1e-6)[0] # find indices of rows where all values are smaller
prob[all_zero] = 1 / prob.shape[1] # fill those rows uniformly
prob /= prob.sum(axis=1, keepdims=True)
# ... somewhere later inside a method
for j in range(14):
sample = np.random.choice(6890, 4, replace=False, p=prob[j]) # error occurs here

最佳答案

问题出在您使用 np.random.choice 时,您要求选择 4 个条目而不重用值 (replace=False)在包含 6890 个条目的数组中非空值少于 4 个,例如:

>>> np.random.choice(5, 1, replace=False, p=[0, 0, 0, 0.6, 0.4])
array([4])

>>> np.random.choice(5, 4, replace=False, p=[0, 0, 0, 0.6, 0.4])
Traceback (most recent call last):
File "<input>", line 1, in <module>
np.random.choice(5, 4, replace=False, p=[0, 0, 0, 0.6, 0.4])
File "mtrand.pyx", line 826, in numpy.random.mtrand.RandomState.choice
ValueError: Fewer non-zero entries in p than size

>>> np.random.choice(5, 4, replace=True, p=[0, 0, 0, 0.6, 0.4])
array([3, 3, 4, 3])

因此解决方案取决于您的需要,您要么确保有更多的非空值,要么在随机选择中启用替换。

作为引用,numpy.random.choice 的文档:

关于Python numpy.random.choice : ValueError: Fewer non-zero entries in p than size,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57890844/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com