设置.train(),self.training=True

设置.eval(),self.training=False

class MyNet(nn.Module):
    def __init__(self):
        super(MyNet, self).__init__()
        self.features = nn.Sequential(
            nn.Conv2d(1, 32, kernel_size=3, padding=1, bias = False),
            nn.BatchNorm2d(32, affine=False),
        )

        self.classifier = nn.Linear(512, 20, bias=False)
        
    def forward(self, input):
        x_features = self.features(input)
        x = x_features.view(x_features.size(0), -1)
        
        if self.training is False:
            return x
        
        x = self.classifier(x)
        return x
m = MyNet()
m.train()
print(m.training)
m.eval()
print(m.training)
True
False
input = torch.randn(1, 1, 4, 4)
m.train()
output = m(input)
print(output.size())
m.eval()
output1 = m(input)
print(output1.size())
torch.Size([1, 20])
torch.Size([1, 512])
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐