{"id":41734,"date":"2025-06-04T03:23:50","date_gmt":"2025-06-03T19:23:50","guid":{"rendered":"https:\/\/www.wsisp.com\/helps\/41734.html"},"modified":"2025-06-04T03:23:50","modified_gmt":"2025-06-03T19:23:50","slug":"day-40-python%e6%89%93%e5%8d%a1","status":"publish","type":"post","link":"https:\/\/www.wsisp.com\/helps\/41734.html","title":{"rendered":"day 40 python\u6253\u5361"},"content":{"rendered":"<p>\u4ed4\u7ec6\u5b66\u4e60\u4e0b\u6d4b\u8bd5\u548c\u8bad\u7ec3\u4ee3\u7801\u7684\u903b\u8f91&#xff0c;\u8fd9\u662f\u57fa\u7840&#xff0c;\u8fd9\u4e2a\u4ee3\u7801\u6846\u67b6\u540e\u7eed\u4f1a\u4e00\u76f4\u6cbf\u7528&#xff0c;\u540e\u7eed\u7684\u91cd\u70b9\u6162\u6162\u5c31\u662f\u8f6c\u5411\u6a21\u578b\u5b9a\u4e49\u9636\u6bb5\u4e86\u3002<\/p>\n<p># \u5148\u7ee7\u7eed\u4e4b\u524d\u7684\u4ee3\u7801<br \/>\nimport torch<br \/>\nimport torch.nn as nn<br \/>\nimport torch.optim as optim<br \/>\nfrom torch.utils.data import DataLoader , Dataset # DataLoader \u662f PyTorch \u4e2d\u7528\u4e8e\u52a0\u8f7d\u6570\u636e\u7684\u5de5\u5177<br \/>\nfrom torchvision import datasets, transforms # torchvision \u662f\u4e00\u4e2a\u7528\u4e8e\u8ba1\u7b97\u673a\u89c6\u89c9\u7684\u5e93&#xff0c;datasets \u548c transforms \u662f\u5176\u4e2d\u7684\u6a21\u5757<br \/>\nimport matplotlib.pyplot as plt<br \/>\nimport warnings<br \/>\n# \u5ffd\u7565\u8b66\u544a\u4fe1\u606f<br \/>\nwarnings.filterwarnings(&#034;ignore&#034;)<br \/>\n# \u8bbe\u7f6e\u968f\u673a\u79cd\u5b50&#xff0c;\u786e\u4fdd\u7ed3\u679c\u53ef\u590d\u73b0<br \/>\ntorch.manual_seed(42)<br \/>\ndevice &#061; torch.device(&#034;cuda&#034; if torch.cuda.is_available() else &#034;cpu&#034;)<br \/>\nprint(f&#034;\u4f7f\u7528\u8bbe\u5907: {device}&#034;)<br \/>\n# 1. \u6570\u636e\u9884\u5904\u7406<br \/>\ntransform &#061; transforms.Compose([<br \/>\n    transforms.ToTensor(),  # \u8f6c\u6362\u4e3a\u5f20\u91cf\u5e76\u5f52\u4e00\u5316\u5230[0,1]<br \/>\n    transforms.Normalize((0.1307,), (0.3081,))  # MNIST\u6570\u636e\u96c6\u7684\u5747\u503c\u548c\u6807\u51c6\u5dee<br \/>\n])<\/p>\n<p># 2. \u52a0\u8f7dMNIST\u6570\u636e\u96c6<br \/>\ntrain_dataset &#061; datasets.MNIST(<br \/>\n    root&#061;&#039;.\/data&#039;,<br \/>\n    train&#061;True,<br \/>\n    download&#061;True,<br \/>\n    transform&#061;transform<br \/>\n)<\/p>\n<p>test_dataset &#061; datasets.MNIST(<br \/>\n    root&#061;&#039;.\/data&#039;,<br \/>\n    train&#061;False,<br \/>\n    transform&#061;transform<br \/>\n)<\/p>\n<p># 3. \u521b\u5efa\u6570\u636e\u52a0\u8f7d\u5668<br \/>\nbatch_size &#061; 64  # \u6bcf\u6279\u5904\u740664\u4e2a\u6837\u672c<br \/>\ntrain_loader &#061; DataLoader(train_dataset, batch_size&#061;batch_size, shuffle&#061;True)<br \/>\ntest_loader &#061; DataLoader(test_dataset, batch_size&#061;batch_size, shuffle&#061;False)<\/p>\n<p># 4. \u5b9a\u4e49\u6a21\u578b\u3001\u635f\u5931\u51fd\u6570\u548c\u4f18\u5316\u5668<br \/>\nclass MLP(nn.Module):<br \/>\n    def __init__(self):<br \/>\n        super(MLP, self).__init__()<br \/>\n        self.flatten &#061; nn.Flatten()  # \u5c0628&#215;28\u7684\u56fe\u50cf\u5c55\u5e73\u4e3a784\u7ef4\u5411\u91cf<br \/>\n        self.layer1 &#061; nn.Linear(784, 128)  # \u7b2c\u4e00\u5c42&#xff1a;784\u4e2a\u8f93\u5165&#xff0c;128\u4e2a\u795e\u7ecf\u5143<br \/>\n        self.relu &#061; nn.ReLU()  # \u6fc0\u6d3b\u51fd\u6570<br \/>\n        self.layer2 &#061; nn.Linear(128, 10)  # \u7b2c\u4e8c\u5c42&#xff1a;128\u4e2a\u8f93\u5165&#xff0c;10\u4e2a\u8f93\u51fa&#xff08;\u5bf9\u5e9410\u4e2a\u6570\u5b57\u7c7b\u522b&#xff09;<\/p>\n<p>    def forward(self, x):<br \/>\n        x &#061; self.flatten(x)  # \u5c55\u5e73\u56fe\u50cf<br \/>\n        x &#061; self.layer1(x)   # \u7b2c\u4e00\u5c42\u7ebf\u6027\u53d8\u6362<br \/>\n        x &#061; self.relu(x)     # \u5e94\u7528ReLU\u6fc0\u6d3b\u51fd\u6570<br \/>\n        x &#061; self.layer2(x)   # \u7b2c\u4e8c\u5c42\u7ebf\u6027\u53d8\u6362&#xff0c;\u8f93\u51falogits<br \/>\n        return x<\/p>\n<p># \u521d\u59cb\u5316\u6a21\u578b<br \/>\nmodel &#061; MLP()<br \/>\nmodel &#061; model.to(device)  # \u5c06\u6a21\u578b\u79fb\u81f3GPU&#xff08;\u5982\u679c\u53ef\u7528&#xff09;<\/p>\n<p># from torchsummary import summary  # \u5bfc\u5165torchsummary\u5e93<br \/>\n# print(&#034;\\\\n\u6a21\u578b\u7ed3\u6784\u4fe1\u606f&#xff1a;&#034;)<br \/>\n# summary(model, input_size&#061;(1, 28, 28))  # \u8f93\u5165\u5c3a\u5bf8\u4e3aMNIST\u56fe\u50cf\u5c3a\u5bf8<\/p>\n<p>criterion &#061; nn.CrossEntropyLoss()  # \u4ea4\u53c9\u71b5\u635f\u5931\u51fd\u6570&#xff0c;\u9002\u7528\u4e8e\u591a\u5206\u7c7b\u95ee\u9898<br \/>\noptimizer &#061; optim.Adam(model.parameters(), lr&#061;0.001)  # Adam\u4f18\u5316\u5668<\/p>\n<p> 5. \u8bad\u7ec3\u6a21\u578b&#xff08;\u8bb0\u5f55\u6bcf\u4e2a iteration \u7684\u635f\u5931&#xff09;<br \/>\ndef train(model, train_loader, test_loader, criterion, optimizer, device, epochs):<br \/>\n    model.train()  # \u8bbe\u7f6e\u4e3a\u8bad\u7ec3\u6a21\u5f0f<\/p>\n<p>    # \u65b0\u589e&#xff1a;\u8bb0\u5f55\u6bcf\u4e2a iteration \u7684\u635f\u5931<br \/>\n    all_iter_losses &#061; []  # \u5b58\u50a8\u6240\u6709 batch \u7684\u635f\u5931<br \/>\n    iter_indices &#061; []     # \u5b58\u50a8 iteration \u5e8f\u53f7&#xff08;\u4ece1\u5f00\u59cb&#xff09;<\/p>\n<p>    for epoch in range(epochs):<br \/>\n        running_loss &#061; 0.0<br \/>\n        correct &#061; 0<br \/>\n        total &#061; 0<\/p>\n<p>        for batch_idx, (data, target) in enumerate(train_loader):<br \/>\n            # enumerate() \u662f Python \u5185\u7f6e\u51fd\u6570&#xff0c;\u7528\u4e8e\u904d\u5386\u53ef\u8fed\u4ee3\u5bf9\u8c61&#xff08;\u5982\u5217\u8868\u3001\u5143\u7ec4&#xff09;\u5e76\u540c\u65f6\u83b7\u53d6\u7d22\u5f15\u548c\u503c\u3002<br \/>\n            # batch_idx&#xff1a;\u5f53\u524d\u6279\u6b21\u7684\u7d22\u5f15&#xff08;\u4ece 0 \u5f00\u59cb&#xff09;<br \/>\n            # (data, target)&#xff1a;\u5f53\u524d\u6279\u6b21\u7684\u6837\u672c\u6570\u636e\u548c\u5bf9\u5e94\u7684\u6807\u7b7e&#xff0c;\u662f\u4e00\u4e2a\u5143\u7ec4&#xff0c;\u8fd9\u662f\u56e0\u4e3adataloader\u5185\u7f6e\u7684getitem\u65b9\u6cd5\u8fd4\u56de\u7684\u662f\u4e00\u4e2a\u5143\u7ec4&#xff0c;\u5305\u542b\u6570\u636e\u548c\u6807\u7b7e\u3002<br \/>\n            # \u53ea\u9700\u8981\u8bb0\u4f4f\u8fd9\u79cd\u56fa\u5b9a\u5199\u6cd5\u5373\u53ef<br \/>\n            data, target &#061; data.to(device), target.to(device)  # \u79fb\u81f3GPU(\u5982\u679c\u53ef\u7528)<\/p>\n<p>            optimizer.zero_grad()  # \u68af\u5ea6\u6e05\u96f6<br \/>\n            output &#061; model(data)  # \u524d\u5411\u4f20\u64ad<br \/>\n            loss &#061; criterion(output, target)  # \u8ba1\u7b97\u635f\u5931<br \/>\n            loss.backward()  # \u53cd\u5411\u4f20\u64ad<br \/>\n            optimizer.step()  # \u66f4\u65b0\u53c2\u6570<\/p>\n<p>            # \u8bb0\u5f55\u5f53\u524d iteration \u7684\u635f\u5931&#xff08;\u6ce8\u610f&#xff1a;\u8fd9\u91cc\u76f4\u63a5\u4f7f\u7528\u5355 batch \u635f\u5931&#xff0c;\u800c\u975e\u7d2f\u52a0\u5e73\u5747&#xff09;<br \/>\n            iter_loss &#061; loss.item()<br \/>\n            all_iter_losses.append(iter_loss)<br \/>\n            iter_indices.append(epoch * len(train_loader) &#043; batch_idx &#043; 1)  # iteration \u5e8f\u53f7\u4ece1\u5f00\u59cb<\/p>\n<p>            # \u7edf\u8ba1\u51c6\u786e\u7387\u548c\u635f\u5931<br \/>\n            running_loss &#043;&#061; loss.item() #\u5c06loss\u8f6c\u5316\u4e3a\u6807\u91cf\u503c\u5e76\u4e14\u7d2f\u52a0\u5230running_loss\u4e2d&#xff0c;\u8ba1\u7b97\u603b\u635f\u5931<br \/>\n            _, predicted &#061; output.max(1) # output&#xff1a;\u662f\u6a21\u578b\u7684\u8f93\u51fa&#xff08;logits&#xff09;&#xff0c;\u5f62\u72b6\u4e3a [batch_size, 10]&#xff08;MNIST \u6709 10 \u4e2a\u7c7b\u522b&#xff09;<br \/>\n            # \u83b7\u53d6\u9884\u6d4b\u7ed3\u679c&#xff0c;max(1) \u8fd4\u56de\u6bcf\u884c&#xff08;\u5373\u6bcf\u4e2a\u6837\u672c&#xff09;\u7684\u6700\u5927\u503c\u548c\u5bf9\u5e94\u7684\u7d22\u5f15&#xff0c;\u8fd9\u91cc\u6211\u4eec\u53ea\u9700\u8981\u7d22\u5f15<br \/>\n            total &#043;&#061; target.size(0) # target.size(0) \u8fd4\u56de\u5f53\u524d\u6279\u6b21\u7684\u6837\u672c\u6570\u91cf&#xff0c;\u5373 batch_size&#xff0c;\u7d2f\u52a0\u6240\u6709\u6279\u6b21\u7684\u6837\u672c\u6570&#xff0c;\u6700\u7ec8\u7b49\u4e8e\u8bad\u7ec3\u96c6\u7684\u603b\u6837\u672c\u6570<br \/>\n            correct &#043;&#061; predicted.eq(target).sum().item() # \u8fd4\u56de\u4e00\u4e2a\u5e03\u5c14\u5f20\u91cf&#xff0c;\u8868\u793a\u9884\u6d4b\u662f\u5426\u6b63\u786e&#xff0c;sum() \u8ba1\u7b97\u6b63\u786e\u9884\u6d4b\u7684\u6570\u91cf&#xff0c;item() \u5c06\u7ed3\u679c\u8f6c\u6362\u4e3a Python \u6570\u5b57<\/p>\n<p>            # \u6bcf100\u4e2a\u6279\u6b21\u6253\u5370\u4e00\u6b21\u8bad\u7ec3\u4fe1\u606f&#xff08;\u53ef\u9009&#xff1a;\u540c\u65f6\u6253\u5370\u5355 batch \u635f\u5931&#xff09;<br \/>\n            if (batch_idx &#043; 1) % 100 &#061;&#061; 0:<br \/>\n                print(f&#039;Epoch: {epoch&#043;1}\/{epochs} | Batch: {batch_idx&#043;1}\/{len(train_loader)} &#039;<br \/>\n                      f&#039;| \u5355Batch\u635f\u5931: {iter_loss:.4f} | \u7d2f\u8ba1\u5e73\u5747\u635f\u5931: {running_loss\/(batch_idx&#043;1):.4f}&#039;)<\/p>\n<p>        # \u6d4b\u8bd5\u3001\u6253\u5370 epoch \u7ed3\u679c<br \/>\n        epoch_train_loss &#061; running_loss \/ len(train_loader)<br \/>\n        epoch_train_acc &#061; 100. * correct \/ total<br \/>\n        epoch_test_loss, epoch_test_acc &#061; test(model, test_loader, criterion, device)<\/p>\n<p>        print(f&#039;Epoch {epoch&#043;1}\/{epochs} \u5b8c\u6210 | \u8bad\u7ec3\u51c6\u786e\u7387: {epoch_train_acc:.2f}% | \u6d4b\u8bd5\u51c6\u786e\u7387: {epoch_test_acc:.2f}%&#039;)<\/p>\n<p>    # \u7ed8\u5236\u6240\u6709 iteration \u7684\u635f\u5931\u66f2\u7ebf<br \/>\n    plot_iter_losses(all_iter_losses, iter_indices)<br \/>\n    # \u4fdd\u7559\u539f epoch \u7ea7\u66f2\u7ebf&#xff08;\u53ef\u9009&#xff09;<br \/>\n    # plot_metrics(train_losses, test_losses, train_accuracies, test_accuracies, epochs)<\/p>\n<p>    return epoch_test_acc  # \u8fd4\u56de\u6700\u7ec8\u6d4b\u8bd5\u51c6\u786e\u7387 <\/p>\n<p>\u5f69\u8272\u56fe\u7247\u5199\u6cd5<\/p>\n<p>import torch<br \/>\nimport torch.nn as nn<br \/>\nimport torch.optim as optim<br \/>\nfrom torchvision import datasets, transforms<br \/>\nfrom torch.utils.data import DataLoader<br \/>\nimport matplotlib.pyplot as plt<br \/>\nimport numpy as np<\/p>\n<p># \u8bbe\u7f6e\u4e2d\u6587\u5b57\u4f53\u652f\u6301<br \/>\nplt.rcParams[&#034;font.family&#034;] &#061; [&#034;SimHei&#034;]<br \/>\nplt.rcParams[&#039;axes.unicode_minus&#039;] &#061; False  # \u89e3\u51b3\u8d1f\u53f7\u663e\u793a\u95ee\u9898<\/p>\n<p># 1. \u6570\u636e\u9884\u5904\u7406<br \/>\ntransform &#061; transforms.Compose([<br \/>\n    transforms.ToTensor(),                # \u8f6c\u6362\u4e3a\u5f20\u91cf<br \/>\n    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))  # \u6807\u51c6\u5316\u5904\u7406<br \/>\n])<\/p>\n<p># 2. \u52a0\u8f7dCIFAR-10\u6570\u636e\u96c6<br \/>\ntrain_dataset &#061; datasets.CIFAR10(<br \/>\n    root&#061;&#039;.\/data&#039;,<br \/>\n    train&#061;True,<br \/>\n    download&#061;True,<br \/>\n    transform&#061;transform<br \/>\n)<\/p>\n<p>test_dataset &#061; datasets.CIFAR10(<br \/>\n    root&#061;&#039;.\/data&#039;,<br \/>\n    train&#061;False,<br \/>\n    transform&#061;transform<br \/>\n)<\/p>\n<p># 3. \u521b\u5efa\u6570\u636e\u52a0\u8f7d\u5668<br \/>\nbatch_size &#061; 64<br \/>\ntrain_loader &#061; DataLoader(train_dataset, batch_size&#061;batch_size, shuffle&#061;True)<br \/>\ntest_loader &#061; DataLoader(test_dataset, batch_size&#061;batch_size, shuffle&#061;False)<\/p>\n<p># 4. \u5b9a\u4e49MLP\u6a21\u578b&#xff08;\u9002\u5e94CIFAR-10\u7684\u8f93\u5165\u5c3a\u5bf8&#xff09;<br \/>\nclass MLP(nn.Module):<br \/>\n    def __init__(self):<br \/>\n        super(MLP, self).__init__()<br \/>\n        self.flatten &#061; nn.Flatten()  # \u5c063x32x32\u7684\u56fe\u50cf\u5c55\u5e73\u4e3a3072\u7ef4\u5411\u91cf<br \/>\n        self.layer1 &#061; nn.Linear(3072, 512)  # \u7b2c\u4e00\u5c42&#xff1a;3072\u4e2a\u8f93\u5165&#xff0c;512\u4e2a\u795e\u7ecf\u5143<br \/>\n        self.relu1 &#061; nn.ReLU()<br \/>\n        self.dropout1 &#061; nn.Dropout(0.2)  # \u6dfb\u52a0Dropout\u9632\u6b62\u8fc7\u62df\u5408<br \/>\n        self.layer2 &#061; nn.Linear(512, 256)  # \u7b2c\u4e8c\u5c42&#xff1a;512\u4e2a\u8f93\u5165&#xff0c;256\u4e2a\u795e\u7ecf\u5143<br \/>\n        self.relu2 &#061; nn.ReLU()<br \/>\n        self.dropout2 &#061; nn.Dropout(0.2)<br \/>\n        self.layer3 &#061; nn.Linear(256, 10)  # \u8f93\u51fa\u5c42&#xff1a;10\u4e2a\u7c7b\u522b<\/p>\n<p>    def forward(self, x):<br \/>\n        # \u7b2c\u4e00\u6b65&#xff1a;\u5c06\u8f93\u5165\u56fe\u50cf\u5c55\u5e73\u4e3a\u4e00\u7ef4\u5411\u91cf<br \/>\n        x &#061; self.flatten(x)  # \u8f93\u5165\u5c3a\u5bf8: [batch_size, 3, 32, 32] \u2192 [batch_size, 3072]<\/p>\n<p>        # \u7b2c\u4e00\u5c42\u5168\u8fde\u63a5 &#043; \u6fc0\u6d3b &#043; Dropout<br \/>\n        x &#061; self.layer1(x)   # \u7ebf\u6027\u53d8\u6362: [batch_size, 3072] \u2192 [batch_size, 512]<br \/>\n        x &#061; self.relu1(x)    # \u5e94\u7528ReLU\u6fc0\u6d3b\u51fd\u6570<br \/>\n        x &#061; self.dropout1(x) # \u8bad\u7ec3\u65f6\u968f\u673a\u4e22\u5f03\u90e8\u5206\u795e\u7ecf\u5143\u8f93\u51fa<\/p>\n<p>        # \u7b2c\u4e8c\u5c42\u5168\u8fde\u63a5 &#043; \u6fc0\u6d3b &#043; Dropout<br \/>\n        x &#061; self.layer2(x)   # \u7ebf\u6027\u53d8\u6362: [batch_size, 512] \u2192 [batch_size, 256]<br \/>\n        x &#061; self.relu2(x)    # \u5e94\u7528ReLU\u6fc0\u6d3b\u51fd\u6570<br \/>\n        x &#061; self.dropout2(x) # \u8bad\u7ec3\u65f6\u968f\u673a\u4e22\u5f03\u90e8\u5206\u795e\u7ecf\u5143\u8f93\u51fa<\/p>\n<p>        # \u7b2c\u4e09\u5c42&#xff08;\u8f93\u51fa\u5c42&#xff09;\u5168\u8fde\u63a5<br \/>\n        x &#061; self.layer3(x)   # \u7ebf\u6027\u53d8\u6362: [batch_size, 256] \u2192 [batch_size, 10]<\/p>\n<p>        return x  # \u8fd4\u56de\u672a\u7ecf\u8fc7Softmax\u7684logits<\/p>\n<p># \u68c0\u67e5GPU\u662f\u5426\u53ef\u7528<br \/>\ndevice &#061; torch.device(&#034;cuda&#034; if torch.cuda.is_available() else &#034;cpu&#034;)<\/p>\n<p># \u521d\u59cb\u5316\u6a21\u578b<br \/>\nmodel &#061; MLP()<br \/>\nmodel &#061; model.to(device)  # \u5c06\u6a21\u578b\u79fb\u81f3GPU&#xff08;\u5982\u679c\u53ef\u7528&#xff09;<\/p>\n<p>criterion &#061; nn.CrossEntropyLoss()  # \u4ea4\u53c9\u71b5\u635f\u5931\u51fd\u6570<br \/>\noptimizer &#061; optim.Adam(model.parameters(), lr&#061;0.001)  # Adam\u4f18\u5316\u5668<\/p>\n<p># 5. \u8bad\u7ec3\u6a21\u578b&#xff08;\u8bb0\u5f55\u6bcf\u4e2a iteration \u7684\u635f\u5931&#xff09;<br \/>\ndef train(model, train_loader, test_loader, criterion, optimizer, device, epochs):<br \/>\n    model.train()  # \u8bbe\u7f6e\u4e3a\u8bad\u7ec3\u6a21\u5f0f<\/p>\n<p>    # \u8bb0\u5f55\u6bcf\u4e2a iteration \u7684\u635f\u5931<br \/>\n    all_iter_losses &#061; []  # \u5b58\u50a8\u6240\u6709 batch \u7684\u635f\u5931<br \/>\n    iter_indices &#061; []     # \u5b58\u50a8 iteration \u5e8f\u53f7<\/p>\n<p>    for epoch in range(epochs):<br \/>\n        running_loss &#061; 0.0<br \/>\n        correct &#061; 0<br \/>\n        total &#061; 0<\/p>\n<p>        for batch_idx, (data, target) in enumerate(train_loader):<br \/>\n            data, target &#061; data.to(device), target.to(device)  # \u79fb\u81f3GPU<\/p>\n<p>            optimizer.zero_grad()  # \u68af\u5ea6\u6e05\u96f6<br \/>\n            output &#061; model(data)  # \u524d\u5411\u4f20\u64ad<br \/>\n            loss &#061; criterion(output, target)  # \u8ba1\u7b97\u635f\u5931<br \/>\n            loss.backward()  # \u53cd\u5411\u4f20\u64ad<br \/>\n            optimizer.step()  # \u66f4\u65b0\u53c2\u6570<\/p>\n<p>            # \u8bb0\u5f55\u5f53\u524d iteration \u7684\u635f\u5931<br \/>\n            iter_loss &#061; loss.item()<br \/>\n            all_iter_losses.append(iter_loss)<br \/>\n            iter_indices.append(epoch * len(train_loader) &#043; batch_idx &#043; 1)<\/p>\n<p>            # \u7edf\u8ba1\u51c6\u786e\u7387\u548c\u635f\u5931<br \/>\n            running_loss &#043;&#061; iter_loss<br \/>\n            _, predicted &#061; output.max(1)<br \/>\n            total &#043;&#061; target.size(0)<br \/>\n            correct &#043;&#061; predicted.eq(target).sum().item()<\/p>\n<p>            # \u6bcf100\u4e2a\u6279\u6b21\u6253\u5370\u4e00\u6b21\u8bad\u7ec3\u4fe1\u606f<br \/>\n            if (batch_idx &#043; 1) % 100 &#061;&#061; 0:<br \/>\n                print(f&#039;Epoch: {epoch&#043;1}\/{epochs} | Batch: {batch_idx&#043;1}\/{len(train_loader)} &#039;<br \/>\n                      f&#039;| \u5355Batch\u635f\u5931: {iter_loss:.4f} | \u7d2f\u8ba1\u5e73\u5747\u635f\u5931: {running_loss\/(batch_idx&#043;1):.4f}&#039;)<\/p>\n<p>        # \u8ba1\u7b97\u5f53\u524depoch\u7684\u5e73\u5747\u8bad\u7ec3\u635f\u5931\u548c\u51c6\u786e\u7387<br \/>\n        epoch_train_loss &#061; running_loss \/ len(train_loader)<br \/>\n        epoch_train_acc &#061; 100. * correct \/ total<\/p>\n<p>        # \u6d4b\u8bd5\u9636\u6bb5<br \/>\n        model.eval()  # \u8bbe\u7f6e\u4e3a\u8bc4\u4f30\u6a21\u5f0f<br \/>\n        test_loss &#061; 0<br \/>\n        correct_test &#061; 0<br \/>\n        total_test &#061; 0<\/p>\n<p>        with torch.no_grad():<br \/>\n            for data, target in test_loader:<br \/>\n                data, target &#061; data.to(device), target.to(device)<br \/>\n                output &#061; model(data)<br \/>\n                test_loss &#043;&#061; criterion(output, target).item()<br \/>\n                _, predicted &#061; output.max(1)<br \/>\n                total_test &#043;&#061; target.size(0)<br \/>\n                correct_test &#043;&#061; predicted.eq(target).sum().item()<\/p>\n<p>        epoch_test_loss &#061; test_loss \/ len(test_loader)<br \/>\n        epoch_test_acc &#061; 100. * correct_test \/ total_test<\/p>\n<p>        print(f&#039;Epoch {epoch&#043;1}\/{epochs} \u5b8c\u6210 | \u8bad\u7ec3\u51c6\u786e\u7387: {epoch_train_acc:.2f}% | \u6d4b\u8bd5\u51c6\u786e\u7387: {epoch_test_acc:.2f}%&#039;)<\/p>\n<p>    # \u7ed8\u5236\u6240\u6709 iteration \u7684\u635f\u5931\u66f2\u7ebf<br \/>\n    plot_iter_losses(all_iter_losses, iter_indices)<\/p>\n<p>    return epoch_test_acc  # \u8fd4\u56de\u6700\u7ec8\u6d4b\u8bd5\u51c6\u786e\u7387<\/p>\n<p># 6. \u7ed8\u5236\u6bcf\u4e2a iteration \u7684\u635f\u5931\u66f2\u7ebf<br \/>\ndef plot_iter_losses(losses, indices):<br \/>\n    plt.figure(figsize&#061;(10, 4))<br \/>\n    plt.plot(indices, losses, &#039;b-&#039;, alpha&#061;0.7, label&#061;&#039;Iteration Loss&#039;)<br \/>\n    plt.xlabel(&#039;Iteration&#xff08;Batch\u5e8f\u53f7&#xff09;&#039;)<br \/>\n    plt.ylabel(&#039;\u635f\u5931\u503c&#039;)<br \/>\n    plt.title(&#039;\u6bcf\u4e2a Iteration \u7684\u8bad\u7ec3\u635f\u5931&#039;)<br \/>\n    plt.legend()<br \/>\n    plt.grid(True)<br \/>\n    plt.tight_layout()<br \/>\n    plt.show()<\/p>\n<p># 7. \u6267\u884c\u8bad\u7ec3\u548c\u6d4b\u8bd5<br \/>\nepochs &#061; 20  # \u589e\u52a0\u8bad\u7ec3\u8f6e\u6b21\u4ee5\u83b7\u5f97\u66f4\u597d\u6548\u679c<br \/>\nprint(&#034;\u5f00\u59cb\u8bad\u7ec3\u6a21\u578b&#8230;&#034;)<br \/>\nfinal_accuracy &#061; train(model, train_loader, test_loader, criterion, optimizer, device, epochs)<br \/>\nprint(f&#034;\u8bad\u7ec3\u5b8c\u6210&#xff01;\u6700\u7ec8\u6d4b\u8bd5\u51c6\u786e\u7387: {final_accuracy:.2f}%&#034;)<\/p>\n<p># # \u4fdd\u5b58\u6a21\u578b<br \/>\n# torch.save(model.state_dict(), &#039;cifar10_mlp_model.pth&#039;)<br \/>\n# # print(&#034;\u6a21\u578b\u5df2\u4fdd\u5b58\u4e3a: cifar10_mlp_model.pth&#034;) <\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u6587\u7ae0\u6d4f\u89c8\u9605\u8bfb231\u6b21\u3002\u4ed4\u7ec6\u5b66\u4e60\u4e0b\u6d4b\u8bd5\u548c\u8bad\u7ec3\u4ee3\u7801\u7684\u903b\u8f91\uff0c\u8fd9\u662f\u57fa\u7840\uff0c\u8fd9\u4e2a\u4ee3\u7801\u6846\u67b6\u540e\u7eed\u4f1a\u4e00\u76f4\u6cbf\u7528\uff0c\u540e\u7eed\u7684\u91cd\u70b9\u6162\u6162\u5c31\u662f\u8f6c\u5411\u6a21\u578b\u5b9a\u4e49\u9636\u6bb5\u4e86\u3002<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[50,86],"topic":[],"class_list":["post-41734","post","type-post","status-publish","format-standard","hentry","category-server","tag-50","tag-86"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v20.3 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>day 40 python\u6253\u5361 - \u7f51\u7855\u4e92\u8054\u5e2e\u52a9\u4e2d\u5fc3<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.wsisp.com\/helps\/41734.html\" \/>\n<meta property=\"og:locale\" content=\"zh_CN\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"day 40 python\u6253\u5361 - \u7f51\u7855\u4e92\u8054\u5e2e\u52a9\u4e2d\u5fc3\" \/>\n<meta property=\"og:description\" content=\"\u6587\u7ae0\u6d4f\u89c8\u9605\u8bfb231\u6b21\u3002\u4ed4\u7ec6\u5b66\u4e60\u4e0b\u6d4b\u8bd5\u548c\u8bad\u7ec3\u4ee3\u7801\u7684\u903b\u8f91\uff0c\u8fd9\u662f\u57fa\u7840\uff0c\u8fd9\u4e2a\u4ee3\u7801\u6846\u67b6\u540e\u7eed\u4f1a\u4e00\u76f4\u6cbf\u7528\uff0c\u540e\u7eed\u7684\u91cd\u70b9\u6162\u6162\u5c31\u662f\u8f6c\u5411\u6a21\u578b\u5b9a\u4e49\u9636\u6bb5\u4e86\u3002\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.wsisp.com\/helps\/41734.html\" \/>\n<meta property=\"og:site_name\" content=\"\u7f51\u7855\u4e92\u8054\u5e2e\u52a9\u4e2d\u5fc3\" \/>\n<meta property=\"article:published_time\" content=\"2025-06-03T19:23:50+00:00\" \/>\n<meta name=\"author\" content=\"admin\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"\u4f5c\u8005\" \/>\n\t<meta name=\"twitter:data1\" content=\"admin\" \/>\n\t<meta name=\"twitter:label2\" content=\"\u9884\u8ba1\u9605\u8bfb\u65f6\u95f4\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 \u5206\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.wsisp.com\/helps\/41734.html\",\"url\":\"https:\/\/www.wsisp.com\/helps\/41734.html\",\"name\":\"day 40 python\u6253\u5361 - \u7f51\u7855\u4e92\u8054\u5e2e\u52a9\u4e2d\u5fc3\",\"isPartOf\":{\"@id\":\"https:\/\/www.wsisp.com\/helps\/#website\"},\"datePublished\":\"2025-06-03T19:23:50+00:00\",\"dateModified\":\"2025-06-03T19:23:50+00:00\",\"author\":{\"@id\":\"https:\/\/www.wsisp.com\/helps\/#\/schema\/person\/358e386c577a3ab51c4493330a20ad41\"},\"breadcrumb\":{\"@id\":\"https:\/\/www.wsisp.com\/helps\/41734.html#breadcrumb\"},\"inLanguage\":\"zh-Hans\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.wsisp.com\/helps\/41734.html\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.wsisp.com\/helps\/41734.html#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"\u9996\u9875\",\"item\":\"https:\/\/www.wsisp.com\/helps\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"day 40 python\u6253\u5361\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.wsisp.com\/helps\/#website\",\"url\":\"https:\/\/www.wsisp.com\/helps\/\",\"name\":\"\u7f51\u7855\u4e92\u8054\u5e2e\u52a9\u4e2d\u5fc3\",\"description\":\"\u9999\u6e2f\u670d\u52a1\u5668_\u9999\u6e2f\u4e91\u670d\u52a1\u5668\u8d44\u8baf_\u670d\u52a1\u5668\u5e2e\u52a9\u6587\u6863_\u670d\u52a1\u5668\u6559\u7a0b\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.wsisp.com\/helps\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"zh-Hans\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/www.wsisp.com\/helps\/#\/schema\/person\/358e386c577a3ab51c4493330a20ad41\",\"name\":\"admin\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"zh-Hans\",\"@id\":\"https:\/\/www.wsisp.com\/helps\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/gravatar.wp-china-yes.net\/avatar\/?s=96&d=mystery\",\"contentUrl\":\"https:\/\/gravatar.wp-china-yes.net\/avatar\/?s=96&d=mystery\",\"caption\":\"admin\"},\"sameAs\":[\"http:\/\/wp.wsisp.com\"],\"url\":\"https:\/\/www.wsisp.com\/helps\/author\/admin\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"day 40 python\u6253\u5361 - \u7f51\u7855\u4e92\u8054\u5e2e\u52a9\u4e2d\u5fc3","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.wsisp.com\/helps\/41734.html","og_locale":"zh_CN","og_type":"article","og_title":"day 40 python\u6253\u5361 - \u7f51\u7855\u4e92\u8054\u5e2e\u52a9\u4e2d\u5fc3","og_description":"\u6587\u7ae0\u6d4f\u89c8\u9605\u8bfb231\u6b21\u3002\u4ed4\u7ec6\u5b66\u4e60\u4e0b\u6d4b\u8bd5\u548c\u8bad\u7ec3\u4ee3\u7801\u7684\u903b\u8f91\uff0c\u8fd9\u662f\u57fa\u7840\uff0c\u8fd9\u4e2a\u4ee3\u7801\u6846\u67b6\u540e\u7eed\u4f1a\u4e00\u76f4\u6cbf\u7528\uff0c\u540e\u7eed\u7684\u91cd\u70b9\u6162\u6162\u5c31\u662f\u8f6c\u5411\u6a21\u578b\u5b9a\u4e49\u9636\u6bb5\u4e86\u3002","og_url":"https:\/\/www.wsisp.com\/helps\/41734.html","og_site_name":"\u7f51\u7855\u4e92\u8054\u5e2e\u52a9\u4e2d\u5fc3","article_published_time":"2025-06-03T19:23:50+00:00","author":"admin","twitter_card":"summary_large_image","twitter_misc":{"\u4f5c\u8005":"admin","\u9884\u8ba1\u9605\u8bfb\u65f6\u95f4":"5 \u5206"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.wsisp.com\/helps\/41734.html","url":"https:\/\/www.wsisp.com\/helps\/41734.html","name":"day 40 python\u6253\u5361 - \u7f51\u7855\u4e92\u8054\u5e2e\u52a9\u4e2d\u5fc3","isPartOf":{"@id":"https:\/\/www.wsisp.com\/helps\/#website"},"datePublished":"2025-06-03T19:23:50+00:00","dateModified":"2025-06-03T19:23:50+00:00","author":{"@id":"https:\/\/www.wsisp.com\/helps\/#\/schema\/person\/358e386c577a3ab51c4493330a20ad41"},"breadcrumb":{"@id":"https:\/\/www.wsisp.com\/helps\/41734.html#breadcrumb"},"inLanguage":"zh-Hans","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.wsisp.com\/helps\/41734.html"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.wsisp.com\/helps\/41734.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"\u9996\u9875","item":"https:\/\/www.wsisp.com\/helps"},{"@type":"ListItem","position":2,"name":"day 40 python\u6253\u5361"}]},{"@type":"WebSite","@id":"https:\/\/www.wsisp.com\/helps\/#website","url":"https:\/\/www.wsisp.com\/helps\/","name":"\u7f51\u7855\u4e92\u8054\u5e2e\u52a9\u4e2d\u5fc3","description":"\u9999\u6e2f\u670d\u52a1\u5668_\u9999\u6e2f\u4e91\u670d\u52a1\u5668\u8d44\u8baf_\u670d\u52a1\u5668\u5e2e\u52a9\u6587\u6863_\u670d\u52a1\u5668\u6559\u7a0b","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.wsisp.com\/helps\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"zh-Hans"},{"@type":"Person","@id":"https:\/\/www.wsisp.com\/helps\/#\/schema\/person\/358e386c577a3ab51c4493330a20ad41","name":"admin","image":{"@type":"ImageObject","inLanguage":"zh-Hans","@id":"https:\/\/www.wsisp.com\/helps\/#\/schema\/person\/image\/","url":"https:\/\/gravatar.wp-china-yes.net\/avatar\/?s=96&d=mystery","contentUrl":"https:\/\/gravatar.wp-china-yes.net\/avatar\/?s=96&d=mystery","caption":"admin"},"sameAs":["http:\/\/wp.wsisp.com"],"url":"https:\/\/www.wsisp.com\/helps\/author\/admin"}]}},"_links":{"self":[{"href":"https:\/\/www.wsisp.com\/helps\/wp-json\/wp\/v2\/posts\/41734","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wsisp.com\/helps\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wsisp.com\/helps\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wsisp.com\/helps\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wsisp.com\/helps\/wp-json\/wp\/v2\/comments?post=41734"}],"version-history":[{"count":0,"href":"https:\/\/www.wsisp.com\/helps\/wp-json\/wp\/v2\/posts\/41734\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wsisp.com\/helps\/wp-json\/wp\/v2\/media?parent=41734"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wsisp.com\/helps\/wp-json\/wp\/v2\/categories?post=41734"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wsisp.com\/helps\/wp-json\/wp\/v2\/tags?post=41734"},{"taxonomy":"topic","embeddable":true,"href":"https:\/\/www.wsisp.com\/helps\/wp-json\/wp\/v2\/topic?post=41734"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}