{"id":1642,"date":"2025-02-03T19:56:38","date_gmt":"2025-02-03T11:56:38","guid":{"rendered":"https:\/\/www.forillusion.com\/?p=1642"},"modified":"2025-02-14T11:39:02","modified_gmt":"2025-02-14T03:39:02","slug":"3-7-softmax-regression-pytorch","status":"publish","type":"post","link":"https:\/\/www.forillusion.com\/index.php\/3-7-softmax-regression-pytorch\/","title":{"rendered":"3.7 softmax\u56de\u5f52\u7684\u7b80\u6d01\u5b9e\u73b0"},"content":{"rendered":"\n<p><div class=\"has-toc have-toc\"><\/div><\/p>\n\n\n\n<p id=\"20250203195216-shjbe1d\">\u5bfc\u5165\u9700\u8981\u7684\u5e93<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import torch\nfrom torch import nn\nfrom torch.nn import init\nimport numpy as np\nimport sys\nimport torchvision\nfrom torch.utils import data\nfrom torchvision import transforms\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"\u83b7\u53d6\u548c\u8bfb\u53d6\u6570\u636e\">\u83b7\u53d6\u548c\u8bfb\u53d6\u6570\u636e<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>def get_dataloader_workers():\n    if sys.platform.startswith('win'):\n        return 0\n    else:\n        return 4\n\ndef load_data_fashion_mnist(batch_size, resize=None): \n    # \u4e0b\u8f7dFashion-MNIST\u6570\u636e\u96c6\uff0c\u7136\u540e\u5c06\u5176\u52a0\u8f7d\u5230\u5185\u5b58\u4e2d\uff0c\u8fd4\u56de\u8bad\u7ec3\u96c6\u548c\u6d4b\u8bd5\u96c6\u7684\u6570\u636e\u8fed\u4ee3\u5668\n    mnist_train = torchvision.datasets.FashionMNIST(root=\"data\", train=True, transform=transforms.ToTensor(), download=True)\n    mnist_test = torchvision.datasets.FashionMNIST(root=\"data\", train=False, transform=transforms.ToTensor(), download=True)\n    return (data.DataLoader(mnist_train, batch_size, shuffle=True, num_workers=get_dataloader_workers()),\n            data.DataLoader(mnist_test, batch_size, shuffle=False, num_workers=get_dataloader_workers()))\n\nbatch_size = 256\ntrain_iter, test_iter = load_data_fashion_mnist(batch_size)\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"\u5b9a\u4e49\u548c\u521d\u59cb\u5316\u6a21\u578b\">\u5b9a\u4e49\u548c\u521d\u59cb\u5316\u6a21\u578b<\/h2>\n\n\n\n<p id=\"20250203163444-91a1jgj\">softmax\u56de\u5f52\u7684\u8f93\u51fa\u5c42\u662f\u4e00\u4e2a\u5168\u8fde\u63a5\u5c42\uff0c\u6240\u4ee5\u7528\u4e00\u4e2a\u7ebf\u6027\u6a21\u5757\u5c31\u53ef\u4ee5\u4e86\u3002<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>num_inputs = 28*28*1\nnum_outputs = 10\n\nclass LinearNet(nn.Module):\n    def __init__(self, num_inputs, num_outputs):\n        super(LinearNet, self).__init__()\n        self.linear = nn.Linear(num_inputs, num_outputs) # nn.Linear(input_size, output_size), \u8be5\u7ebf\u6027\u5c42\u7684\u8f93\u5165\u7279\u5f81\u6570\u4e3anum_inputs\uff0c\u8f93\u51fa\u7279\u5f81\u6570\u4e3a1\n  \n    def forward(self, x): # \u524d\u9762\u6570\u636e\u8fd4\u56de\u7684\u6bcf\u4e2abatch\u6837\u672cx\u7684\u5f62\u72b6\u4e3a(batch_size, 1, 28, 28), \u8981\u5148\u7528view()\u5c06x\u7684\u5f62\u72b6\u8f6c\u6362\u6210(batch_size, 784)\u624d\u9001\u5165\u5168\u8fde\u63a5\u5c42\u3002\n        y = self.linear(x.view(x.shape&#91;0], -1)) # \u7b49\u4ef7\u4e8e y = xw + b\n        return y\n\nnet = LinearNet(num_inputs, num_outputs)\n\n# \u7528OrederedDict\u5b9a\u4e49\u7f51\u7edc\n# class FlattenLayer(nn.Module):\n#     def __init__(self):\n#         super(FlattenLayer, self).__init__()\n#     def forward(self, x): \n#         return x.view(x.shape&#91;0], -1) # x \u7684\u5f62\u72b6\u8f6c\u6362\u6210(batch, 784)\uff0cx.shape&#91;0]\u8868\u793abatch_size\uff0c-1\u8868\u793a\u81ea\u52a8\u63a8\u6d4b\n\n\n# from collections import OrderedDict\n\n# net = nn.Sequential(\n#     OrderedDict(&#91; # \u662f\u4e00\u4e2a\u6709\u5e8f\u5b57\u5178\n#         ('flatten', FlattenLayer()), # \u5c06\u8f93\u5165x\u5c55\u5e73\n#         ('linear', nn.Linear(num_inputs, num_outputs)) # \u5168\u8fde\u63a5\u5c42\n#     ])\n# )\n<\/code><\/pre>\n\n\n\n<p id=\"20250203164340-3aoyn38\">\u521d\u59cb\u5316\u6a21\u578b\u53c2\u6570\uff1a<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>init.normal_(net.linear.weight, mean=0, std=0.01) # \u6b63\u6001\u5206\u5e03\u521d\u59cb\u5316\ninit.constant_(net.linear.bias, val=0) \n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"softmax\u548c\u4ea4\u53c9\u71b5\u635f\u5931\u51fd\u6570\">softmax\u548c\u4ea4\u53c9\u71b5\u635f\u5931\u51fd\u6570<\/h2>\n\n\n\n<p id=\"20250203173805-v11bmsm\">\u5206\u5f00\u5b9a\u4e49softmax\u8fd0\u7b97\u548c\u4ea4\u53c9\u71b5\u635f\u5931\u51fd\u6570\u53ef\u80fd\u4f1a\u9020\u6210\u6570\u503c\u4e0d\u7a33\u5b9a\u3002PyTorch\u63d0\u4f9b\u4e86\u4e00\u4e2a\u5305\u62ecsoftmax\u8fd0\u7b97\u548c\u4ea4\u53c9\u71b5\u635f\u5931\u8ba1\u7b97\u7684\u51fd\u6570\u3002\u5b83\u7684\u6570\u503c\u7a33\u5b9a\u6027\u66f4\u597d\u3002<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>loss = nn.CrossEntropyLoss() # \u4ea4\u53c9\u71b5\u635f\u5931\u51fd\u6570\uff0c\u5176\u4e2d\u5305\u62ecsoftmax\u8fd0\u7b97\u548c\u4ea4\u53c9\u71b5\u635f\u5931\u8ba1\u7b97\n# \u5148\u7528softmax\u8fd0\u7b97\u5f97\u5230\u7c7b\u522b\u7684\u6982\u7387\u5206\u5e03\uff0c\u518d\u7528\u4ea4\u53c9\u71b5\u635f\u5931\u8ba1\u7b97\u5f97\u5230\u4ea4\u53c9\u71b5\u635f\u5931\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"\u5b9a\u4e49\u4f18\u5316\u7b97\u6cd5\">\u5b9a\u4e49\u4f18\u5316\u7b97\u6cd5<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>optimizer = torch.optim.SGD(net.parameters(), lr=0.1) # \u8c03\u7528optim\u5b9e\u4f8b\u7684step\u51fd\u6570\u6765\u8fed\u4ee3\u6a21\u578b\u53c2\u6570\n# net.parameters()\u8fd4\u56de\u4e00\u4e2a\u5305\u542b\u6a21\u578b\u6240\u6709\u53c2\u6570\u7684\u751f\u6210\u5668\uff0c\u6bcf\u4e2a\u53c2\u6570\u662f\u4e00\u4e2atensor\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"\u8bad\u7ec3\u6a21\u578b\">\u8bad\u7ec3\u6a21\u578b<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>def evaluate_accuracy(data_iter, net):\n    acc_sum, n = 0.0, 0\n    for X, y in data_iter: # X\u662f\u56fe\u50cf\uff0cy\u662f\u6807\u7b7e\uff0c\u6570\u91cf\u4e3abatch_size\n        acc_sum += (net(X).argmax(dim=1) == y).float().sum().item() # net(X) \u8fd4\u56de\u9884\u6d4b\u6982\u7387\uff0cargmax(dim=1)\u8fd4\u56de\u6982\u7387\u6700\u5927\u7684\u7c7b\u522b\uff0c\u4e0e\u6807\u7b7ey\u6bd4\u8f83\n        n += y.shape&#91;0] # y.shape&#91;0]\u662fy\u7684\u884c\u6570\uff0c\u4e5f\u5c31\u662fbatch_size\n    return acc_sum \/ n # \u8fd4\u56de\u6b63\u786e\u7387\n\ndef train_ch3(net, train_iter, test_iter, loss, num_epochs, batch_size, params=None, lr=None, optimizer=None): \n    for epoch in range(num_epochs):  # \u8bad\u7ec3\u6a21\u578b\u4e00\u5171\u9700\u8981num_epochs\u4e2a\u8fed\u4ee3\u5468\u671f\n        train_l_sum, train_acc_sum, n = 0.0, 0.0, 0 # \u8bad\u7ec3\u635f\u5931\u603b\u548c\uff0c\u8bad\u7ec3\u51c6\u786e\u5ea6\u603b\u548c\uff0c\u6837\u672c\u6570\n        for X, y in train_iter: # X\u662f\u56fe\u50cf\uff0cy\u662f\u6807\u7b7e\uff0c\u6570\u91cf\u4e3abatch_size\n            y_hat = net(X) # \u9884\u6d4b\u6982\u7387\n            l = loss(y_hat, y).sum() # \u8ba1\u7b97\u635f\u5931\uff0csum()\u5c06\u6240\u6709loss\u503c\u76f8\u52a0\u5f97\u5230\u4e00\u4e2a\u6807\u91cf\n            optimizer.zero_grad() # \u68af\u5ea6\u6e05\u96f6\n            l.backward() # \u8ba1\u7b97\u68af\u5ea6\n            optimizer.step()  # \u66f4\u65b0\u6a21\u578b\u53c2\u6570\n\n            train_l_sum += l.item() # \u5c06\u5f53\u524d\u6279\u6b21loss\u503c\u76f8\u52a0\u5f97\u5230\u4e00\u4e2a\u603b\u7684loss\u503c\n            train_acc_sum += (y_hat.argmax(dim=1) == y).sum().item() # \u8ba1\u7b97\u603b\u51c6\u786e\u7387\n            n += y.shape&#91;0] # y.shape&#91;0]\u662fy\u7684\u884c\u6570\uff0c\u4e5f\u5c31\u662fbatch_size\uff0c\u8ba1\u7b97\u603b\u6837\u672c\u6570\n\n        test_acc = evaluate_accuracy(test_iter, net) # \u8ba1\u7b97\u6d4b\u8bd5\u96c6\u51c6\u786e\u7387\n        print('\u5468\u671f %d, \u635f\u5931 %.4f, \u6570\u636e\u96c6\u51c6\u786e\u7387 %.3f, \u6d4b\u8bd5\u96c6\u51c6\u786e\u7387 %.3f'\n              % (epoch + 1, train_l_sum \/ n, train_acc_sum \/ n, test_acc))\n\n\n# \u8bad\u7ec3\u6a21\u578b\nnum_epochs = 5\ntrain_ch3(net, train_iter, test_iter, loss, num_epochs, batch_size, None, None, optimizer)\n<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>\u5bfc\u5165\u9700\u8981\u7684\u5e93 \u83b7\u53d6\u548c\u8bfb\u53d6\u6570\u636e \u5b9a\u4e49\u548c\u521d\u59cb\u5316\u6a21\u578b softmax\u56de\u5f52\u7684\u8f93\u51fa\u5c42\u662f\u4e00\u4e2a\u5168\u8fde\u63a5\u5c42\uff0c\u6240\u4ee5\u7528\u4e00\u4e2a\u7ebf\u6027\u6a21\u5757\u5c31\u53ef\u4ee5\u4e86\u3002 \u521d\u59cb\u5316\u6a21\u578b &#8230;<\/p>","protected":false},"author":1,"featured_media":1644,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[46,3],"tags":[45,44,12,22],"class_list":["post-1642","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-46","category-3","tag-45","tag-44","tag-12","tag-22"],"_links":{"self":[{"href":"https:\/\/www.forillusion.com\/index.php\/wp-json\/wp\/v2\/posts\/1642","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.forillusion.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.forillusion.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.forillusion.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.forillusion.com\/index.php\/wp-json\/wp\/v2\/comments?post=1642"}],"version-history":[{"count":1,"href":"https:\/\/www.forillusion.com\/index.php\/wp-json\/wp\/v2\/posts\/1642\/revisions"}],"predecessor-version":[{"id":1715,"href":"https:\/\/www.forillusion.com\/index.php\/wp-json\/wp\/v2\/posts\/1642\/revisions\/1715"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.forillusion.com\/index.php\/wp-json\/wp\/v2\/media\/1644"}],"wp:attachment":[{"href":"https:\/\/www.forillusion.com\/index.php\/wp-json\/wp\/v2\/media?parent=1642"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.forillusion.com\/index.php\/wp-json\/wp\/v2\/categories?post=1642"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.forillusion.com\/index.php\/wp-json\/wp\/v2\/tags?post=1642"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}