1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
| import torch import torchvision from torch.utils.data import DataLoader import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import matplotlib.pyplot as plt
n_epochs = 20 batch_size_train = 60 batch_size_test = 1000 learning_rate = 0.01 momentum = 0.5 log_interval = 10 random_seed = 1 torch.manual_seed(random_seed)
train_loader = torch.utils.data.DataLoader( torchvision.datasets.MNIST('./data/', train=True, download=True, transform=torchvision.transforms.Compose([ torchvision.transforms.ToTensor(), torchvision.transforms.Normalize( (0.1307,), (0.3081,)) ])), batch_size=batch_size_train, shuffle=True)
test_loader = torch.utils.data.DataLoader( torchvision.datasets.MNIST('./data/', train=False, download=True, transform=torchvision.transforms.Compose([ torchvision.transforms.ToTensor(), torchvision.transforms.Normalize( (0.1307,), (0.3081,)) ])), batch_size=batch_size_test, shuffle=True)
examples = enumerate(test_loader) batch_idx, (example_data, example_targets) = next(examples)
fig = plt.figure(figsize=(10, 6)) for i in range(6): plt.subplot(2, 3, i + 1) plt.tight_layout() plt.imshow(example_data[i][0], cmap='gray', interpolation='none') plt.title("Ground Truth: {}".format(example_targets[i])) plt.xticks([]) plt.yticks([]) plt.show()
class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 2, kernel_size=5) self.conv2 = nn.Conv2d(2, 4, kernel_size=5) self.conv2_drop = nn.Dropout2d() self.fc1 = nn.Linear(64, 50) self.fc2 = nn.Linear(50, 10)
def forward(self, x): x = F.relu(F.max_pool2d(self.conv1(x), 2)) x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2)) x = x.view(-1, 64) x = F.relu(self.fc1(x)) x = F.dropout(x, training=self.training) x = self.fc2(x) return F.log_softmax(x, dim=1)
network = Net() optimizer = optim.SGD(network.parameters(), lr=learning_rate, momentum=momentum)
train_losses = [] train_counter = [] test_losses = [] test_counter = [i * len(train_loader.dataset) for i in range(n_epochs + 1)] test_accuracies = []
best_accuracy = 0.0 best_epoch = 0
def train(epoch): network.train() total_loss = 0 for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() output = network(data) loss = F.nll_loss(output, target) loss.backward() optimizer.step() total_loss += loss.item() avg_loss = total_loss / len(train_loader) train_losses.append(avg_loss) train_counter.append((epoch - 1) * len(train_loader.dataset)) print(f'Epoch {epoch}: Train Loss = {avg_loss:.4f}')
def test(): network.eval() test_loss = 0 correct = 0 with torch.no_grad(): for data, target in test_loader: output = network(data) test_loss += F.nll_loss(output, target, reduction='sum').item() pred = output.data.max(1, keepdim=True)[1] correct += pred.eq(target.data.view_as(pred)).sum() test_loss /= len(test_loader.dataset) test_losses.append(test_loss) accuracy = 100. * correct / len(test_loader.dataset) test_accuracies.append(accuracy) return accuracy, test_loss
def save_best_model(epoch, accuracy, test_loss): global best_accuracy, best_epoch if accuracy > best_accuracy: best_accuracy = accuracy best_epoch = epoch torch.save({ 'epoch': epoch, 'model_state_dict': network.state_dict(), 'optimizer_state_dict': optimizer.state_dict(), 'accuracy': accuracy, 'loss': test_loss, 'train_losses': train_losses, 'test_losses': test_losses, 'test_accuracies': test_accuracies }, 'best_model.pth') print(f"✅ 保存最佳模型: epoch={epoch}, 准确率={accuracy:.2f}%")
print("开始训练...") print("-" * 50)
print("初始测试 (未训练模型):") initial_acc, initial_loss = test() print(f"初始准确率: {initial_acc:.2f}%\n")
for epoch in range(1, n_epochs + 1): train(epoch) acc, test_loss = test() print(f"Epoch {epoch} 测试准确率: {acc:.2f}%") save_best_model(epoch, acc, test_loss) print()
fig = plt.figure(figsize=(12, 5))
plt.subplot(1, 2, 1) plt.plot(train_counter, train_losses, color='blue', marker='o', linewidth=2, label='Train Loss') plt.scatter(test_counter, test_losses, color='red', s=80, label='Test Loss', zorder=5) plt.legend(loc='upper right') plt.xlabel('Number of training examples seen') plt.ylabel('Negative log likelihood loss') plt.title('Training and Test Loss') plt.grid(True, alpha=0.3)
plt.subplot(1, 2, 2) epochs_list = range(len(test_accuracies)) plt.plot(epochs_list, test_accuracies, color='green', marker='s', linewidth=2)
if best_epoch > 0: plt.scatter(best_epoch, best_accuracy, color='red', s=100, zorder=5, label=f'Best: {best_accuracy:.1f}%') plt.text(best_epoch, best_accuracy + 0.5, f'{best_accuracy:.1f}%', ha='center', va='bottom', fontweight='bold') plt.xlabel('Epoch') plt.ylabel('Accuracy (%)') plt.title('Test Accuracy') plt.legend(loc='lower right') plt.grid(True, alpha=0.3)
plt.tight_layout() plt.show()
print("加载最佳模型进行预测...") checkpoint = torch.load('best_model.pth') network.load_state_dict(checkpoint['model_state_dict']) optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
print(f"最佳模型信息:") print(f" - 训练轮次: {checkpoint['epoch']}") print(f" - 测试准确率: {checkpoint['accuracy']:.2f}%") print(f" - 测试损失: {checkpoint['loss']:.4f}")
examples = enumerate(test_loader) batch_idx, (example_data, example_targets) = next(examples)
with torch.no_grad(): network.eval() output = network(example_data)
fig = plt.figure(figsize=(10, 6)) for i in range(6): plt.subplot(2, 3, i + 1) plt.tight_layout() plt.imshow(example_data[i][0], cmap='gray', interpolation='none') pred = output.data.max(1, keepdim=True)[1][i].item() true_label = example_targets[i].item() if pred == true_label: color = 'green' title = f"✓ Pred: {pred}" else: color = 'red' title = f"✗ Pred: {pred} (True: {true_label})" plt.title(title, color=color) plt.xticks([]) plt.yticks([]) plt.show()
print("=" * 50) print(f"最终测试准确率: {test_accuracies[-1]:.2f}%") print(f"最佳测试准确率: {best_accuracy:.2f}% (epoch {best_epoch})") print(f"训练完成,共 {n_epochs} 个 epoch") print("=" * 50)
|