# -*- coding:utf-8 -*-
"""
开发时间:2024/8/4 15:44
@author:xd
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
class VGG(nn.Module):
def __init__(self, num_classes=224):
super(VGG, self).__init__()
self.conv1 = nn.Conv2d(3, 64, 3, 1, 1)
self.conv2 = nn.Conv2d(64, 64, 3, 1, 1)
self.max_pool1 = nn.MaxPool2d(2, 2)
self.conv3 = nn.Conv2d(64, 128, 3, 1, 1)
self.conv4 = nn.Conv2d(128, 128, 3, 1, 1)
self.max_pool2 = nn.MaxPool2d(2, 2)
self.conv5 = nn.Conv2d(128, 256, 3, 1, 1)
self.conv6 = nn.Conv2d(256, 256, 3, 1, 1)
self.conv7 = nn.Conv2d(256, 256, 3, 1, 1)
self.max_pool3 = nn.MaxPool2d(2, 2)
self.conv8 = nn.Conv2d(256, 512, 3, 1, 1)
self.conv9 = nn.Conv2d(512, 512, 3, 1, 1)
self.conv10 = nn.Conv2d(512, 512, 3, 1, 1)
self.max_pool4 = nn.MaxPool2d(2, 2)
self.conv11 = nn.Conv2d(512, 512, 3, 1, 1)
self.conv12 = nn.Conv2d(512, 512, 3, 1, 1)
self.conv13 = nn.Conv2d(512, 512, 3, 1, 1)
self.max_pool5 = nn.MaxPool2d(2, 2)
self.fc1 = nn.Linear(7 * 7 * 512, 4096)
self.fc2 = nn.Linear(4096, 4096)
self.fc3 = nn.Linear(4096, num_classes)
self.softmax = nn.Softmax(dim=1)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.relu(self.conv2(x))
x = self.max_pool1(x)
x = F.relu(self.conv3(x))
x = F.relu(self.conv4(x))
x = self.max_pool2(x)
x = F.relu(self.conv5(x))
x = F.relu(self.conv6(x))
x = F.relu(self.conv7(x))
x = self.max_pool3(x)
x = F.relu(self.conv8(x))
x = F.relu(self.conv9(x))
x = F.relu(self.conv10(x))
x = self.max_pool4(x)
x = F.relu(self.conv11(x))
x = F.relu(self.conv12(x))
x = F.relu(self.conv13(x))
x = self.max_pool5(x)
x = torch.flatten(x, 1)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.softmax(self.fc3(x))
return x
def test():
model = VGG(num_classes=10)
print(model)
input = torch.zeros((1, 3, 224, 224))
output = model(input)
print(output)
if __name__ == "__main__":
test()
VGG16代码复现
最新推荐文章于 2024-08-22 22:01:15 发布