{"id":1658,"date":"2025-02-04T13:18:12","date_gmt":"2025-02-04T05:18:12","guid":{"rendered":"https:\/\/www.forillusion.com\/?p=1658"},"modified":"2025-02-14T11:39:02","modified_gmt":"2025-02-14T03:39:02","slug":"3-9-mlp-scratch","status":"publish","type":"post","link":"https:\/\/www.forillusion.com\/index.php\/3-9-mlp-scratch\/","title":{"rendered":"3.9 \u591a\u5c42\u611f\u77e5\u673a\u7684\u4ece\u96f6\u5f00\u59cb\u5b9e\u73b0"},"content":{"rendered":"\n<p><div class=\"has-toc have-toc\"><\/div><\/p>\n\n\n\n<p id=\"20250203215042-v7wrmi0\">\u5bfc\u5165\u9700\u8981\u7684\u5e93<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code class=\"python\">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 class=\"python\">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\u6a21\u578b\u53c2\u6570\">\u5b9a\u4e49\u6a21\u578b\u53c2\u6570<\/h2>\n\n\n\n<p id=\"20250203215811-trodwuk\">\u8f93\u5165\u4e2a\u6570\u4e3a784\uff0c\u8f93\u51fa\u4e2a\u6570\u4e3a10\u3002\u5b9e\u9a8c\u4e2d\uff0c\u8bbe\u8d85\u53c2\u6570\u9690\u85cf\u5355\u5143\u4e2a\u6570\u4e3a256\u3002<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code class=\"python\">num_inputs, num_outputs, num_hiddens = 784, 10, 256\n\nW1 = torch.tensor(np.random.normal(0, 0.01, (num_inputs, num_hiddens)), dtype=torch.float) # \u6b63\u6001\u5206\u5e03\u521d\u59cb\u5316\uff0c\u5747\u503c\u4e3a0\uff0c\u6807\u51c6\u5dee\u4e3a0.01\uff0c\u5f62\u72b6\u4e3a(784, 256)\nb1 = torch.zeros(num_hiddens, dtype=torch.float)\nW2 = torch.tensor(np.random.normal(0, 0.01, (num_hiddens, num_outputs)), dtype=torch.float) # \u6b63\u6001\u5206\u5e03\u521d\u59cb\u5316\uff0c\u5747\u503c\u4e3a0\uff0c\u6807\u51c6\u5dee\u4e3a0.01\uff0c\u5f62\u72b6\u4e3a(256, 10)\nb2 = torch.zeros(num_outputs, dtype=torch.float)\n\nparams = &#91;W1, b1, W2, b2] # \u53c2\u6570\u5217\u8868\nfor param in params:\n    param.requires_grad_(requires_grad=True) # \u5c06\u53c2\u6570\u7684requires_grad\u5c5e\u6027\u8bbe\u7f6e\u4e3aTrue\uff0c\u56e0\u4e3a\u4e4b\u524d\u9ed8\u8ba4\u662fFalse\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"\u5b9a\u4e49\u6fc0\u6d3b\u51fd\u6570\">\u5b9a\u4e49\u6fc0\u6d3b\u51fd\u6570<\/h2>\n\n\n\n<p id=\"20250203215900-kgeqwzv\">\u4f7f\u7528\u57fa\u7840\u7684max\u200b\u51fd\u6570\u6765\u5b9e\u73b0ReLU\uff0c\u800c\u975e\u76f4\u63a5\u8c03\u7528relu\u200b\u51fd\u6570\u3002<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code class=\"python\">def relu(X):\n    return torch.max(input=X, other=torch.tensor(0.0))\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"\u5b9a\u4e49\u6a21\u578b\">\u5b9a\u4e49\u6a21\u578b<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code class=\"python\">def net(X):\n    X = X.view((-1, num_inputs))  # X\u7684\u5f62\u72b6: (batch_size, 1, 28, 28) =&gt; (batch_size, 784)\n    H = relu(torch.matmul(X, W1) + b1) \n    return torch.matmul(H, W2) + b2\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"\u5b9a\u4e49\u635f\u5931\u51fd\u6570\">\u5b9a\u4e49\u635f\u5931\u51fd\u6570<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code class=\"python\">loss = torch.nn.CrossEntropyLoss()\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 class=\"python\">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\n# 3.2.6 \u5b9a\u4e49\u4f18\u5316\u7b97\u6cd5\ndef sgd(params,lr,batch_size):  #\u5b9a\u4e49\u4f18\u5316\u7b97\u6cd5,params:\u5f85\u4f18\u5316\u53c2\u6570,lr:\u5b66\u4e60\u7387,batch_size:\u6279\u91cf\u5927\u5c0f\n    for param in params:\n        param.data-=lr*param.grad\/batch_size  #\u6ce8\u610f\u8fd9\u91cc\u66f4\u6539param\u65f6\u7528\u7684param.data\n\n\ndef train_ch3(net, train_iter, test_iter, loss, num_epochs, batch_size, params=None, lr=None, optimizer=None): \n    # net: \u7f51\u7edc\uff0c\u5373\u7ebf\u6027\u56de\u5f52\u6a21\u578b\n    # train_iter: \u8bad\u7ec3\u6570\u636e\u96c6\uff0ctest_iter: \u6d4b\u8bd5\u6570\u636e\u96c6\n    # loss: \u635f\u5931\u51fd\u6570\uff0cnum_epochs: \u8bad\u7ec3\u7684\u8f6e\u6570\uff0cbatch_size: \u6279\u91cf\u5927\u5c0f\n    # params: \u6a21\u578b\u53c2\u6570\uff0c\u5373W\u548cb\uff0clr: \u5b66\u4e60\u7387\uff0coptimizer: \u4f18\u5316\u7b97\u6cd5\uff0c\u5982SGD\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\n            # \u68af\u5ea6\u6e05\u96f6\n            if optimizer is not None: # \u4f7f\u7528PyTorch\u5185\u7f6e\u7684\u4f18\u5316\u5668\u548c\u635f\u5931\u51fd\u6570\n                optimizer.zero_grad() # \u68af\u5ea6\u6e05\u96f6\n            elif params is not None and params&#91;0].grad is not None: # \u4f7f\u7528\u81ea\u5b9a\u4e49\u7684\u4f18\u5316\u5668\u548c\u635f\u5931\u51fd\u6570\n                for param in params: \n                    param.grad.data.zero_()\n\n            l.backward() # \u8ba1\u7b97\u68af\u5ea6\n            if optimizer is None: # \u4f7f\u7528PyTorch\u5185\u7f6e\u7684\u4f18\u5316\u5668\u548c\u635f\u5931\u51fd\u6570\n                sgd(params, lr, batch_size) # \u66f4\u65b0\u6a21\u578b\u53c2\u6570\n            else:\n                optimizer.step()  # \u201csoftmax\u56de\u5f52\u7684\u7b80\u6d01\u5b9e\u73b0\u201d\u4e00\u8282\u5c06\u7528\u5230\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\nnum_epochs, lr = 5, 100\ntrain_ch3(net, train_iter, test_iter, loss, num_epochs, batch_size, params, lr)\n<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>\u5bfc\u5165\u9700\u8981\u7684\u5e93 \u83b7\u53d6\u548c\u8bfb\u53d6\u6570\u636e \u5b9a\u4e49\u6a21\u578b\u53c2\u6570 \u8f93\u5165\u4e2a\u6570\u4e3a784\uff0c\u8f93\u51fa\u4e2a\u6570\u4e3a10\u3002\u5b9e\u9a8c\u4e2d\uff0c\u8bbe\u8d85\u53c2\u6570\u9690\u85cf\u5355\u5143\u4e2a\u6570\u4e3a256\u3002 \u5b9a\u4e49\u6fc0\u6d3b\u51fd\u6570 &#8230;<\/p>","protected":false},"author":1,"featured_media":1662,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[46,3],"tags":[45,44,12,22],"class_list":["post-1658","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\/1658","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=1658"}],"version-history":[{"count":1,"href":"https:\/\/www.forillusion.com\/index.php\/wp-json\/wp\/v2\/posts\/1658\/revisions"}],"predecessor-version":[{"id":1713,"href":"https:\/\/www.forillusion.com\/index.php\/wp-json\/wp\/v2\/posts\/1658\/revisions\/1713"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.forillusion.com\/index.php\/wp-json\/wp\/v2\/media\/1662"}],"wp:attachment":[{"href":"https:\/\/www.forillusion.com\/index.php\/wp-json\/wp\/v2\/media?parent=1658"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.forillusion.com\/index.php\/wp-json\/wp\/v2\/categories?post=1658"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.forillusion.com\/index.php\/wp-json\/wp\/v2\/tags?post=1658"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}