首页 > 解决方案 > 在 pytorch 中,我怎样才能对一些元素求和,并得到一个更小形状的张量?

问题描述

具体来说,我有一个尺寸为 298x160x160 的张量(298 帧中的面),我需要对最后两个维度中的每个 4x4 元素求和,这样我才能得到一个 298x40x40 的张量。

我怎样才能做到这一点?

标签: sumpytorchtensor

解决方案


您可以创建一个具有单个 4x4 通道的卷积层,并将其权重设置为 1,步长为 4(另请参阅 Conv2D 文档):

a = torch.ones((298,160,160))
# add a dimension for the channels. Conv2D expects the input to be : (N,C,H,W)
# where N=number of samples, C=number of channels, H=height, W=width
a = a.unsqueeze(1)
a.shape

Out: torch.Size([298, 1, 160, 160])

with torch.no_grad(): # I assume you don't need to backprop, otherwise remove this check
    m = torch.nn.Conv2d(in_channels=1, out_channels=1, kernel_size=4,stride=4,bias=False)
    # set the kernel values to 1
    m.weight.data = m.weight.data * 0. + 1.
# apply the kernel and squeeze the channel dim out again
res = m(a).squeeze()
res.shape

Out: torch.Size([298, 40, 40])


推荐阅读