Python numpy.random.choice:ValueError:p 中的非零条目少于大小

我想根据prob给定行指定的概率分布随机选择样本点。但是,ValueError: Fewer non-zero entries in p than size当我调用np.random.choice. 甚至是什么意思size?我还查看了实现,但我不明白。谢谢你的帮助!!


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



互换的青春
浏览 775回答 1
1回答

侃侃无极

问题在于您使用np.random.choice您要求在 6890 个具有少于 4 个非空值的条目的数组中选择4个条目而不重用值 ( ) ,例如:replace=False>>> 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):&nbsp; File "<input>", line 1, in <module>&nbsp; &nbsp; np.random.choice(5, 4, replace=False, p=[0, 0, 0, 0.6, 0.4])&nbsp; File "mtrand.pyx", line 826, in numpy.random.mtrand.RandomState.choiceValueError: 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 的文档:https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.random.choice.html
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python