【问题标题】:Code a tensor view layer in nn.sequential在 nn.sequential 中编写张量视图层
【发布时间】:2022-12-15 03:26:03
【问题描述】:

我有一个 sequential 容器,我想在里面使用 Tensor.view 函数。因此,我当前的解决方案如下所示:

class Reshape(nn.Module):
    def __init__(self, *args):
        super().__init__()
        self.my_shape = args

    def forward(self, x):
        return x.view(self.my_shape)

在我的AutoEncoder课上我有:

self.decoder = nn.Sequential(
                torch.nn.Linear(self.bottleneck_size, 4096*2),
                Reshape(-1, 128, 8, 8),
                
                nn.UpsamplingNearest2d(scale_factor=2), 
                ...

有没有办法直接在 sequential 块中重塑张量,这样我就不需要使用外部创建的 Reshape 类? 谢谢

【问题讨论】:

    标签: python machine-learning pytorch autoencoder


    【解决方案1】:

    您可以使用UNFLATTEN层,来自Pytorch docs

    Unflattens tensor dim 将其扩展为所需的形状。与顺序一起使用。

    所以你会有:

    self.decoder = nn.Sequential(
                torch.nn.Linear(self.bottleneck_size, 4096*2),
                nn.Unflatten(0, 1, 128, 8, 8), # The first parameters is the dimension you would like to unflatten, here dimension 0. 
                nn.UpsamplingNearest2d(scale_factor=2), 
                ...
    

    如果您还没有,还应该查看Pytorch forum 上的讨论。另外 here 是如何在 Pytorch 中实现 torchvision 模型的。你可以看到他们已经将 Tensor.viewSequential 模块的其余部分分开,并将其应用到 forward 中。相同代码的current version现在使用flatten,也就是说这里使用unflatten是合理的。

    【讨论】:

      猜你喜欢
      • 2021-01-12
      • 1970-01-01
      • 2020-10-09
      • 2021-01-09
      • 2018-10-10
      • 2021-05-11
      • 2020-04-05
      • 2018-07-31
      • 1970-01-01
      相关资源
      最近更新 更多