在numpy.argmax函数中,多个max元素之间的领带断裂使得第一个元素被返回。是否有随机破坏领带的功能,使所有的最大数目都有相同的机会被选中?
下面是直接来自numpy.argmax文档的一个示例。
>>> b = np.arange(6)
>>> b[1] = 5
>>> b
array([0, 5, 2, 3, 4, 5])
>>> np.argmax(b) # Only the first occurrence is returned.
1我正在寻找方法,以便列表中的第1和第5元素以相同的概率返回。
谢谢!
发布于 2017-02-06 15:40:33
使用np.random.choice -
np.random.choice(np.flatnonzero(b == b.max()))让我们来验证一个有三个最大候选的数组-
In [298]: b
Out[298]: array([0, 5, 2, 5, 4, 5])
In [299]: c=[np.random.choice(np.flatnonzero(b == b.max())) for i in range(100000)]
In [300]: np.bincount(c)
Out[300]: array([ 0, 33180, 0, 33611, 0, 33209])发布于 2017-03-29 20:14:59
在多维数组的情况下,choice不能工作。
另一种选择是
def randargmax(b,**kw):
""" a random tie-breaking argmax"""
return np.argmax(np.random.random(b.shape) * (b==b.max()), **kw)如果由于某种原因产生随机浮点数比其他方法慢,则可以用另一种方法代替random.random。
发布于 2019-10-10 05:03:46
最简单的方法是
np.random.choice(np.where(b == b.max())[0])https://stackoverflow.com/questions/42071597
复制相似问题