【发布时间】:2019-06-01 02:21:19
【问题描述】:
我正在尝试索引多维张量中最后一维的最大元素。例如,假设我有一个张量
A = torch.randn((5, 2, 3))
_, idx = torch.max(A, dim=2)
这里 idx 存储最大索引,可能看起来像
>>>> A
tensor([[[ 1.0503, 0.4448, 1.8663],
[ 0.8627, 0.0685, 1.4241]],
[[ 1.2924, 0.2456, 0.1764],
[ 1.3777, 0.9401, 1.4637]],
[[ 0.5235, 0.4550, 0.2476],
[ 0.7823, 0.3004, 0.7792]],
[[ 1.9384, 0.3291, 0.7914],
[ 0.5211, 0.1320, 0.6330]],
[[ 0.3292, 0.9086, 0.0078],
[ 1.3612, 0.0610, 0.4023]]])
>>>> idx
tensor([[ 2, 2],
[ 0, 2],
[ 0, 0],
[ 0, 2],
[ 1, 0]])
我希望能够访问这些索引并根据它们分配给另一个张量。意思是我希望能够做到
B = torch.new_zeros(A.size())
B[idx] = A[idx]
其中 B 处处为 0,除了 A 在最后一个维度上最大的地方。那就是B应该存储
>>>>B
tensor([[[ 0, 0, 1.8663],
[ 0, 0, 1.4241]],
[[ 1.2924, 0, 0],
[ 0, 0, 1.4637]],
[[ 0.5235, 0, 0],
[ 0.7823, 0, 0]],
[[ 1.9384, 0, 0],
[ 0, 0, 0.6330]],
[[ 0, 0.9086, 0],
[ 1.3612, 0, 0]]])
事实证明这比我预期的要困难得多,因为 idx 没有正确索引数组 A。到目前为止,我一直无法找到使用 idx 来索引 A 的矢量化解决方案。
有没有很好的矢量化方法来做到这一点?
【问题讨论】:
标签: python multidimensional-array deep-learning pytorch tensor