{"id":4940,"date":"2024-10-28T16:29:21","date_gmt":"2024-10-28T08:29:21","guid":{"rendered":"http:\/\/cnliutz.ipyingshe.net\/?p=4940"},"modified":"2024-10-28T16:46:01","modified_gmt":"2024-10-28T08:46:01","slug":"%e4%bd%bf%e7%94%a8pytorch%e5%ae%9e%e7%8e%b0%e7%ba%bf%e6%80%a7%e5%9b%9e%e5%bd%92%e6%a8%a1%e5%9e%8b%e7%9a%84%e4%bb%a3%e7%a0%81","status":"publish","type":"post","link":"http:\/\/strawberry.ipyingshe.net:5347\/?p=4940","title":{"rendered":"\u4f7f\u7528PyTorch\u5b9e\u73b0\u7ebf\u6027\u56de\u5f52\u6a21\u578b\u7684\u4ee3\u7801"},"content":{"rendered":"\n<pre class=\"wp-block-code\"><code>#\u4f7f\u7528 PyTorch \u5b9e\u73b0\u7ebf\u6027\u56de\u5f52\u6a21\u578b\u7684\u4ee3\u7801\nimport torch\nimport torch.nn as nn\nimport  matplotlib.pyplot as plt\n\n\n# \u751f\u6210\u6a21\u62df\u6570\u636e\ntorch.manual_seed(42)\nx = torch.linspace(-1, 1, 100).view(-1, 1)\ny = 2 * x + 1 + 0.3 * torch.randn(x.size())\n\n# \u5b9a\u4e49\u7ebf\u6027\u56de\u5f52\u6a21\u578b\nclass LinearRegressionModel(nn.Module):\n    def __init__(self):\n        super(LinearRegressionModel, self).__init__()\n        self.linear = nn.Linear(1, 1)\n\n    def forward(self, x):\n        return self.linear(x)\n\nmodel = LinearRegressionModel()\n\n# \u5b9a\u4e49\u635f\u5931\u51fd\u6570\u548c\u4f18\u5316\u5668\ncriterion = nn.MSELoss()\noptimizer = torch.optim.SGD(model.parameters(), lr=0.01)\n\n# \u8bad\u7ec3\u6a21\u578b\nepochs = 1000\nfor epoch in range(epochs):\n    optimizer.zero_grad()\n    outputs = model(x)\n    loss = criterion(outputs, y)\n    loss.backward()\n    optimizer.step()\n\n    if (epoch + 1) % 100 == 0:\n        print(f'Epoch &#91;{epoch + 1}\/{epochs}], Loss: {loss.item()}')\n\n# \u8fdb\u884c\u9884\u6d4b\nwith torch.no_grad():\n    predicted = model(x)\n\n# \u7ed8\u5236\u7ed3\u679c\nplt.scatter(x.numpy(), y.numpy(), label='True data')\nplt.plot(x.numpy(), predicted.numpy(), 'r', label='Predicted')\nplt.legend()\nplt.show()\n'''\n\u5728\u8fd9\u6bb5\u4ee3\u7801\u4e2d\uff0c\u9996\u5148\u751f\u6210\u4e86\u6a21\u62df\u7684\u7ebf\u6027\u6570\u636e\uff0c\u5e76\u6dfb\u52a0\u4e86\u4e00\u4e9b\u566a\u58f0\u3002\n\u7136\u540e\u5b9a\u4e49\u4e86\u4e00\u4e2a\u7ebf\u6027\u56de\u5f52\u6a21\u578b\uff0c\u5305\u542b\u4e00\u4e2a\u7ebf\u6027\u5c42\u3002\n\u63a5\u7740\u4f7f\u7528\u5747\u65b9\u8bef\u5dee\u635f\u5931\u51fd\u6570\u548c\u968f\u673a\u68af\u5ea6\u4e0b\u964d\u4f18\u5316\u5668\u8fdb\u884c\u6a21\u578b\u8bad\u7ec3\u3002\n\u6700\u540e\uff0c\u8fdb\u884c\u9884\u6d4b\u5e76\u7ed8\u5236\u51fa\u771f\u5b9e\u6570\u636e\u548c\u9884\u6d4b\u7ed3\u679c\u7684\u5bf9\u6bd4\u56fe\u3002\n'''<\/code><\/pre>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"642\" height=\"554\" src=\"http:\/\/cnliutz.ipyingshe.net\/wp-content\/uploads\/2024\/10\/line.png\" alt=\"\" class=\"wp-image-4942\" srcset=\"http:\/\/strawberry.ipyingshe.net:5347\/wp-content\/uploads\/2024\/10\/line.png 642w, http:\/\/strawberry.ipyingshe.net:5347\/wp-content\/uploads\/2024\/10\/line-300x259.png 300w\" sizes=\"auto, (max-width: 642px) 100vw, 642px\" \/><\/figure>\n\n\n\n<pre class=\"wp-block-code\"><code>#\u4f7f\u7528 PyTorch \u5728 GPU \u4e0a\u8fdb\u884c\u7ebf\u6027\u56de\u5f52\u7684\u4ee3\u7801\u5b9e\u4f8b\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\n\n# \u8bbe\u7f6e\u8bbe\u5907\u4e3a GPU\uff08\u5982\u679c\u53ef\u7528\uff09\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nprint(f'Using device: {device}')\n# \u751f\u6210\u6a21\u62df\u6570\u636e\ntorch.manual_seed(42)\nx = torch.randn(100, 1).to(device)\ny = 3 * x + 2 + torch.randn(100, 1).to(device)\n\n# \u5b9a\u4e49\u7ebf\u6027\u56de\u5f52\u6a21\u578b\nclass LinearRegression(nn.Module):\n    def __init__(self):\n        super(LinearRegression, self).__init__()\n        self.linear = nn.Linear(1, 1)\n\n    def forward(self, x):\n        return self.linear(x)\n\nmodel = LinearRegression().to(device)\n\n# \u5b9a\u4e49\u635f\u5931\u51fd\u6570\u548c\u4f18\u5316\u5668\ncriterion = nn.MSELoss()\noptimizer = optim.SGD(model.parameters(), lr=0.01)\n\n# \u8bad\u7ec3\u6a21\u578b\nnum_epochs = 1000\nfor epoch in range(num_epochs):\n    # \u5c06\u6570\u636e\u548c\u6a21\u578b\u90fd\u79fb\u5230 GPU\n    inputs = x.to(device)\n    targets = y.to(device)\n    outputs = model(inputs)\n    loss = criterion(outputs, targets)\n    optimizer.zero_grad()\n    loss.backward()\n    optimizer.step()\n\n    if (epoch + 1) % 100 == 0:\n        print(f'Epoch &#91;{epoch+1}\/{num_epochs}], Loss: {loss.item()}')\n\n# \u5728 GPU \u4e0a\u8fdb\u884c\u9884\u6d4b\nwith torch.no_grad():\n    test_input = torch.tensor(&#91;&#91;4.0]]).to(device)\n    predicted = model(test_input)\n    print(f'Predicted value for input 4.0: {predicted.item()}')\n\n'''\n\u5728\u8fd9\u4e2a\u4f8b\u5b50\u4e2d\uff0c\u9996\u5148\u68c0\u67e5\u662f\u5426\u6709\u53ef\u7528\u7684 GPU\uff0c\u5982\u679c\u6709\u5219\u5c06\u8bbe\u5907\u8bbe\u7f6e\u4e3a GPU\u3002\n\u7136\u540e\u751f\u6210\u6a21\u62df\u6570\u636e\u5e76\u5c06\u5176\u79fb\u5230 GPU \u4e0a\u3002\u5b9a\u4e49\u7ebf\u6027\u56de\u5f52\u6a21\u578b\u5e76\u5c06\u5176\u4e5f\u79fb\u5230 GPU\u3002\n\u4f7f\u7528\u5747\u65b9\u8bef\u5dee\u635f\u5931\u51fd\u6570\u548c\u968f\u673a\u68af\u5ea6\u4e0b\u964d\u4f18\u5316\u5668\u8fdb\u884c\u6a21\u578b\u8bad\u7ec3\u3002\u6700\u540e\uff0c\u5728 GPU \u4e0a\u8fdb\u884c\u9884\u6d4b\u5e76\u8f93\u51fa\u7ed3\u679c\u3002\n'''\n<\/code><\/pre>\n\n\n\n<p>[Running] python -u &#8220;d:\\python\\torch_gpu.py&#8221;<\/p>\n\n\n\n<p>Using device: cpu<br>Epoch [100\/1000], Loss: 0.917326033115387<br>Epoch [200\/1000], Loss: 0.7827349305152893<br>Epoch [300\/1000], Loss: 0.7804043292999268<br>Epoch [400\/1000], Loss: 0.7803614735603333<br>Epoch [500\/1000], Loss: 0.7803605794906616<br>Epoch [600\/1000], Loss: 0.7803605794906616<br>Epoch [700\/1000], Loss: 0.7803606390953064<br>Epoch [800\/1000], Loss: 0.7803606390953064<br>Epoch [900\/1000], Loss: 0.7803606390953064<br>Epoch [1000\/1000], Loss: 0.7803606390953064<br><br>Predicted value for input 4.0: 14.082897186279297<\/p>\n\n\n\n<p>[Done] exited with code=0 in 2.915 seconds<\/p>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>[Running] python -u &#8220;d:\\python\\tor <span class=\"readmore\"><a href=\"http:\/\/strawberry.ipyingshe.net:5347\/?p=4940\">Continue Reading<\/a><\/span><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2,11],"tags":[],"class_list":["post-4940","post","type-post","status-publish","format-standard","hentry","category-2","category-11"],"_links":{"self":[{"href":"http:\/\/strawberry.ipyingshe.net:5347\/index.php?rest_route=\/wp\/v2\/posts\/4940","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/strawberry.ipyingshe.net:5347\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/strawberry.ipyingshe.net:5347\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/strawberry.ipyingshe.net:5347\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/strawberry.ipyingshe.net:5347\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=4940"}],"version-history":[{"count":3,"href":"http:\/\/strawberry.ipyingshe.net:5347\/index.php?rest_route=\/wp\/v2\/posts\/4940\/revisions"}],"predecessor-version":[{"id":4945,"href":"http:\/\/strawberry.ipyingshe.net:5347\/index.php?rest_route=\/wp\/v2\/posts\/4940\/revisions\/4945"}],"wp:attachment":[{"href":"http:\/\/strawberry.ipyingshe.net:5347\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=4940"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/strawberry.ipyingshe.net:5347\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=4940"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/strawberry.ipyingshe.net:5347\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=4940"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}