Pytorch 如何对这类张量使用蒙版选择?

Pytorch 如何对这类张量使用蒙版选择?,pytorch,tensor,Pytorch,Tensor,假设我得到一个张量a和一个张量b import torch a = torch.tensor([[[ 0.8856, 0.1411, -0.1856, -0.1425], [-0.0971, 0.1251, 0.1608, -0.1302], [-0.0901, 0.3215, 0.1763, -0.0412]], [[ 0.8856, 0.1411, -0.1856, -0.1425], [-0.0971, 0.1251, 0.1608, -0

假设我得到一个张量
a
和一个张量
b

import torch
a = torch.tensor([[[ 0.8856,  0.1411, -0.1856, -0.1425],
    [-0.0971,  0.1251,  0.1608, -0.1302],
    [-0.0901,  0.3215,  0.1763, -0.0412]], 
    [[ 0.8856,  0.1411, -0.1856, -0.1425],
    [-0.0971,  0.1251,  0.1608, -0.1302],
    [-0.0901,  0.3215,  0.1763, -0.0412]]])
b = torch.tensor([[0,
    2,
    1], 
    [0,
    2,
    1]])
现在,我想从张量
a
中选择索引,其中张量
b
的值不是0

pred_masks = ( b != 0 )
c = torch.masked_select( a, (pred_masks == 1))
当然,我得到了一个预期的错误

----> 1 c = torch.masked_select( a, (pred_masks == 1))

RuntimeError: The size of tensor a (4) must match the size of tensor b (3) at non-singleton dimension 2
这是由包含4项的嵌套列表引起的。但是,需要选择tensor
a
中索引x处嵌套列表的所有值,对应于tensor
b
中的索引x


如果您有任何提示或回答,我将不胜感激。

我不太确定您想要的是输出c的形状。由于遮罩的形状为(2,3),a的形状为(2,3,4),您是否希望输出形状张量(n,4),其中n是(2,3)-遮罩中真实的元素数

如果是的话,我建议只使用遮罩作为前两个维度的索引

c = a[pred_masks,:]

希望这有点帮助

我不太确定您想要的是输出c的形状。由于遮罩的形状为(2,3),a的形状为(2,3,4),您是否希望输出形状张量(n,4),其中n是(2,3)-遮罩中真实的元素数

如果是的话,我建议只使用遮罩作为前两个维度的索引

c = a[pred_masks,:]

希望这有点帮助

非常感谢您的解决方案。使用遮罩作为前两个DIM的索引有效。非常感谢您提供的解决方案。使用遮罩作为前两个DIM的索引有效。