import torch import torch.nn as nn import torch.optim as optim from torchvision import datasets,transforms from torch.utils.data import DataLoader import matplotlib.pyplot as plt
# 前向传播 defforward(self, X): # 输入到隐层 1 X = self.hidden1(X) X = self.act1(X) X = self.pool1(X) # 隐层 2 X = self.hidden2(X) X = self.act2(X) X = self.pool2(X) # 扁平化 X = X.view(-1, 4*4*50) # 隐层 3 X = self.hidden3(X) X = self.act3(X) # 输出层 X = self.hidden4(X) X = self.act4(X) return X
print(f"Epoch {epoch + 1} / {epochs}, Loss: {running_loss / len(train_loader):.4f},Train Accuracy :{train_accuracy:.2%}") net.eval() correct = 0 total = 0 with torch.no_grad(): for inputs,labels in test_loader: outputs = net(inputs) _,predicted = torch.max(outputs,1) # 获取预测结果及其下标 【0,0,0.1,0.2,0.2,0,0,0.5,0,0】 total += labels.size(0) # 累加样本数量 correct += (predicted == labels).sum().item()
test_accuracy = correct / total test_accuracies.append(test_accuracy)#记录每个epoch的测试集准确率 print(f"Epoch {epoch+1}/{epochs},Test Accuracy:{test_accuracy:.2%}")
#如果测试集准确率提高,保存当前模型的权重 if test_accuracy > best_accuracy: best_accuracy = test_accuracy torch.save(net.state_dict(),best_model_path) print(f"Best model saved with accuracy:{best_accuracy:.2%}")