【问题标题】:numpy stack to 2d array, select by index from another stacknumpy堆栈到二维数组,从另一个堆栈中按索引选择
【发布时间】:2018-08-22 13:21:29
【问题描述】:

我有两组分类(Lc1Lc2)和两组概率(Lp1Lp2)。 Lp1 是描述Lc1 中分类可能性的概率集。我想使用最可能的分类将Lc1Lc2 中的信息组合成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)

我最初的方法是为分类和概率集创建一个np.stack,并使用np.argmax 查找最大值出现在p_stack 中的轴索引。 np.take 的文档似乎描述了我需要做的操作,但我不明白为什么它返回一个数组。有没有办法通过指定我要选择的值的轴来减少np.stack 的维度?

我想要的结果是:

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

【问题讨论】:

    标签: python arrays numpy indexing


    【解决方案1】:

    在您的情况下,ìndex 指的是第一个维度,您需要为其他维度创建升序索引。

    如果你手动编写它们看起来像

    dim_1 = np.array([[0, 0],
                      [1, 1]])
    
    
    dim_2 = np.array([[0, 1],
                      [0, 1]])
    
    print(c_stack[index, dim_1, dim_2])
    

    您可以使用np.arangenp.vstacknp.hstacknp.tilenp.column_stack 自动创建它们。有几种方法可以做到这一点。

    例如

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

    这种技术在 Numpy 中称为"Integer array indexing"

    【讨论】:

    • 你提供的这个链接很有帮助。
    • 我知道,我每天都会访问它,因为我一直忘记它是如何工作的 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 2012-03-11
    • 1970-01-01
    • 2020-10-12
    • 1970-01-01
    • 2022-10-17
    • 2013-12-26
    相关资源
    最近更新 更多