假设我有两个具有维度的3D矩阵/张量:
[10, 3, 1000]
[10, 4, 1000]
如何将每个向量的第三个维度的每个组合相加,以获得维度:
[10, 3, 4, 1000]
所以每一行,如果你愿意,在第二个x第三个维度中,每个向量在每个组合中与另一个相加。抱歉,如果这不是很清楚,我很难清楚地表达这一点。
有没有一种聪明的方法可以用numpy或pytorch来做到这一点(对numpy解决方案非常满意,尽管我正在尝试在pytorch上下文中使用它,因此torch张量操作会更好),而不需要我编写一堆嵌套的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, :]
发布于 2018-02-24 16:08:03
它对你有效吗?
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]
https://stackoverflow.com/questions/48940080
复制相似问题