简体   繁体   English

Numpy select 索引随机

[英]Numpy select index randomly

I have a numpy array that is like this我有一个像这样的 numpy 数组

arr = np.random.randint(2, size=(32, 4, 19))

and I want to output a random index for arr that is equal to 1 in respect to axis=2 .我想 output arr的随机索引,相对于axis=2等于 1 。 So I want to return an array that is of shape (32, 4, 1) consisting of a random index that is 1. For example, say the first few rows of the array looks like this所以我想返回一个形状为(32, 4, 1)的数组,该数组由一个随机索引为 1 组成。例如,假设数组的前几行看起来像这样

array([[[0, 1, 0, ..., 0, 1, 1],
        [0, 0, 1, ..., 1, 1, 0],
        [0, 0, 0, ..., 1, 0, 0],
        [0, 0, 1, ..., 0, 0, 0]],
        ...
       [[0, 1, 1, ..., 1, 1, 1],
        [1, 0, 1, ..., 0, 1, 0],
        [1, 1, 0, ..., 1, 0, 0],
        [0, 0, 0, ..., 0, 1, 1]]])

I want to get something like我想得到类似的东西

array([[[1],[17],[16],[5]], 
       [[3], ...
        ....
       [[7],[4],[7],[11]]]) 

since arr[0,0,1] == 1 and arr[0,1,17] == 1 etc. Can someone please help me因为arr[0,0,1] == 1arr[0,1,17] == 1等等。有人可以帮帮我吗

Assuming you have at least one 1 per vector on axis 2, you can multiply each item by a random value and get the argmax , then reshape to add an extra dimension:假设您在轴 2 上每个向量至少有一个 1,您可以将每个项目乘以一个随机值并获得argmax ,然后重新整形以添加一个额外的维度:

np.argmax(arr*np.random.random(size=arr.shape), axis=2)[...,None]

Example output:示例 output:

[[[ 6], [ 7], [ 9], [ 5]],
 [[10], [15], [13], [16]],
 [[ 1], [ 9], [ 3], [16]],
 [[ 0], [18], [14], [ 0]],
 [[10], [14], [ 1], [11]],
...
]

NB.注意。 If the last dimension (19) is extremely large, you might have a bias towards lower indices in case twice the same random value is generated ( argmax will pick the first max), but this is extremely unlikely and will still give a correct result.如果最后一个维度 (19) 非常大,您可能会偏向较低的索引,以防生成两次相同的随机值( argmax将选择第一个最大值),但这极不可能并且仍然会给出正确的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM