{"id":1576,"date":"2024-07-29T12:51:06","date_gmt":"2024-07-29T04:51:06","guid":{"rendered":"https:\/\/www.forillusion.com\/?p=1576"},"modified":"2025-02-14T11:39:02","modified_gmt":"2025-02-14T03:39:02","slug":"3-3-linear-regression-pytorch","status":"publish","type":"post","link":"https:\/\/www.forillusion.com\/index.php\/3-3-linear-regression-pytorch\/","title":{"rendered":"3.3 \u7ebf\u6027\u56de\u5f52\u7684\u7b80\u6d01\u5b9e\u73b0"},"content":{"rendered":"\n<p>  <div class=\"has-toc have-toc\"><\/div> <\/p>\n\n\n\n<h2 class=\"wp-block-heading\">\u751f\u6210\u6570\u636e\u96c6<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code class=\"python\">import torch\n\nnum_inputs=2   #\u7279\u5f81\u6570\nnum_examples=1000  #\u6837\u672c\u6570\ntrue_w=&#91;2,-3.4]  #\u771f\u5b9e\u6743\u91cd\ntrue_b=4.2   #\u771f\u5b9e\u504f\u5dee\nfeatures=torch.randn(num_examples,num_inputs,dtype=torch.float32)  #\u751f\u6210\u7279\u5f81\nlabels=true_w&#91;0]*features&#91;:,0]+true_w&#91;1]*features&#91;:,1]+true_b  #\u751f\u6210\u6807\u7b7e &#91;:,0]\u8868\u793a\u53d6\u6240\u6709\u884c\u7684\u7b2c0\u4e2a\u5143\u7d20\nlabels+=torch.tensor(torch.normal(0,0.01,size=labels.size()),dtype=torch.float32)  #\u52a0\u5165\u566a\u58f0\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">\u8bfb\u53d6\u6570\u636e<\/h2>\n\n\n\n<p>PyTorch\u63d0\u4f9b\u4e86<code>data<\/code>\u5305\u6765\u8bfb\u53d6\u6570\u636e\u3002\u7531\u4e8e<code>data<\/code>\u5e38\u7528\u4f5c\u53d8\u91cf\u540d\uff0c\u6240\u4ee5\u5c06\u5bfc\u5165\u7684<code>data<\/code>\u6a21\u5757\u7528<code>Data<\/code>\u4ee3\u66ff\u3002<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code class=\"python\">import torch.utils.data as Data\n\nbatch_size = 10\ndataset = Data.TensorDataset(features, labels) # \u5c06\u8bad\u7ec3\u6570\u636e\u7684\u7279\u5f81\u548c\u6807\u7b7e\u7ec4\u5408\ndata_iter = Data.DataLoader(dataset, batch_size, shuffle=True) # \u968f\u673a\u8bfb\u53d6\u5c0f\u6279\u91cf<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">\u5b9a\u4e49\u6a21\u578b<\/h2>\n\n\n\n<p>PyTorch\u63d0\u4f9b\u4e86\u5927\u91cf\u9884\u5b9a\u4e49\u7684\u5c42\uff0c\u53ef\u4ee5\u7528PyTorch\u66f4\u7b80\u6d01\u5730\u5b9a\u4e49\u7ebf\u6027\u56de\u5f52\u3002<\/p>\n\n\n\n<p>\u9996\u5148\uff0c\u5bfc\u5165<code>torch.nn<\/code>\u6a21\u5757\u3002\u201cnn\u201d\u662fneural networks\uff08\u795e\u7ecf\u7f51\u7edc\uff09\u7684\u7f29\u5199\u3002\u8be5\u6a21\u5757\u5b9a\u4e49\u4e86\u5927\u91cf\u795e\u7ecf\u7f51\u7edc\u7684\u5c42\u3002<code>nn<\/code>\u5229\u7528<code>autograd<\/code>\u6765\u5b9a\u4e49\u6a21\u578b\u3002<code>nn<\/code>\u7684\u6838\u5fc3\u6570\u636e\u7ed3\u6784\u662f<code>Module<\/code>\uff0c\u5b83\u662f\u4e00\u4e2a\u62bd\u8c61\u6982\u5ff5\uff0c\u65e2\u53ef\u4ee5\u8868\u793a\u795e\u7ecf\u7f51\u7edc\u4e2d\u7684\u67d0\u4e2a\u5c42\uff08layer\uff09\uff0c\u4e5f\u53ef\u4ee5\u8868\u793a\u4e00\u4e2a\u5305\u542b\u5f88\u591a\u5c42\u7684\u795e\u7ecf\u7f51\u7edc\u3002\u5728\u5b9e\u9645\u4f7f\u7528\u4e2d\uff0c\u6700\u5e38\u89c1\u7684\u505a\u6cd5\u662f\u7ee7\u627f<code>nn.Module<\/code>\uff0c\u64b0\u5199\u81ea\u5df1\u7684\u7f51\u7edc\/\u5c42\u3002\u4e00\u4e2a<code>nn.Module<\/code>\u5b9e\u4f8b\u5e94\u8be5\u5305\u542b\u4e00\u4e9b\u5c42\u4ee5\u53ca\u8fd4\u56de\u8f93\u51fa\u7684\u524d\u5411\u4f20\u64ad\uff08forward\uff09\u65b9\u6cd5\u3002<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code class=\"python\">import torch.nn as nn\n\nclass LinearNet(nn.Module):\n    def __init__(self, n_feature): # n_feature\u8868\u793a\u7279\u5f81\u6570\n        super(LinearNet, self).__init__()\n        self.linear = nn.Linear(n_feature, 1) # nn.Linear(input_size, output_size), \u8be5\u7ebf\u6027\u5c42\u7684\u8f93\u5165\u7279\u5f81\u6570\u4e3an_feature\uff0c\u8f93\u51fa\u7279\u5f81\u6570\u4e3a1\n    # forward \u5b9a\u4e49\u524d\u5411\u4f20\u64ad\n    def forward(self, x):\n        y = self.linear(x) # \u7b49\u4ef7\u4e8e y = xw + b\n        return y\n\nnet = LinearNet(num_inputs)\nprint(net) # \u4f7f\u7528print\u53ef\u4ee5\u6253\u5370\u51fa\u7f51\u7edc\u7684\u7ed3\u6784<\/code><\/pre>\n\n\n\n<p>\u4e5f\u53ef\u4ee5\u7528<code>nn.Sequential<\/code>\u6765\u66f4\u52a0\u65b9\u4fbf\u5730\u642d\u5efa\u7f51\u7edc\uff0c<code>Sequential<\/code>\u662f\u4e00\u4e2a\u6709\u5e8f\u7684\u5bb9\u5668\uff0c\u7f51\u7edc\u5c42\u5c06\u6309\u7167\u5728\u4f20\u5165<code>Sequential<\/code>\u7684\u987a\u5e8f\u4f9d\u6b21\u88ab\u6dfb\u52a0\u5230\u8ba1\u7b97\u56fe\u4e2d\u3002<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code class=\"python\"># \u5199\u6cd5\u4e00\nnet = nn.Sequential(\n    nn.Linear(num_inputs, 1)\n    # \u6b64\u5904\u8fd8\u53ef\u4ee5\u4f20\u5165\u5176\u4ed6\u5c42\n    )\n\n# \u5199\u6cd5\u4e8c\nnet = nn.Sequential()\nnet.add_module('linear', nn.Linear(num_inputs, 1))\n# net.add_module ......\n\n# \u5199\u6cd5\u4e09\nfrom collections import OrderedDict\nnet = nn.Sequential(OrderedDict(&#91;\n          ('linear', nn.Linear(num_inputs, 1))\n          # ......\n        ]))<\/code><\/pre>\n\n\n\n<p>\u53ef\u4ee5\u901a\u8fc7<code>net.parameters()<\/code>\u6765\u67e5\u770b\u6a21\u578b\u6240\u6709\u7684\u53ef\u5b66\u4e60\u53c2\u6570\uff0c\u6b64\u51fd\u6570\u5c06\u8fd4\u56de\u4e00\u4e2a\u751f\u6210\u5668\u3002<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code class=\"python\">for param in net.parameters():\n    print(param)<\/code><\/pre>\n\n\n\n<p>\u6ce8\u610f\uff1a<code>torch.nn<\/code>\u4ec5\u652f\u6301\u8f93\u5165\u4e00\u4e2abatch\u7684\u6837\u672c\u4e0d\u652f\u6301\u5355\u4e2a\u6837\u672c\u8f93\u5165\uff0c\u5982\u679c\u53ea\u6709\u5355\u4e2a\u6837\u672c\uff0c\u53ef\u4f7f\u7528<code>input.unsqueeze(0)<\/code>\u6765\u6dfb\u52a0\u4e00\u7ef4\u3002<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">\u521d\u59cb\u5316\u6a21\u578b\u53c2\u6570<\/h2>\n\n\n\n<p>\u5728\u4f7f\u7528<code>net<\/code>\u524d\uff0c\u9700\u8981\u521d\u59cb\u5316\u6a21\u578b\u53c2\u6570\uff0c\u5982\u7ebf\u6027\u56de\u5f52\u6a21\u578b\u4e2d\u7684\u6743\u91cd\u548c\u504f\u5dee\u3002PyTorch\u5728<code>init<\/code>\u6a21\u5757\u4e2d\u63d0\u4f9b\u4e86\u591a\u79cd\u53c2\u6570\u521d\u59cb\u5316\u65b9\u6cd5\u3002\u8fd9\u91cc\u7684<code>init<\/code>\u662f<code>initializer<\/code>\u7684\u7f29\u5199\u5f62\u5f0f\u3002\u901a\u8fc7<code>init.normal_<\/code>\u5c06\u6743\u91cd\u53c2\u6570\u6bcf\u4e2a\u5143\u7d20\u521d\u59cb\u5316\u4e3a\u968f\u673a\u91c7\u6837\u4e8e\u5747\u503c\u4e3a0\u3001\u6807\u51c6\u5dee\u4e3a0.01\u7684\u6b63\u6001\u5206\u5e03\u3002\u504f\u5dee\u4f1a\u521d\u59cb\u5316\u4e3a\u96f6\u3002<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code class=\"python\">from torch.nn import init\n\ninit.normal_(net&#91;0].weight, mean=0, std=0.01) # \u6b63\u6001\u5206\u5e03\u521d\u59cb\u5316\n# init.constant_(net&#91;0].bias, val=0)  # \u4e5f\u53ef\u4ee5\u76f4\u63a5\u4fee\u6539bias\u7684data: net&#91;0].bias.data.fill_(0)\n<\/code><\/pre>\n\n\n\n<p>\u6ce8\uff1a\u5982\u679c\u8fd9\u91cc\u7684<code>net<\/code>\u662f\u7528\u4e00\u5f00\u59cb\u7684\u4ee3\u7801\u81ea\u5b9a\u4e49\u7684\uff0c\u90a3\u4e48\u4e0a\u9762\u4ee3\u7801\u4f1a\u62a5\u9519\uff0c<code>net[0].weight<\/code>\u5e94\u6539\u4e3a<code>net.linear.weight<\/code>\uff0c<code>bias<\/code>\u4ea6\u7136\u3002\u56e0\u4e3a<code>net[0]<\/code>\u8fd9\u6837\u6839\u636e\u4e0b\u6807\u8bbf\u95ee\u5b50\u6a21\u5757\u7684\u5199\u6cd5\u53ea\u6709\u5f53<code>net<\/code>\u662f\u4e2a<code>ModuleList<\/code>\u6216\u8005<code>Sequential<\/code>\u5b9e\u4f8b\u65f6\u624d\u53ef\u4ee5\u3002<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">\u5b9a\u4e49\u635f\u5931\u51fd\u6570<\/h2>\n\n\n\n<p>PyTorch\u5728<code>nn<\/code>\u6a21\u5757\u4e2d\u63d0\u4f9b\u4e86\u5404\u79cd\u635f\u5931\u51fd\u6570\uff0c\u8fd9\u4e9b\u635f\u5931\u51fd\u6570\u53ef\u770b\u4f5c\u662f\u4e00\u79cd\u7279\u6b8a\u7684\u5c42\uff0cPyTorch\u4e5f\u5c06\u8fd9\u4e9b\u635f\u5931\u51fd\u6570\u5b9e\u73b0\u4e3a<code>nn.Module<\/code>\u7684\u5b50\u7c7b\u3002\u73b0\u5728\u4f7f\u7528\u5b83\u63d0\u4f9b\u7684\u5747\u65b9\u8bef\u5dee\u635f\u5931\u4f5c\u4e3a\u6a21\u578b\u7684\u635f\u5931\u51fd\u6570\u3002<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code class=\"python\">loss = nn.MSELoss()<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">\u5b9a\u4e49\u4f18\u5316\u7b97\u6cd5<\/h2>\n\n\n\n<p><code>torch.optim<\/code>\u6a21\u5757\u63d0\u4f9b\u4e86\u5f88\u591a\u5e38\u7528\u7684\u4f18\u5316\u7b97\u6cd5\u6bd4\u5982SGD\u3001Adam\u548cRMSProp\u7b49\u3002\u4e0b\u9762\u5c06\u521b\u5efa\u4e00\u4e2a\u7528\u4e8e\u4f18\u5316<code>net<\/code>\u6240\u6709\u53c2\u6570\u7684\u4f18\u5316\u5668\u5b9e\u4f8b\uff0c\u5e76\u6307\u5b9a\u5b66\u4e60\u7387\u4e3a0.03\u7684\u5c0f\u6279\u91cf\u968f\u673a\u68af\u5ea6\u4e0b\u964d\uff08SGD\uff09\u4e3a\u4f18\u5316\u7b97\u6cd5\u3002<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code class=\"python\">import torch.optim as optim\n\noptimizer = optim.SGD(net.parameters(), lr=0.03) # \u8c03\u7528optim\u5b9e\u4f8b\u7684step\u51fd\u6570\u6765\u8fed\u4ee3\u6a21\u578b\u53c2\u6570\nprint(optimizer)<\/code><\/pre>\n\n\n\n<p>\u6211\u4eec\u8fd8\u53ef\u4ee5\u4e3a\u4e0d\u540c\u5b50\u7f51\u7edc\u8bbe\u7f6e\u4e0d\u540c\u7684\u5b66\u4e60\u7387\uff0c\u8fd9\u5728finetune\u65f6\u7ecf\u5e38\u7528\u5230\u3002\u4f8b\uff1a<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code class=\"python\">optimizer =optim.SGD(&#91;\n                # \u5982\u679c\u5bf9\u67d0\u4e2a\u53c2\u6570\u4e0d\u6307\u5b9a\u5b66\u4e60\u7387\uff0c\u5c31\u4f7f\u7528\u6700\u5916\u5c42\u7684\u9ed8\u8ba4\u5b66\u4e60\u7387\n                {'params': net.subnet1.parameters()}, # lr=0.03\n                {'params': net.subnet2.parameters(), 'lr': 0.01}\n            ], lr=0.03)\n<\/code><\/pre>\n\n\n\n<p>\u8c03\u6574\u5b66\u4e60\u7387\uff0c\u4e3b\u8981\u6709\u4e24\u79cd\u505a\u6cd5\u3002\u4e00\u79cd\u662f\u4fee\u6539<code>optimizer.param_groups<\/code>\u4e2d\u5bf9\u5e94\u7684\u5b66\u4e60\u7387\uff0c\u53e6\u4e00\u79cd\u662f\u66f4\u7b80\u5355\u4e5f\u662f\u8f83\u4e3a\u63a8\u8350\u7684\u505a\u6cd5\u2014\u2014\u65b0\u5efa\u4f18\u5316\u5668\uff0c\u7531\u4e8eoptimizer\u5341\u5206\u8f7b\u91cf\u7ea7\uff0c\u6784\u5efa\u5f00\u9500\u5f88\u5c0f\uff0c\u6545\u800c\u53ef\u4ee5\u6784\u5efa\u65b0\u7684optimizer\u3002\u4f46\u662f\u540e\u8005\u5bf9\u4e8e\u4f7f\u7528\u52a8\u91cf\u7684\u4f18\u5316\u5668\uff08\u5982Adam\uff09\uff0c\u4f1a\u4e22\u5931\u52a8\u91cf\u7b49\u72b6\u6001\u4fe1\u606f\uff0c\u53ef\u80fd\u4f1a\u9020\u6210\u635f\u5931\u51fd\u6570\u7684\u6536\u655b\u51fa\u73b0\u9707\u8361\u7b49\u60c5\u51b5\u3002<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code class=\"python\"># \u8c03\u6574\u5b66\u4e60\u7387\nfor param_group in optimizer.param_groups:\n    param_group&#91;'lr'] *= 0.1 # \u5b66\u4e60\u7387\u4e3a\u4e4b\u524d\u76840.1\u500d\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">\u8bad\u7ec3\u6a21\u578b<\/h2>\n\n\n\n<p>\u5728\u4f7f\u7528Gluon\u8bad\u7ec3\u6a21\u578b\u65f6\uff0c\u901a\u8fc7\u8c03\u7528<code>optim<\/code>\u5b9e\u4f8b\u7684<code>step<\/code>\u51fd\u6570\u6765\u8fed\u4ee3\u6a21\u578b\u53c2\u6570\u3002\u6309\u7167\u5c0f\u6279\u91cf\u968f\u673a\u68af\u5ea6\u4e0b\u964d\u7684\u5b9a\u4e49\uff0c\u5728<code>step<\/code>\u51fd\u6570\u4e2d\u6307\u660e\u6279\u91cf\u5927\u5c0f\uff0c\u4ece\u800c\u5bf9\u6279\u91cf\u4e2d\u6837\u672c\u68af\u5ea6\u6c42\u5e73\u5747\u3002<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code class=\"python\">num_epochs = 3 # \u8bbe\u7f6e\u8fed\u4ee3\u5468\u671f\nfor epoch in range(1, num_epochs + 1):\n    for X, y in data_iter: # X\u662f\u7279\u5f81\uff0cy\u662f\u6807\u7b7e\n        output = net(X) # \u901a\u8fc7\u5b9a\u4e49\u7684\u6a21\u578b\u5f97\u5230\u8f93\u51fa\n        l = loss(output, y.view(-1, 1)) # \u8ba1\u7b97\u635f\u5931\u51fd\u6570, view\u51fd\u6570\u5c06y\u53d8\u6210\u548coutput\u5f62\u72b6\u76f8\u540c, -1\u8868\u793a\u4e0d\u6307\u5b9a\u7ef4\u5ea6\u5927\u5c0f\uff0c\u8ba9\u7cfb\u7edf\u81ea\u52a8\u5206\u914d, 1\u8868\u793a\u5217\u6570\u4e3a1\n        optimizer.zero_grad() # \u68af\u5ea6\u6e05\u96f6\uff0c\u7b49\u4ef7\u4e8enet.zero_grad()\n        l.backward() # \u53cd\u5411\u4f20\u64ad\n        optimizer.step() # \u8fed\u4ee3\u6a21\u578b\u53c2\u6570\n    print('epoch %d, loss: %f' % (epoch, l.item()))\n\n\ndense = net&#91;0]\nprint(true_w, dense.weight)\nprint(true_b, dense.bias)<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>\u751f\u6210\u6570\u636e\u96c6 \u8bfb\u53d6\u6570\u636e PyTorch\u63d0\u4f9b\u4e86data\u5305\u6765\u8bfb\u53d6\u6570\u636e\u3002\u7531\u4e8edata\u5e38\u7528\u4f5c\u53d8\u91cf\u540d\uff0c\u6240\u4ee5\u5c06\u5bfc\u5165\u7684data\u6a21\u5757\u7528Data\u4ee3\u66ff\u3002 &#8230;<\/p>","protected":false},"author":1,"featured_media":1578,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[46,3],"tags":[45,44,12,22],"class_list":["post-1576","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\/1576","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=1576"}],"version-history":[{"count":1,"href":"https:\/\/www.forillusion.com\/index.php\/wp-json\/wp\/v2\/posts\/1576\/revisions"}],"predecessor-version":[{"id":1722,"href":"https:\/\/www.forillusion.com\/index.php\/wp-json\/wp\/v2\/posts\/1576\/revisions\/1722"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.forillusion.com\/index.php\/wp-json\/wp\/v2\/media\/1578"}],"wp:attachment":[{"href":"https:\/\/www.forillusion.com\/index.php\/wp-json\/wp\/v2\/media?parent=1576"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.forillusion.com\/index.php\/wp-json\/wp\/v2\/categories?post=1576"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.forillusion.com\/index.php\/wp-json\/wp\/v2\/tags?post=1576"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}