numpy stack to 2d array, select by index from another stack

半世苍凉 提交于 2019-12-24 18:49:50

问题


I have two sets of classifications (Lc1 and Lc2) and two sets of probabilities (Lp1 and Lp2). Lp1 is the set of probabilities that describes the classification likelihood in Lc1. I want to combine the information in Lc1 and Lc2 using the classifications that are the most probable into class_result.

import numpy as np

#example data
Lp1 = np.ones((2,2))*0.5
Lc2 = np.ones((2,2))

Lc1 = np.ones((2,2))
Lp2 = np.ones((2,2))*0.5

#Change some values for the example
Lp1[1,1] =0.95
Lc1[1,1] = 0

Lc2[0,1]=3
Lp2[0,1]=.95

p_stack = np.stack((Lp1,Lp2))
c_stack = np.stack((Lc1,Lc2))

index = np.argmax(p_stack, axis=2)

class_result = np.take(c_stack, index)

My initial approach is to create a np.stack for the sets of classifications and probabilities and use np.argmax to find the axis index where the maximum value occurs in p_stack. The docs for np.take seem to describe the operation I need to do, but I don't understand why it returns an array with ones. Is there a way to reduce the dimensionality of a np.stack by specifying the axis of the value I want to select?

My desired result is:

class_result = np.array([[1,3],[1,0]])

回答1:


In your case ìndex refers to the first dimension, and you need to create ascending indices for the other dimensions.

If you write them manually it looks like

dim_1 = np.array([[0, 0],
                  [1, 1]])


dim_2 = np.array([[0, 1],
                  [0, 1]])

print(c_stack[index, dim_1, dim_2])

You can create them automatically using np.arange, np.vstack, np.hstack and np.tile, np.column_stack. There are several ways to do this.

E.g.

x = np.arange(5)

a = np.tile(x, (5, 1))
b = np.column_stack(tuple(a))
print(a)
print(b)

This technique in Numpy is called "Integer array indexing".



来源:https://stackoverflow.com/questions/51967890/numpy-stack-to-2d-array-select-by-index-from-another-stack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!