如何减少 PyTorch 中张量的最后一个维度?

How can I reduce a tensor's last dimension in PyTorch?

我有形状为 (1, 3, 256, 256, 3) 的张量。我需要减少其中一个维度以获得形状 (1, 3, 256, 256)。我该怎么做?

谢谢!

如果您打算对最后一个维度应用均值,那么您可以这样做:

In [18]: t = torch.randn((1, 3, 256, 256, 3))

In [19]: t.shape
Out[19]: torch.Size([1, 3, 256, 256, 3])

# apply mean over the last dimension
In [23]: t_reduced = torch.mean(t, -1)

In [24]: t_reduced.shape
Out[24]: torch.Size([1, 3, 256, 256])

# equivalently
In [32]: torch.mean(t, t.ndimension()-1).shape
Out[32]: torch.Size([1, 3, 256, 256])