defforward(self,x): x= self.pool(F.relu(self.conv1(x))) x = F.relu(self.conv2(x)) x = x.view(-1,16*8*8) x= F.relu(self.fc1(x)) x = self.fc2(x) return x
''' train the neural network ''' for epoch in range(epoch_time): running_loss = 0.0 for i, data in enumerate(trainloader): # 注意这里要将images和labels的数据放到GPU上。 images,labels = data[0].to(device),data[1].to(device)
# print(labels) optimizer.zero_grad()
predicted = net(images)
loss = criterion(predicted,labels) loss.backward() optimizer.step()
net = Net().to(device) net.load_state_dict(torch.load(path))
class_correct = list(0.for i in range(10)) class_total = list(0.for i in range(10)) with torch.no_grad(): for i ,data in enumerate(testloader): images ,labels = data[0].to(device),data[1].to(device)
outputs = net(images) print(outputs,labels)
_,predicted = torch.max(outputs,1) c = (predicted==labels).squeeze() loss = criterion(outputs,labels) print(loss) # print(c,predicted,labels) for i in range(len(c)): label = labels[i] class_correct[label]+= c[i].item() class_total[label]+=1 for i in range(10): print("accuracy of Number:%d : %.2f %%"%(i,100*class_correct[i]/class_total[i]))
训练结果如下:
1 2 3 4 5 6 7 8 9 10
accuracy of Number:0 : 99.39 % accuracy of Number:1 : 99.74 % accuracy of Number:2 : 99.22 % accuracy of Number:3 : 99.21 % accuracy of Number:4 : 99.08 % accuracy of Number:5 : 99.10 % accuracy of Number:6 : 98.75 % accuracy of Number:7 : 99.03 % accuracy of Number:8 : 98.56 % accuracy of Number:9 : 98.81 %