{"id":43450,"date":"2025-06-12T15:28:29","date_gmt":"2025-06-12T07:28:29","guid":{"rendered":"https:\/\/www.wsisp.com\/helps\/43450.html"},"modified":"2025-06-12T15:28:29","modified_gmt":"2025-06-12T07:28:29","slug":"%e3%80%90%e6%97%a0%e6%a0%87%e9%a2%98%e3%80%91","status":"publish","type":"post","link":"https:\/\/www.wsisp.com\/helps\/43450.html","title":{"rendered":"\u3010\u65e0\u6807\u9898\u3011"},"content":{"rendered":"<p>Day51<\/p>\n<p>import torch<br \/>\nimport torch.nn as nn<br \/>\nimport torch.optim as optim<br \/>\nimport torchvision<br \/>\nimport torchvision.transforms as transforms<br \/>\nimport matplotlib.pyplot as plt<br \/>\nimport numpy as np<\/p>\n<p># \u8bbe\u7f6e\u968f\u673a\u79cd\u5b50\u4ee5\u786e\u4fdd\u7ed3\u679c\u53ef\u590d\u73b0<br \/>\ntorch.manual_seed(42)<\/p>\n<p># \u5b9a\u4e49\u6570\u636e\u9884\u5904\u7406<br \/>\ntransform &#061; transforms.Compose([<br \/>\n    transforms.ToTensor(),<br \/>\n    transforms.Normalize((0.1307,), (0.3081,))<br \/>\n])<\/p>\n<p># \u52a0\u8f7dMNIST\u6570\u636e\u96c6<br \/>\ntrain_dataset &#061; torchvision.datasets.MNIST(<br \/>\n    root&#061;&#039;.\/data&#039;, train&#061;True, download&#061;True, transform&#061;transform)<br \/>\ntest_dataset &#061; torchvision.datasets.MNIST(<br \/>\n    root&#061;&#039;.\/data&#039;, train&#061;False, download&#061;True, transform&#061;transform)<\/p>\n<p># \u521b\u5efa\u6570\u636e\u52a0\u8f7d\u5668<br \/>\ntrain_loader &#061; torch.utils.data.DataLoader(<br \/>\n    train_dataset, batch_size&#061;64, shuffle&#061;True)<br \/>\ntest_loader &#061; torch.utils.data.DataLoader(<br \/>\n    test_dataset, batch_size&#061;1000, shuffle&#061;False)<\/p>\n<p># \u5b9a\u4e49CNN\u6a21\u578b<br \/>\nclass SimpleCNN(nn.Module):<br \/>\n    def __init__(self):<br \/>\n        super(SimpleCNN, self).__init__()<br \/>\n        self.conv1 &#061; nn.Conv2d(1, 32, kernel_size&#061;3, stride&#061;1, padding&#061;1)<br \/>\n        self.relu1 &#061; nn.ReLU()<br \/>\n        self.pool1 &#061; nn.MaxPool2d(kernel_size&#061;2)<br \/>\n        self.conv2 &#061; nn.Conv2d(32, 64, kernel_size&#061;3, stride&#061;1, padding&#061;1)<br \/>\n        self.relu2 &#061; nn.ReLU()<br \/>\n        self.pool2 &#061; nn.MaxPool2d(kernel_size&#061;2)<br \/>\n        self.fc1 &#061; nn.Linear(64 * 7 * 7, 128)<br \/>\n        self.relu3 &#061; nn.ReLU()<br \/>\n        self.fc2 &#061; nn.Linear(128, 10)<\/p>\n<p>    def forward(self, x):<br \/>\n        x &#061; self.pool1(self.relu1(self.conv1(x)))<br \/>\n        x &#061; self.pool2(self.relu2(self.conv2(x)))<br \/>\n        x &#061; x.view(-1, 64 * 7 * 7)<br \/>\n        x &#061; self.relu3(self.fc1(x))<br \/>\n        x &#061; self.fc2(x)<br \/>\n        return x<\/p>\n<p># \u521d\u59cb\u5316\u6a21\u578b\u3001\u635f\u5931\u51fd\u6570\u548c\u4f18\u5316\u5668<br \/>\ndevice &#061; torch.device(&#034;cuda&#034; if torch.cuda.is_available() else &#034;cpu&#034;)<br \/>\nmodel &#061; SimpleCNN().to(device)<br \/>\ncriterion &#061; nn.CrossEntropyLoss()<br \/>\noptimizer &#061; optim.Adam(model.parameters(), lr&#061;0.001)<\/p>\n<p># \u8bad\u7ec3\u6a21\u578b<br \/>\ndef train(epoch):<br \/>\n    model.train()<br \/>\n    train_loss &#061; 0<br \/>\n    correct &#061; 0<br \/>\n    total &#061; 0<\/p>\n<p>    for batch_idx, (inputs, targets) in enumerate(train_loader):<br \/>\n        inputs, targets &#061; inputs.to(device), targets.to(device)<\/p>\n<p>        optimizer.zero_grad()<br \/>\n        outputs &#061; model(inputs)<br \/>\n        loss &#061; criterion(outputs, targets)<br \/>\n        loss.backward()<br \/>\n        optimizer.step()<\/p>\n<p>        train_loss &#043;&#061; loss.item()<br \/>\n        _, predicted &#061; outputs.max(1)<br \/>\n        total &#043;&#061; targets.size(0)<br \/>\n        correct &#043;&#061; predicted.eq(targets).sum().item()<\/p>\n<p>        if batch_idx % 100 &#061;&#061; 0:<br \/>\n            print(f&#039;Epoch: {epoch} | Batch: {batch_idx} | Loss: {train_loss\/(batch_idx&#043;1):.3f} | Acc: {100.*correct\/total:.3f}%&#039;)<\/p>\n<p>    return train_loss \/ len(train_loader), 100. * correct \/ total<\/p>\n<p># \u6d4b\u8bd5\u6a21\u578b<br \/>\ndef test():<br \/>\n    model.eval()<br \/>\n    test_loss &#061; 0<br \/>\n    correct &#061; 0<br \/>\n    total &#061; 0<\/p>\n<p>    with torch.no_grad():<br \/>\n        for batch_idx, (inputs, targets) in enumerate(test_loader):<br \/>\n            inputs, targets &#061; inputs.to(device), targets.to(device)<br \/>\n            outputs &#061; model(inputs)<br \/>\n            loss &#061; criterion(outputs, targets)<\/p>\n<p>            test_loss &#043;&#061; loss.item()<br \/>\n            _, predicted &#061; outputs.max(1)<br \/>\n            total &#043;&#061; targets.size(0)<br \/>\n            correct &#043;&#061; predicted.eq(targets).sum().item()<\/p>\n<p>    print(f&#039;Test Loss: {test_loss\/len(test_loader):.3f} | Test Acc: {100.*correct\/total:.3f}%&#039;)<br \/>\n    return test_loss \/ len(test_loader), 100. * correct \/ total<\/p>\n<p># \u8bad\u7ec3\u548c\u6d4b\u8bd5\u6a21\u578b<br \/>\nepochs &#061; 5<br \/>\ntrain_losses, train_accs &#061; [], []<br \/>\ntest_losses, test_accs &#061; [], []<\/p>\n<p>for epoch in range(1, epochs &#043; 1):<br \/>\n    train_loss, train_acc &#061; train(epoch)<br \/>\n    test_loss, test_acc &#061; test()<\/p>\n<p>    train_losses.append(train_loss)<br \/>\n    train_accs.append(train_acc)<br \/>\n    test_losses.append(test_loss)<br \/>\n    test_accs.append(test_acc)<\/p>\n<p># \u7ed8\u5236\u8bad\u7ec3\u548c\u6d4b\u8bd5\u66f2\u7ebf<br \/>\nplt.figure(figsize&#061;(12, 5))<br \/>\nplt.subplot(1, 2, 1)<br \/>\nplt.plot(train_losses, label&#061;&#039;Train Loss&#039;)<br \/>\nplt.plot(test_losses, label&#061;&#039;Test Loss&#039;)<br \/>\nplt.xlabel(&#039;Epoch&#039;)<br \/>\nplt.ylabel(&#039;Loss&#039;)<br \/>\nplt.legend()<br \/>\nplt.title(&#039;Loss Curves&#039;)<\/p>\n<p>plt.subplot(1, 2, 2)<br \/>\nplt.plot(train_accs, label&#061;&#039;Train Accuracy&#039;)<br \/>\nplt.plot(test_accs, label&#061;&#039;Test Accuracy&#039;)<br \/>\nplt.xlabel(&#039;Epoch&#039;)<br \/>\nplt.ylabel(&#039;Accuracy (%)&#039;)<br \/>\nplt.legend()<br \/>\nplt.title(&#039;Accuracy Curves&#039;)<\/p>\n<p>plt.tight_layout()<br \/>\nplt.savefig(&#039;cnn_training_curves.png&#039;)<br \/>\nplt.show()<\/p>\n<p># \u53ef\u89c6\u5316\u4e00\u4e9b\u6d4b\u8bd5\u7ed3\u679c<br \/>\ndef visualize_results():<br \/>\n    model.eval()<br \/>\n    samples &#061; next(iter(test_loader))<br \/>\n    images, labels &#061; samples[0][:10].to(device), samples[1][:10]<\/p>\n<p>    with torch.no_grad():<br \/>\n        outputs &#061; model(images)<br \/>\n        _, predicted &#061; torch.max(outputs, 1)<\/p>\n<p>    fig &#061; plt.figure(figsize&#061;(12, 5))<br \/>\n    for i in range(10):<br \/>\n        ax &#061; fig.add_subplot(2, 5, i&#043;1, xticks&#061;[], yticks&#061;[])<br \/>\n        ax.imshow(images[i].cpu().squeeze(), cmap&#061;&#039;gray&#039;)<br \/>\n        ax.set_title(f&#039;Pred: {predicted[i].item()}, True: {labels[i].item()}&#039;,<br \/>\n                    color&#061;(&#034;green&#034; if predicted[i] &#061;&#061; labels[i] else &#034;red&#034;))<\/p>\n<p>    plt.tight_layout()<br \/>\n    plt.savefig(&#039;cnn_prediction_examples.png&#039;)<br \/>\n    plt.show()<\/p>\n<p>visualize_results()<\/p>\n<p>&#064;\u6d59\u5927\u758f\u9526\u884c<\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u6587\u7ae0\u6d4f\u89c8\u9605\u8bfb269\u6b21\u3002\u3010\u4ee3\u7801\u3011\u3010\u65e0\u6807\u9898\u3011<\/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":[4027],"topic":[],"class_list":["post-43450","post","type-post","status-publish","format-standard","hentry","category-server","tag-cocoa"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v20.3 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>\u3010\u65e0\u6807\u9898\u3011 - \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\/43450.html\" \/>\n<meta property=\"og:locale\" content=\"zh_CN\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"\u3010\u65e0\u6807\u9898\u3011 - \u7f51\u7855\u4e92\u8054\u5e2e\u52a9\u4e2d\u5fc3\" \/>\n<meta property=\"og:description\" content=\"\u6587\u7ae0\u6d4f\u89c8\u9605\u8bfb269\u6b21\u3002\u3010\u4ee3\u7801\u3011\u3010\u65e0\u6807\u9898\u3011\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.wsisp.com\/helps\/43450.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-12T07:28:29+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=\"3 \u5206\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.wsisp.com\/helps\/43450.html\",\"url\":\"https:\/\/www.wsisp.com\/helps\/43450.html\",\"name\":\"\u3010\u65e0\u6807\u9898\u3011 - \u7f51\u7855\u4e92\u8054\u5e2e\u52a9\u4e2d\u5fc3\",\"isPartOf\":{\"@id\":\"https:\/\/www.wsisp.com\/helps\/#website\"},\"datePublished\":\"2025-06-12T07:28:29+00:00\",\"dateModified\":\"2025-06-12T07:28:29+00:00\",\"author\":{\"@id\":\"https:\/\/www.wsisp.com\/helps\/#\/schema\/person\/358e386c577a3ab51c4493330a20ad41\"},\"breadcrumb\":{\"@id\":\"https:\/\/www.wsisp.com\/helps\/43450.html#breadcrumb\"},\"inLanguage\":\"zh-Hans\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.wsisp.com\/helps\/43450.html\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.wsisp.com\/helps\/43450.html#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"\u9996\u9875\",\"item\":\"https:\/\/www.wsisp.com\/helps\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"\u3010\u65e0\u6807\u9898\u3011\"}]},{\"@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":"\u3010\u65e0\u6807\u9898\u3011 - \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\/43450.html","og_locale":"zh_CN","og_type":"article","og_title":"\u3010\u65e0\u6807\u9898\u3011 - \u7f51\u7855\u4e92\u8054\u5e2e\u52a9\u4e2d\u5fc3","og_description":"\u6587\u7ae0\u6d4f\u89c8\u9605\u8bfb269\u6b21\u3002\u3010\u4ee3\u7801\u3011\u3010\u65e0\u6807\u9898\u3011","og_url":"https:\/\/www.wsisp.com\/helps\/43450.html","og_site_name":"\u7f51\u7855\u4e92\u8054\u5e2e\u52a9\u4e2d\u5fc3","article_published_time":"2025-06-12T07:28:29+00:00","author":"admin","twitter_card":"summary_large_image","twitter_misc":{"\u4f5c\u8005":"admin","\u9884\u8ba1\u9605\u8bfb\u65f6\u95f4":"3 \u5206"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.wsisp.com\/helps\/43450.html","url":"https:\/\/www.wsisp.com\/helps\/43450.html","name":"\u3010\u65e0\u6807\u9898\u3011 - \u7f51\u7855\u4e92\u8054\u5e2e\u52a9\u4e2d\u5fc3","isPartOf":{"@id":"https:\/\/www.wsisp.com\/helps\/#website"},"datePublished":"2025-06-12T07:28:29+00:00","dateModified":"2025-06-12T07:28:29+00:00","author":{"@id":"https:\/\/www.wsisp.com\/helps\/#\/schema\/person\/358e386c577a3ab51c4493330a20ad41"},"breadcrumb":{"@id":"https:\/\/www.wsisp.com\/helps\/43450.html#breadcrumb"},"inLanguage":"zh-Hans","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.wsisp.com\/helps\/43450.html"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.wsisp.com\/helps\/43450.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"\u9996\u9875","item":"https:\/\/www.wsisp.com\/helps"},{"@type":"ListItem","position":2,"name":"\u3010\u65e0\u6807\u9898\u3011"}]},{"@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\/43450","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=43450"}],"version-history":[{"count":0,"href":"https:\/\/www.wsisp.com\/helps\/wp-json\/wp\/v2\/posts\/43450\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wsisp.com\/helps\/wp-json\/wp\/v2\/media?parent=43450"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wsisp.com\/helps\/wp-json\/wp\/v2\/categories?post=43450"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wsisp.com\/helps\/wp-json\/wp\/v2\/tags?post=43450"},{"taxonomy":"topic","embeddable":true,"href":"https:\/\/www.wsisp.com\/helps\/wp-json\/wp\/v2\/topic?post=43450"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}