{"id":10021262,"date":"2026-02-20T14:46:13","date_gmt":"2026-02-20T06:46:13","guid":{"rendered":"https:\/\/itmax.cn\/?p=10021262"},"modified":"2026-02-20T14:46:13","modified_gmt":"2026-02-20T06:46:13","slug":"python-%e6%b7%b1%e5%ba%a6%e5%ad%a6%e4%b9%a0%ef%bc%9apytorch-%e7%a5%9e%e7%bb%8f%e7%bd%91%e7%bb%9c%e6%9e%84%e5%bb%ba","status":"publish","type":"post","link":"https:\/\/itmax.cn\/?p=10021262","title":{"rendered":"Python \u6df1\u5ea6\u5b66\u4e60\uff1aPyTorch \u795e\u7ecf\u7f51\u7edc\u6784\u5efa"},"content":{"rendered":"<h2>Python \u6df1\u5ea6\u5b66\u4e60\uff1aPyTorch \u795e\u7ecf\u7f51\u7edc\u6784\u5efa<\/h2>\n<p>\u6df1\u5ea6\u5b66\u4e60\u662f\u673a\u5668\u5b66\u4e60\u7684\u524d\u6cbf\u9886\u57df\uff0cPyTorch \u662f\u6700\u53d7\u6b22\u8fce\u7684\u6df1\u5ea6\u5b66\u4e60\u6846\u67b6\u4e4b\u4e00\u3002\u672c\u6587\u5c06\u6df1\u5165\u63a2\u8ba8 PyTorch \u7684\u795e\u7ecf\u7f51\u7edc\u6784\u5efa\u6280\u672f\uff0c\u5305\u62ec\u5f20\u91cf\u64cd\u4f5c\u3001\u81ea\u52a8\u5fae\u5206\u3001\u6a21\u578b\u8bad\u7ec3\u7b49\u6838\u5fc3\u6280\u672f\u3002<\/p>\n<h3>\u5f20\u91cf\u57fa\u7840<\/h3>\n<p>\u5f20\u91cf\u662f PyTorch \u7684\u57fa\u672c\u6570\u636e\u7ed3\u6784\uff0c\u7c7b\u4f3c\u4e8e NumPy \u6570\u7ec4\u4f46\u652f\u6301 GPU \u52a0\u901f\u3002<\/p>\n<pre><code class=\"python\">import torch\n\ndef tensor_basic_demo():\n    print(&quot;\u5f20\u91cf\u57fa\u7840\u6f14\u793a:&quot;)\n    \n    x = torch.tensor([1, 2, 3, 4])\n    print(f&quot;\u5f20\u91cf: {x}&quot;)\n    print(f&quot;\u5f20\u91cf\u7c7b\u578b: {x.dtype}&quot;)\n    print(f&quot;\u5f20\u91cf\u8bbe\u5907: {x.device}&quot;)\n    \n    y = torch.randn(2, 3)\n    print(f&quot;\u968f\u673a\u5f20\u91cf:\/n{y}&quot;)\n\ntensor_basic_demo()<\/code><\/pre>\n<h3>\u81ea\u52a8\u5fae\u5206<\/h3>\n<p>\u81ea\u52a8\u5fae\u5206\u81ea\u52a8\u8ba1\u7b97\u68af\u5ea6\uff0c\u662f\u795e\u7ecf\u7f51\u7edc\u8bad\u7ec3\u7684\u6838\u5fc3\u3002<\/p>\n<pre><code class=\"python\">def autograd_demo():\n    print(&quot;\u81ea\u52a8\u5fae\u5206\u6f14\u793a:&quot;)\n    \n    x = torch.tensor([2.0], requires_grad=True)\n    y = x ** 2 + 3 * x + 1\n    \n    y.backward()\n    \n    print(f&quot;x: {x.item()}&quot;)\n    print(f&quot;y: {y.item()}&quot;)\n    print(f&quot;dy\/dx: {x.grad.item()}&quot;)\n\nautograd_demo()<\/code><\/pre>\n<h3>\u795e\u7ecf\u7f51\u7edc\u5c42<\/h3>\n<p>\u795e\u7ecf\u7f51\u7edc\u5c42\u6784\u5efa\u6df1\u5ea6\u5b66\u4e60\u6a21\u578b\u7684\u57fa\u672c\u7ec4\u4ef6\u3002<\/p>\n<pre><code class=\"python\">import torch.nn as nn\n\ndef neural_network_layers_demo():\n    print(&quot;\u795e\u7ecf\u7f51\u7edc\u5c42\u6f14\u793a:&quot;)\n    \n    print(&quot;1. \u5168\u8fde\u63a5\u5c42&quot;)\n    fc = nn.Linear(10, 5)\n    print(f&quot;\u5168\u8fde\u63a5\u5c42: {fc}&quot;)\n    \n    print(&quot;2. \u5377\u79ef\u5c42&quot;)\n    conv = nn.Conv2d(3, 64, kernel_size=3)\n    print(f&quot;\u5377\u79ef\u5c42: {conv}&quot;)\n    \n    print(&quot;3. \u6c60\u5316\u5c42&quot;)\n    pool = nn.MaxPool2d(kernel_size=2)\n    print(f&quot;\u6c60\u5316\u5c42: {pool}&quot;)\n\nneural_network_layers_demo()<\/code><\/pre>\n<h3>\u6fc0\u6d3b\u51fd\u6570<\/h3>\n<p>\u6fc0\u6d3b\u51fd\u6570\u5f15\u5165\u975e\u7ebf\u6027\uff0c\u4f7f\u795e\u7ecf\u7f51\u7edc\u80fd\u591f\u5b66\u4e60\u590d\u6742\u6a21\u5f0f\u3002<\/p>\n<pre><code class=\"python\">def activation_functions_demo():\n    print(&quot;\u6fc0\u6d3b\u51fd\u6570\u6f14\u793a:&quot;)\n    \n    x = torch.linspace(-5, 5, 100)\n    \n    relu = nn.ReLU()\n    sigmoid = nn.Sigmoid()\n    tanh = nn.Tanh()\n    \n    print(f&quot;ReLU \u8f93\u51fa\u8303\u56f4: {relu(x).min():.2f} \u5230 {relu(x).max():.2f}&quot;)\n    print(f&quot;Sigmoid \u8f93\u51fa\u8303\u56f4: {sigmoid(x).min():.2f} \u5230 {sigmoid(x).max():.2f}&quot;)\n    print(f&quot;Tanh \u8f93\u51fa\u8303\u56f4: {tanh(x).min():.2f} \u5230 {tanh(x).max():.2f}&quot;)\n\nactivation_functions_demo()<\/code><\/pre>\n<h3>\u6df1\u5ea6\u5b66\u4e60\u67b6\u6784<\/h3>\n<pre style=\"display:none;\"><code class=\"mermaid\">graph TD\n    A[\u8f93\u5165\u6570\u636e] --&gt; B[\u8f93\u5165\u5c42]\n    B --&gt; C[\u9690\u85cf\u5c42 1]\n    C --&gt; D[\u9690\u85cf\u5c42 2]\n    D --&gt; E[\u9690\u85cf\u5c42 N]\n    E --&gt; F[\u8f93\u51fa\u5c42]\n    F --&gt; G[\u635f\u5931\u51fd\u6570]\n    G --&gt; H[\u4f18\u5316\u5668]\n    H --&gt; I[\u6a21\u578b\u66f4\u65b0]<\/code><\/pre>\n<h3>\u635f\u5931\u51fd\u6570<\/h3>\n<p>\u635f\u5931\u51fd\u6570\u8861\u91cf\u6a21\u578b\u9884\u6d4b\u4e0e\u771f\u5b9e\u6807\u7b7e\u4e4b\u95f4\u7684\u5dee\u8ddd\u3002<\/p>\n<pre><code class=\"python\">def loss_functions_demo():\n    print(&quot;\u635f\u5931\u51fd\u6570\u6f14\u793a:&quot;)\n    \n    print(&quot;1. \u5747\u65b9\u8bef\u5dee\u635f\u5931&quot;)\n    mse_loss = nn.MSELoss()\n    \n    print(&quot;2. \u4ea4\u53c9\u71b5\u635f\u5931&quot;)\n    ce_loss = nn.CrossEntropyLoss()\n    \n    print(&quot;3. \u4e8c\u5143\u4ea4\u53c9\u71b5\u635f\u5931&quot;)\n    bce_loss = nn.BCEWithLogitsLoss()\n\nloss_functions_demo()<\/code><\/pre>\n<h3>\u4f18\u5316\u5668<\/h3>\n<p>\u4f18\u5316\u5668\u6839\u636e\u68af\u5ea6\u66f4\u65b0\u6a21\u578b\u53c2\u6570\u3002<\/p>\n<pre><code class=\"python\">def optimizer_demo():\n    print(&quot;\u4f18\u5316\u5668\u6f14\u793a:&quot;)\n    \n    model = nn.Linear(10, 2)\n    \n    print(&quot;1. SGD \u4f18\u5316\u5668&quot;)\n    optimizer = torch.optim.SGD(model.parameters(), lr=0.01)\n    \n    print(&quot;2. Adam \u4f18\u5316\u5668&quot;)\n    optimizer = torch.optim.Adam(model.parameters(), lr=0.001)\n    \n    print(&quot;3. RMSprop \u4f18\u5316\u5668&quot;)\n    optimizer = torch.optim.RMSprop(model.parameters(), lr=0.001)\n\noptimizer_demo()<\/code><\/pre>\n<h3>\u6a21\u578b\u8bad\u7ec3<\/h3>\n<p>\u6a21\u578b\u8bad\u7ec3\u4f7f\u7528\u6570\u636e\u8fed\u4ee3\u66f4\u65b0\u6a21\u578b\u53c2\u6570\u3002<\/p>\n<pre><code class=\"python\">def model_training_demo():\n    print(&quot;\u6a21\u578b\u8bad\u7ec3\u6f14\u793a:&quot;)\n    \n    model = nn.Sequential(\n        nn.Linear(10, 50),\n        nn.ReLU(),\n        nn.Linear(50, 2)\n    )\n    \n    criterion = nn.CrossEntropyLoss()\n    optimizer = torch.optim.Adam(model.parameters(), lr=0.001)\n    \n    X = torch.randn(100, 10)\n    y = torch.randint(0, 2, (100,))\n    \n    for epoch in range(10):\n        optimizer.zero_grad()\n        outputs = model(X)\n        loss = criterion(outputs, y)\n        loss.backward()\n        optimizer.step()\n        \n        if (epoch + 1) % 2 == 0:\n            print(f'Epoch [{epoch+1}\/10], Loss: {loss.item():.4f}')\n\nmodel_training_demo()<\/code><\/pre>\n<h3>\u6570\u636e\u52a0\u8f7d<\/h3>\n<p>\u6570\u636e\u52a0\u8f7d\u9ad8\u6548\u5730\u52a0\u8f7d\u548c\u9884\u5904\u7406\u8bad\u7ec3\u6570\u636e\u3002<\/p>\n<pre><code class=\"python\">from torch.utils.data import Dataset, DataLoader\n\nclass CustomDataset(Dataset):\n    def __init__(self, X, y):\n        self.X = X\n        self.y = y\n    \n    def __len__(self):\n        return len(self.X)\n    \n    def __getitem__(self, idx):\n        return self.X[idx], self.y[idx]\n\ndef data_loading_demo():\n    print(&quot;\u6570\u636e\u52a0\u8f7d\u6f14\u793a:&quot;)\n    \n    X = torch.randn(1000, 10)\n    y = torch.randint(0, 2, (1000,))\n    \n    dataset = CustomDataset(X, y)\n    dataloader = DataLoader(dataset, batch_size=32, shuffle=True)\n    \n    for batch_X, batch_y in dataloader:\n        print(f&quot;\u6279\u6b21\u5f62\u72b6: {batch_X.shape}, {batch_y.shape}&quot;)\n        break\n\ndata_loading_demo()<\/code><\/pre>\n<h3>\u6a21\u578b\u8bc4\u4f30<\/h3>\n<p>\u6a21\u578b\u8bc4\u4f30\u4f7f\u7528\u6d4b\u8bd5\u6570\u636e\u8861\u91cf\u6a21\u578b\u6027\u80fd\u3002<\/p>\n<pre><code class=\"python\">def model_evaluation_demo():\n    print(&quot;\u6a21\u578b\u8bc4\u4f30\u6f14\u793a:&quot;)\n    \n    model.eval()\n    \n    with torch.no_grad():\n        outputs = model(X)\n        _, predicted = torch.max(outputs, 1)\n        accuracy = (predicted == y).float().mean()\n        \n        print(f&quot;\u51c6\u786e\u7387: {accuracy.item():.4f}&quot;)\n\nmodel_evaluation_demo()<\/code><\/pre>\n<h3>\u6a21\u578b\u4fdd\u5b58\u4e0e\u52a0\u8f7d<\/h3>\n<p>\u6a21\u578b\u4fdd\u5b58\u4e0e\u52a0\u8f7d\u6301\u4e45\u5316\u8bad\u7ec3\u597d\u7684\u6a21\u578b\u3002<\/p>\n<pre><code class=\"python\">def model_save_load_demo():\n    print(&quot;\u6a21\u578b\u4fdd\u5b58\u4e0e\u52a0\u8f7d\u6f14\u793a:&quot;)\n    \n    model = nn.Linear(10, 2)\n    \n    torch.save(model.state_dict(), 'model.pth')\n    \n    loaded_model = nn.Linear(10, 2)\n    loaded_model.load_state_dict(torch.load('model.pth'))\n    \n    print(&quot;\u6a21\u578b\u5df2\u4fdd\u5b58\u548c\u52a0\u8f7d&quot;)\n\nmodel_save_load_demo()<\/code><\/pre>\n<h3>GPU \u52a0\u901f<\/h3>\n<p>GPU \u52a0\u901f\u663e\u8457\u63d0\u9ad8\u8bad\u7ec3\u901f\u5ea6\u3002<\/p>\n<pre><code class=\"python\">def gpu_acceleration_demo():\n    print(&quot;GPU \u52a0\u901f\u6f14\u793a:&quot;)\n    \n    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n    print(f&quot;\u4f7f\u7528\u8bbe\u5907: {device}&quot;)\n    \n    model = nn.Linear(10, 2).to(device)\n    X = torch.randn(100, 10).to(device)\n    \n    outputs = model(X)\n    print(f&quot;\u8f93\u51fa\u8bbe\u5907: {outputs.device}&quot;)\n\ngpu_acceleration_demo()<\/code><\/pre>\n<h3>\u603b\u7ed3<\/h3>\n<p>PyTorch \u63d0\u4f9b\u4e86\u7075\u6d3b\u7684\u6df1\u5ea6\u5b66\u4e60\u6846\u67b6\uff0c\u652f\u6301\u4ece\u5f20\u91cf\u64cd\u4f5c\u5230\u6a21\u578b\u8bad\u7ec3\u7684\u5b8c\u6574\u6d41\u7a0b\u3002\u638c\u63e1\u8fd9\u4e9b\u6838\u5fc3\u6280\u672f\uff0c\u5bf9\u4e8e\u6784\u5efa\u6df1\u5ea6\u5b66\u4e60\u5e94\u7528\u81f3\u5173\u91cd\u8981\u3002<\/p>\n<p>\u5728\u5b9e\u9645\u5e94\u7528\u4e2d\uff0c\u9700\u8981\u6839\u636e\u4efb\u52a1\u7279\u70b9\u9009\u62e9\u5408\u9002\u7684\u7f51\u7edc\u7ed3\u6784\u548c\u8d85\u53c2\u6570\uff0c\u5e73\u8861\u6a21\u578b\u590d\u6742\u5ea6\u548c\u6027\u80fd\u3002\u826f\u597d\u7684\u6df1\u5ea6\u5b66\u4e60\u5b9e\u8df5\u80fd\u591f\u663e\u8457\u63d0\u9ad8\u6a21\u578b\u7684\u51c6\u786e\u6027\u548c\u8bad\u7ec3\u6548\u7387\u3002<\/p>\n<p><a href=\"https:\/\/segmentfault.com\/a\/1190000047614881\">https:\/\/segmentfault.com\/a\/1190000047614881<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Python \u6df1\u5ea6\u5b66\u4e60\uff1aPyTorch \u795e\u7ecf\u7f51\u7edc\u6784\u5efa \u6df1\u5ea6\u5b66\u4e60\u662f\u673a\u5668\u5b66\u4e60\u7684\u524d\u6cbf\u9886\u57df\uff0cPyTorch \u662f\u6700\u53d7\u6b22\u8fce [&hellip;]<\/p>\n","protected":false},"author":4,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[4],"tags":[],"class_list":["post-10021262","post","type-post","status-publish","format-standard","hentry","category-share"],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/itmax.cn\/index.php?rest_route=\/wp\/v2\/posts\/10021262","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/itmax.cn\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/itmax.cn\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/itmax.cn\/index.php?rest_route=\/wp\/v2\/users\/4"}],"replies":[{"embeddable":true,"href":"https:\/\/itmax.cn\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=10021262"}],"version-history":[{"count":0,"href":"https:\/\/itmax.cn\/index.php?rest_route=\/wp\/v2\/posts\/10021262\/revisions"}],"wp:attachment":[{"href":"https:\/\/itmax.cn\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=10021262"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/itmax.cn\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=10021262"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/itmax.cn\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=10021262"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}