繁体   English   中英

numpy 3d张量乘2d数组

[英]numpy 3d tensor by 2d array

我有一个稀疏矩阵。 我知道每一列都有两个非零值 ,因此我想使用定义为置换矩阵列表的张量来压缩 (去除零)。

我有

src = np.array([[2, 9, 0, 2, 4],
                [0, 1, 8, 8, 0],
                [1, 0, 3, 0, 0],
                [0, 0, 0, 0, 7]])

而且我要

trg = np.array([[2, 9, 8, 2, 4],
                [1, 1, 3, 8, 7]])

这是相同的矩阵,但没有零。

我已经对选择非零值的张量进行了硬编码

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

我可以遍历psrc来获取trg

>>> for i in range(len(p)):
>>>    print(p[i] @ src[:,i])

[2 1]
[9 1]
[8 3]
[2 8]
[4 7]

我怎样才能做到这一点的numpy的方式 (即没有循环)? 我尝试过tensordot并在没有运气的情况下转置了矩阵。

由于行优先排序,我们可以使用转置版本使用非零掩码对数组进行index ,然后重塑-

out = src.T[src.T!=0].reshape(src.shape[1],-1).T

样品运行-

In [19]: src
Out[19]: 
array([[2, 9, 0, 2, 4],
       [0, 1, 8, 8, 0],
       [1, 0, 3, 0, 0],
       [0, 0, 0, 0, 7]])

In [20]: src.T[src.T!=0].reshape(src.shape[1],-1).T
Out[20]: 
array([[2, 9, 8, 2, 4],
       [1, 1, 3, 8, 7]])

使用np.where的解决方案:

src[np.where(src.T)[::-1]].reshape(2, -1, order='F')

这是发生了什么:

  • np.where通过转置给出非零元素的索引,这样它们就可以正确排序而无需采取进一步措施,
  • [::-1]反转顺序,因为由于转置,行和列索引被交换,
  • 应用高级索引来获取元素,
  • 最后,重塑。

输出:

array([[2, 9, 8, 2, 4],
       [1, 1, 3, 8, 7]])

您可以使用遮罩:

mask = src != 0
src[mask] #array without the zeroes but 1d
n_cols = src.shape[1]
tgt = src[mask].reshape(-1,n_cols)

此方法需要将1d数组重塑为2d,我决定保留相同数量的列,但在某些情况下,您的数组可能对2d不太满意。

这是一种方法:

import numpy as np

src = np.array([[2, 9, 0, 2, 4],
                [0, 1, 8, 8, 0],
                [1, 0, 3, 0, 0],
                [0, 0, 0, 0, 7]])
# Masked indices of non-zero positions
idx = np.arange(len(src))[:, np.newaxis] * (src != 0)
# Sort to and pick valid indices at the end
idx = np.sort(idx, axis=0)[-2:]
# Get values
trg = src[idx, np.arange(src.shape[1])]
print(trg)

输出:

[[2 9 8 2 4]
 [1 1 3 8 7]]

暂无
暂无

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

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