卷积层能保留图像的空间信息,所以相对于线性变换把所有像素值展成一维来说,更能保留图像的特性。这段代码把计算放在gpu上,相对较快
import numpy as np
import torch
import matplotlib.pyplot as plt
from torchvision import transforms
import torch.nn.functional as F
from torchvision import datasets #与Datasets类相比,不用实现里面的函数,直接就可以取出里面的(x,y)
from torch.utils.data import DataLoader
batch_size = 64
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))])
#transforms.ToTensor()将数据从[0,255]范围转换到[0,1],图像转张量,transforms.Normalize是归一化,后面参数是均值和标准差
train_dataset = datasets.MNIST(root='../dataset/mnist/', train=True, download=True, transform=transform)
train_loader = DataLoader(train_dataset, shuffle=True, batch_size=batch_size)
test_dataset = datasets.MNIST(root='../dataset/mnist/', train=False, download=True, transform=transform)
test_loader = DataLoader(test_dataset, shuffle=False, batch_size=batch_size)
class Net(torch.nn.Module):
def __init__(self):
super().__init__()
self.conv1 = torch.nn.Conv2d(1,10,kernel_size=5)
self.conv2 = torch.nn.Conv2d(10, 20, kernel_size=5)
self.pooling = torch.nn.MaxPool2d(2)
self.fc = torch.nn.Linear(320,10)
def forward(self,x):
batch_size = x.size(0)
x = F.relu(self.pooling(self.conv1(x)))
x = F.relu(self.pooling(self.conv2(x)))
x = x.view(batch_size,-1) #-1自动算出320
x = self.fc(x)
return x
model = Net()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
criterion = torch.nn.CrossEntropyLoss(reduction='mean') #交叉熵
optimizer = torch.optim.SGD(model.parameters(), lr=0.01,momentum=0.5)
def train(epoch):
sum_loss = 0
for i,data in enumerate(train_loader, 0):
inputs,labels = data #inputs是一个batch的输入
#print(i,inputs.size())
inputs, labels = inputs.to(device), labels.to(device)
y_pred = model(inputs)
loss = criterion(y_pred,labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
sum_loss+=loss.item()
if(i%300==299):
print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, sum_loss / 300))
sum_loss = 0.0
def t():
correct = 0
total = 0
with torch.no_grad():
for data in test_loader:
images, labels = data
images, labels = images.to(device), labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, dim=1) # dim = 1 列是第0个维度,行是第1个维度
#_是无用变量,占位的,因为第一个返回值是最大值,predicted是最大值的下标,只需要第二个变量
total += labels.size(0)
correct += (predicted == labels).sum().item() # 张量之间的比较运算
print('accuracy on test set: %d %% ' % (100 * correct / total))
return correct/total
epoch_list = []
acc_list = []
if __name__ == '__main__':
for epoch in range(10):
train(epoch)
acc = t()
epoch_list.append(epoch)
acc_list.append(acc)
plt.plot(epoch_list, acc_list)
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.show()