传送门:第11讲:高级神经网络 import matplotlib.pyplot as plt import torch import torch.nn.functional as F import torch.optim as optim from torchvision import transforms from torchvision import datasets from torch.utils.data import DataLoader import os os.environ["KMP_DUPLICATE_LIB_OK"]="True" # 1.Prepare dataset batch_size = 64 transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.1307), (0.3081)) ]) train_dataset = datasets.MNIST(root="D:\Python-learn\深度学习", train=True, download=False, transform=transform) train_loader = DataLoader(train_dataset, shuffle=True, batch_size=batch_size) test_dataset = datasets.MNIST(root="D:\Python-learn\深度学习", train=False, download=False, transform=transform) test_loader = DataLoader(test_dataset, shuffle=False, batch_size=batch_size) class InceptionA(torch.nn.Module): def __init__(self, in_channels): super(InceptionA,self).__init__() self.branch11 = torch.nn.Conv2d(in_channels, 16, kernel_size=1) self.branch_pool = torch.nn.Conv2d(in_channels, 24, kernel_size=1) self.branch55_1 = torch.nn.Conv2d(in_channels, 16, kernel_size=1) self.branch55_2 = torch.nn.Conv2d(16, 24, kernel_size=5, padding =2) # 千万别忘记加padding扩充!!不然会报错维度不一致因为滤波后少了一圈 self.branch33_1 = torch.nn.Conv2d(in_channels, 16, kernel_size=1) self.branch33_2 = torch.nn.Conv2d(16, 24, kernel_size=3, padding=1) self.branch33_3 = torch.nn.Conv2d(24, 24, kernel_size=3, padding=1) def forward(self, x): branch11 = self.branch11(x) branch55 = self.branch55_1(x) branch55 = self.branch55_2(branch55) branch33 = self.branch33_1(x) branch33 = self.branch33_2(branch33) branch33 = self.branch33_3(branch33) branch_pool = F.avg_pool2d(x, kernel_size = 3, stride = 1, padding = 1) branch_pool = self.branch_pool(branch_pool) outputs = [branch11, branch55, branch33, branch_pool] # outputs = torch.cat(output, dim = 1) # b,c,w,h按照通道方向将其拼接 return torch.cat(outputs, dim=1) class Net(torch.nn.Module): def __init__(self): super(Net,self).__init__() self.conv1 = torch.nn.Conv2d(1, 10, kernel_size=5) self.conv2 = torch.nn.Conv2d(88, 20, kernel_size=5) self.incep1 = InceptionA(in_channels=10) self.incep2 = InceptionA(in_channels=20) self.mp = torch.nn.MaxPool2d(2) self.fc = torch.nn.Linear(1408, 10) def forward(self, x): in_size = x.size(0) x = F.relu(self.mp(self.conv1(x))) # 输入10维 x = self.incep1(x) # 经过Inception,维度为:24+24+24+16=88 x = F.relu(self.mp(self.conv2(x))) # 88-->20 x = self.incep2(x) # 经过Inception,维度为:24+24+24+16=88 x = x.view(in_size, -1) x = self.fc(x) # 全连接 return x model = Net() # 实例化 # 2.1Move model to GPU device = torch.device("cuda:0"if torch.cuda.is_available() else "cpu") model.to(device) # 3. Construcrt Loss and Optimizer criterion = torch.nn.CrossEntropyLoss() optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5) epoch_list = [] right_list = [] # 4.train and test # Move Tensor To GPU def trian(epoch): running_loss = 0.0 for batch_size, data in enumerate(train_loader,0): inputs, target = data # 将训练数据转移到GPU inputs, target = inputs.to(device), target.to(device) optimizer.zero_grad() # forward + backward +updata outputs = model(inputs) loss = criterion(outputs, target) loss.backward() optimizer.step() running_loss += loss.item() if batch_size % 300 == 299: print('[%d, %5d] loss: %.3f' % (epoch + 1, batch_size + 1, running_loss / 300)) running_loss = 0.0 def test(): correct = 0 total = 0 with torch.no_grad(): for data in test_loader: images, labels = data # 将测试数据转移到GPU images, labels = images.to(device), labels.to(device) outputs = model(images) _, predict = torch.max(outputs.data, dim=1) total += labels.size(0) correct += (predict == labels).sum().item() right_rate = 100 * correct / total right_list.append(right_rate) print('Accuracy on test set:%d %%' % (right_rate)) # # %%: 用于在字符串中插入一个实际的百分号 %。 if __name__=='__main__': for epoch in range(10): epoch_list.append(epoch) trian(epoch) test() plt.plot(epoch_list, right_list) plt.xlabel('Epoch') plt.ylabel('Accuracy') plt.title('Accuracy vs Epoch') plt.show()
运行结果: