import torch import torch.nn as nn import torch.nn.functional as F # 定义GoogLeNet模型 class InceptionModule(nn.Module): def __init__(self, in_channels, out1, out2_in, out2, out3_in, out3, out4): super(InceptionModule, self).__init__() self.branch1 = nn.Sequential( nn.Conv2d(in_channels, out1, kernel_size=1), ) self.branch2 = nn.Sequential( nn.Conv2d(in_channels, out2_in, kernel_size=1), nn.Conv2d(out2_in, out2, kernel_size=3, padding=1), ) self.branch3 = nn.Sequential( nn.Conv2d(in_channels, out3_in, kernel_size=1), nn.Conv2d(out3_in, out3, kernel_size=5, padding=2), ) self.branch4 = nn.Sequential( nn.MaxPool2d(kernel_size=3, stride=1, padding=1), nn.Conv2d(in_channels, out4, kernel_size=1), ) def forward(self, x): out1 = self.branch1(x) out2 = self.branch2(x) out3 = self.branch3(x) out4 = self.branch4(x) return torch.cat([out1, out2, out3, out4], 1) class GoogLeNet(nn.Module): def __init__(self, num_classes=10): super(GoogLeNet, self).__init__() self.conv1 = nn.Sequential( nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=3, stride=2, padding=1), ) self.conv2 = nn.Sequential( nn.Conv2d(64, 64, kernel_size=1), nn.ReLU(inplace=True), nn.Conv2d(64, 192, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=3, stride=2, padding=1), ) self.inception3a = InceptionModule(192, 64, 96, 128, 16, 32, 32) self.inception3b = InceptionModule(256, 128, 128, 192, 32, 96, 64) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) self.inception4a = InceptionModule(480, 192, 96, 208, 16, 48, 64) self.inception4b = InceptionModule(512, 160, 112, 224, 24, 64, 64) self.inception4c = InceptionModule(512, 128, 128, 256, 24, 64, 64) self.inception4d = InceptionModule(512, 112, 144, 288, 32, 64, 64) self.inception4e = InceptionModule(528, 256, 160, 320, 32, 128, 128) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) self.inception5a = InceptionModule(832, 256, 160, 320, 32, 128, 128) self.inception5b = InceptionModule(832, 384, 192, 384, 48, 128, 128) self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) self.dropout = nn.Dropout(0.4) self.fc = nn.Linear(1024, num_classes) def forward(self, x): x = self.conv1(x) x = self.conv2(x) x = self.inception3a(x) x = self.inception3b(x) x = self.maxpool(x) x = self.inception4a(x) x = self.inception4b(x) x = self.inception4c(x) x = self.inception4d(x) x = self.inception4e(x) x = self.maxpool(x) x = self.inception5a(x) x = self.inception5b(x) x = self.avgpool(x) x = x.view(x.size(0), -1) x = self.dropout(x) x = self.fc(x) return x