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
| import torch from torch import nn from d2l import torch as d2l
# 定义VGG块 def vgg_block(num_convs, in_channels, out_channels): layers = [] for _ in range(num_convs): layers.append(nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1)) layers.append(nn.ReLU()) in_channels = out_channels#更新输入通道数 layers.append(nn.MaxPool2d(kernel_size=2, stride=2)) return nn.Sequential(*layers)
def vgg(conv_arch, num_classes=10): conv_blocks = [] in_channels = 1 # 输入通道数 for (num_convs, out_channels) in conv_arch: conv_blocks.append(vgg_block(num_convs, in_channels, out_channels)) in_channels = out_channels return nn.Sequential( #卷积单元 *conv_blocks, #全连接单元 nn.Flatten(), nn.Linear(in_channels * 7 * 7, 4096), # 假设输入图像大小为224x224 nn.ReLU(), nn.Dropout(0.5), nn.Linear(4096, 4096), nn.ReLU(), nn.Dropout(0.5), nn.Linear(4096, num_classes) )
if __name__ == "__main__": conv_arch = [(1, 64), (1, 128), (2, 256), (2, 512), (2, 512)] # VGG架构 net = vgg(conv_arch) # 测试网络结构 # X = torch.randn(1, 1, 224, 224) # 输入图像的形状 # for layer in net: # X = layer(X) # 前向传播 # print(layer.__class__.__name__, 'output shape:\t', X.shape)
batch_size = 128 train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size, resize=224) lr, num_epochs = 0.01, 10 d2l.train_ch6(net, train_iter, test_iter, num_epochs, lr, d2l.try_gpu())
|