1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| import torch.nn as nn import torch
model\_urls = { 'vgg11': 'https://download.pytorch.org/models/vgg11-bbd30ac9.pth', 'vgg13': 'https://download.pytorch.org/models/vgg13-c768596a.pth', 'vgg16': 'https://download.pytorch.org/models/vgg16-397923af.pth', 'vgg19': 'https://download.pytorch.org/models/vgg19-dcbb9e9d.pth' } class VGG(nn.Module): def \_\_init\_\_(self, features, num\_classes=1000, init\_weights=False): super(VGG, self).\_\_init\_\_() self.features = features self.classifier = nn.Sequential( nn.Dropout(p=0.5), nn.Linear(512\*7\*7, 2048), nn.ReLU(True), nn.Dropout(p=0.5), nn.Linear(2048, 2048), nn.ReLU(True), nn.Linear(2048, num\_classes)
) if init\_weights: self.\_initialize\_weights() def forward(self, x):
x = self.features(x)
x = torch.flatten(x, start\_dim=1)
x = self.classifier(x) return x
def \_initialize\_weights(self): for m in self.modules(): if isinstance(m, nn.Conv2d):
nn.init.xavier\_uniform\_(m.weight) if m.bias is not None: nn.init.constant\_(m.bias, 0) elif isinstance(m, nn.Linear): nn.init.xavier\_uniform\_(m.weight)
nn.init.constant\_(m.bias, 0)
def make\_features(cfg: list): layers = [] in\_channels = 3 for v in cfg: if v == "M": layers += [nn.MaxPool2d(kernel\_size=2, stride=2)] else: conv2d = nn.Conv2d(in\_channels, v, kernel\_size=3, padding=1) layers += [conv2d, nn.ReLU(True)] in\_channels = v return nn.Sequential(\*layers)
cfgs = { 'vgg11': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'], 'vgg13': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'], 'vgg16': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'], 'vgg19': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'], }
def make\_features(cfg: list): layers = [] in\_channels = 3 for v in cfg:
if v == "M": layers += [nn.MaxPool2d(kernel\_size=2, stride=2)]
else: conv2d = nn.Conv2d(in\_channels, v, kernel\_size=3, padding=1) layers += [conv2d, nn.ReLU(True)] in\_channels = v return nn.Sequential(\*layers) def vgg(model\_name="vgg16", \*\*kwargs): try: cfg = cfgs[model\_name] except: print("Warning: model number {} not in cfgs dict!".format(model\_name)) exit(-1) model = VGG(make\_features(cfg), \*\*kwargs) return model
|