【发布时间】:2021-06-07 13:37:42
【问题描述】:
我在 PyTorch 中有两个张量,z 是形状为 (n_samples, n_features, n_views) 的 3d 张量,其中 n_samples 是数据集中的样本数,n_features 是每个样本的特征数,@ 987654325@ 是描述相同(n_samples, n_features) 特征矩阵但具有其他值的不同视图的数量。
我有另一个二维张量b,形状为(n_samples, n_views),其目的是在不同视图中重新缩放样本的所有特征。换句话说,它封装了同一样本的每个视图的特征的重要性。
例如:
import torch
z = torch.Tensor(([[2,3], [1,1], [4,5]],
[[2,2], [1,2], [7,7]],
[[2,3], [1,1], [4,5]],
[[2,3], [1,1], [4,5]]))
b = torch.Tensor(([1, 0],
[0, 1],
[0.2, 0.8],
[0.5, 0.5]))
print(z.shape, b.shape)
>>>torch.Size([4, 3, 2]) torch.Size([4, 2])
由于z 和b 之间的运算,我想获得形状为(n_samples, n_features) 的第三张量r。
一种可能的解决方案是:
b = b.unsqueeze(1)
r = z * b
r = torch.sum(r, dim=-1)
print(r, r.shape)
>>>tensor([[2.0000, 1.0000, 4.0000],
[2.0000, 2.0000, 7.0000],
[2.8000, 1.0000, 4.8000],
[2.5000, 1.0000, 4.5000]]) torch.Size([4, 3])
使用torch.matmul() 是否可以达到相同的结果?我已经尝试了很多次来置换两个向量的维度,但都没有成功。
【问题讨论】:
标签: python pytorch linear-algebra tensor