在numpy中将列矩阵行添加到列中

问题描述 投票:1回答:1

假设我有两个尺寸的3D矩阵/张量:

[10, 3, 1000]
[10, 4, 1000]

如何将每个向量的第三个维度的每个组合添加到一起,以便获得以下维度:

[10, 3, 4, 1000]

因此,如果您愿意,每个行在每个向量的第二个x第三维中添加到每个组合中的另一个。对不起,如果不清楚,我很难说清楚这个......

是否有某种聪明的方法来做numpy或pytorch(非常满意numpy解决方案,虽然我试图在pytorch上下文中使用它,所以火炬张量操作会更好),这不涉及我写一堆嵌套for循环?

嵌套循环示例:

x = np.random.randint(50, size=(32, 16, 512))
y = np.random.randint(50, size=(32, 21, 512))
scores = np.zeros(shape=(x.shape[0], x.shape[1], y.shape[1], 512))

for b in range(x.shape[0]):
    for i in range(x.shape[1]):
        for j in range(y.shape[1]):

            scores[b, i, j, :] = y[b, j, :] + x[b, i, :]
python numpy pytorch
1个回答
0
投票

对你起作用吗?

import torch

x1 = torch.rand(5, 3, 6)
y1 = torch.rand(5, 4, 6)

dim1, dim2 = x1.size()[0:2], y1.size()[-2:]
x2 = x1.unsqueeze(2).expand(*dim1, *dim2)
y2 = y1.unsqueeze(1).expand(*dim1, *dim2)

result = x2 + y2

print(x1[0, 1, :])
print(y1[0, 2, :])
print(result[0, 1, 2, :])

输出:

 0.2884
 0.5253
 0.1463
 0.4632
 0.8944
 0.6218
[torch.FloatTensor of size 6]


 0.5654
 0.0536
 0.9355
 0.1405
 0.9233
 0.1738
[torch.FloatTensor of size 6]


 0.8538
 0.5789
 1.0818
 0.6037
 1.8177
 0.7955
[torch.FloatTensor of size 6]
© www.soinside.com 2019 - 2024. All rights reserved.