1 回答

TA貢獻1911條經驗 獲得超7個贊
ResNet 實現
我能想到的最簡單的投影通用版本是這樣的:
class Residual(torch.nn.Module):
? ? def __init__(self, module: torch.nn.Module, projection: torch.nn.Module = None):
? ? ? ? super().__init__()
? ? ? ? self.module = module
? ? ? ? self.projection = projection
? ? def forward(self, inputs):
? ? ? ? output = self.module(inputs)
? ? ? ? if self.projection is not None:
? ? ? ? ? ? inputs = self.projection(inputs)
? ? ? ? return output + inputs
您可以傳遞module兩個堆疊卷積之類的東西,并添加1x1卷積(帶有填充或步幅或其他東西)作為投影模塊。
對于tabular數據,您可以將其用作module(假設您的輸入具有50功能):
torch.nn.Sequential(
? ? torch.nn.Linear(50, 50),
? ? torch.nn.ReLU(),
? ? torch.nn.Linear(50, 50),
? ? torch.nn.ReLU(),
? ? torch.nn.Linear(50, 50),
)
基本上,您所要做的就是將input某個模塊添加到其輸出中,僅此而已。
理由如下nn.Identity
構建神經網絡(然后讀取它們)可能會更容易,例如批量歸一化(取自上述 PR):
batch_norm = nn.BatchNorm2d
if dont_use_batch_norm:
? ? batch_norm = Identity
現在您可以nn.Sequential輕松地使用它:
nn.Sequential(
? ? ...
? ? batch_norm(N, momentum=0.05),
? ? ...
)
當打印網絡時,它總是具有相同數量的子模塊(帶有BatchNorm或Identity),這也使整個過程在我看來更加流暢。
這里提到的另一個用例可能是刪除現有神經網絡的部分內容:
net = tv.models.alexnet(pretrained=True)
# Assume net has two parts
# features and classifier
net.classifier = Identity()
net.features(input)現在,您可以運行而不是運行net(input),這對其他人來說也更容易閱讀。
添加回答
舉報