Break_tie_randomly

np.argmax()返回 arr 中第一个最大元素的下标,但是有时候需要在最大元素中随机选择一个.

1
np.random.choice(np.flatnonzero(b == b.max()))
  • b==b.max() will return an array of booleans, with values of true where items are max and values of false for other items.
  • flatnonzero() will do two things: ignore the false values (nonzero part) then return indices of true values. In other words, you get an array with indices of items matching the max value.
  • Finally, you pick a random index from the array.

发现还是很慢,不如手写版本

1
2
3
4
def random_argmax(value_list):
""" a random tie-breaking argmax """
values = np.asarray(value_list)
return np.argmax(np.random.random(values.shape) * (values==values.max()))