import torch
import torch.nn as nn
class VGG16(nn.Module):
def __init__(self, nums):
super(VGG16, self).__init__()
self.nums = nums
vgg = []
vgg.append(nn.Conv2d(in_channels=3, out_channels=64, kernel_size=3, stride=1, padding=1))
vgg.append(nn.ReLU())
vgg.append(nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1))
vgg.append(nn.ReLU())
vgg.append(nn.MaxPool2d(kernel_size=2, stride=2))
vgg.append(nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, stride=1, padding=1))
vgg.append(nn.ReLU())
vgg.append(nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=1))
vgg.append(nn.ReLU())
vgg.append(nn.MaxPool2d(kernel_size=2, stride=2))
vgg.append(nn.Conv2d(in_channels=128, out_channels=256, kernel_size=3, stride=1, padding=1))
vgg.append(nn.ReLU())
vgg.append(nn.Conv2d(in_channels=256, out_channels=256, kernel_size=3, stride=1, padding=1))
vgg.append(nn.ReLU())
vgg.append(nn.Conv2d(in_channels=256, out_channels=256, kernel_size=3, stride=1, padding=1))
vgg.append(nn.ReLU())
vgg.append(nn.MaxPool2d(kernel_size=2, stride=2))
vgg.append(nn.Conv2d(in_channels=256, out_channels=512, kernel_size=3, stride=1, padding=1))
vgg.append(nn.ReLU())
vgg.append(nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1))
vgg.append(nn.ReLU())
vgg.append(nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1))
vgg.append(nn.ReLU())
vgg.append(nn.MaxPool2d(kernel_size=2, stride=2))
vgg.append(nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1))
vgg.append(nn.ReLU())
vgg.append(nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1))
vgg.append(nn.ReLU())
vgg.append(nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1))
vgg.append(nn.ReLU())
vgg.append(nn.MaxPool2d(kernel_size=2, stride=2))
self.main = nn.Sequential(*vgg)
classfication = []
classfication.append(nn.Linear(in_features=512 * 7 * 7, out_features=4096))
classfication.append(nn.ReLU())
classfication.append(nn.Dropout(p=0.5))
classfication.append(nn.Linear(in_features=4096, out_features=4096))
classfication.append(nn.ReLU())
classfication.append(nn.Dropout(p=0.5))
classfication.append(nn.Linear(in_features=4096, out_features=self.nums))
self.classfication = nn.Sequential(*classfication)
def forward(self, x):
feature = self.main(x)
feature = feature.view(x.size(0), -1)
result = self.classfication(feature)
return result
x = torch.rand(size=(8, 3, 224, 224))
vgg16 = VGG16(nums=1000)
out = vgg16(x)
print(vgg16)