神经网络架构如下:

实现代码如下,运算速度有点长。
import torch
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
import torch.nn.functional as F
import matplotlib.pyplot as plt
batch_size = 64
learning_rate = 0.01
#将图像转化为张量
transform = transforms.Compose([ #把读取的图片进行张量化
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
#加载数据集
train_dataset = datasets.MNIST(root='../dataset',
train=True,
transform=transform,
download=False)
train_loader = DataLoader(train_dataset,
batch_size=batch_size,
shuffle=True)
test_dataset = datasets.MNIST(root='../dataset',
download=False,
train=True,
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.branch1x1 = torch.nn.Conv2d(in_channels=in_channels,out_channels=16,kernel_size=1,bias=False)
self.branch_pooling = torch.nn.Conv2d(in_channels=in_channels,out_channels=24,kernel_size=1,bias=False)
self.branch5x5_1 = torch.nn.Conv2d(in_channels=in_channels,out_channels=16,kernel_size=1,bias=False)
self.branch5x5_2 = torch.nn.Conv2d(in_channels=16,out_channels=24,kernel_size=5,bias=False,padding=2)
self.branch3x3_1 = torch.nn.Conv2d(in_channels=in_channels,out_channels=16,kernel_size=1,bias=False)
self.branch3x3_2 = torch.nn.Conv2d(in_channels=16,out_channels=24,kernel_size=3,bias=False,padding=1)
self.branch3x3_3 = torch.nn.Conv2d(in_channels=24,out_channels=24,kernel_size=3,bias=False,padding=1)
def forward(self,x):
branch1x1 = self.branch1x1(x)
branch_pooling = F.avg_pool2d(x,kernel_size=3,stride=1,padding=1)
branch_pooling = self.branch_pooling(branch_pooling)
branch5x5 = self.branch5x5_1(x)
branch5x5 = self.branch5x5_2(branch5x5)
branch3x3 = self.branch3x3_1(x)
branch3x3 = self.branch3x3_2(branch3x3)
branch3x3 = self.branch3x3_3(branch3x3)
output = [branch1x1, branch_pooling, branch5x5, branch3x3]
return torch.cat(output, 1)
class Net(torch.nn.Module):
def __init__(self):
super(Net,self).__init__()
self.conv1 = torch.nn.Conv2d(in_channels=1,out_channels=10,kernel_size=5,bias=False)
self.conv2 = torch.nn.Conv2d(in_channels=88,out_channels=20,kernel_size=5,bias=False)
self.incep1 = InceptionA(in_channels = 10)
self.incep2 = InceptionA(in_channels = 20)
self.mp = torch.nn.MaxPool2d(kernel_size=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)))
x = self.incep1(x)
x = F.relu(self.mp(self.conv2(x)))
x = self.incep2(x)
x = x.view(in_size, -1)
x = self.fc(x)
return x
#实例化对象
model = Net()
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model.to(device)
#定义损失函数和优化器
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(),lr=learning_rate,momentum=0.5)
#训练过程
def train(epoch):
model.train()
running_loss = 0.0
for batch_idx, data in enumerate(train_loader, 0):
inputs, target = data
inputs, target = inputs.to(device), target.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, target)
loss.backward()
optimizer.step()
running_loss += loss.item()
if batch_idx % 300 == 299:
print(f'[{epoch + 1}, {batch_idx + 1:5d}] loss: {running_loss / 300:.3f}')
running_loss = 0.0
#测试过程
def test(epoch):
model.eval()
correct = 0
total = 0
with torch.no_grad():
for data in test_loader:
inputs, labels = data
inputs, labels = inputs.to(device), labels.to(device)
outputs = model(inputs)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
accuracy = 100 * correct / total
print(f'Accuracy on test set: {accuracy:.3f}')
return accuracy
if __name__ == '__main__':
epochs = 10
epoch_list = []
accuracy_list = []
for epoch in range(epochs):
train(epoch)
accuracy = test(epoch)
epoch_list.append(epoch + 1)
accuracy_list.append(accuracy)
# 绘制准确率曲线
plt.figure(figsize=(12, 5))
plt.plot(epoch_list, accuracy_list, 'b-')
plt.title('Test Accuracy vs. Epochs')
plt.xlabel('Epoch')
plt.ylabel('Accuracy (%)')
plt.grid(True)
plt.show()
实现效果如下,准确率可以突破到99以上:




154

被折叠的 条评论
为什么被折叠?



