[英]Is it possible to return `nn.Module` rather than `nn.Sequential` in the `_make_layer` of ResNet code?
[英]Code a tensor view layer in nn.sequential
我有一個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
類? 謝謝
您可以使用 Pytorch 文檔中的UNFLATTEN
層:
Unflattens tensor dim 將其擴展為所需的形狀。 與順序一起使用。
所以你會有:
self.decoder = nn.Sequential(
torch.nn.Linear(self.bottleneck_size, 4096*2),
nn.Unflatten(1, (1, 128, 8, 8)), # The first parameters is the dimension you would like to unflatten, note that dimension 0 is usually your batch size. So here we need dimension 1.
# These alsos work
# nn.Unflatten(1, (-1, 128, 8, 8)),
# nn.Unflatten(1, (128, 8, 8)), nn.UpsamplingNearest2d(scale_factor=2),
...
如果您還沒有,還應該在Pytorch 論壇上查看此討論。 這里還有 torchvision 模型過去是如何在 Pytorch 中實現的。 你可以看到他們已經將Tensor.view
從其余的Sequential
模塊中分離出來,並將其應用在forward
中。 相同代碼的當前版本現在使用flatten
,這意味着在這里使用unflatten
是合理的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.