PyTorch torch功能

2025-06-25 13:50 更新

一、PyTorch 簡介

PyTorch 是一款開源的機器學習框架,它具有動態(tài)計算圖、強大的 GPU 支持和易于使用的 API 等優(yōu)勢,廣泛應用于深度學習領域。

二、torch.nn.functional 模塊基礎

torch.nn.functional 是 PyTorch 中用于實現(xiàn)各種神經(jīng)網(wǎng)絡操作的函數(shù)集合。它提供了豐富的函數(shù)用于構建和訓練神經(jīng)網(wǎng)絡,包括卷積、池化、激活函數(shù)、損失函數(shù)等。

1. 卷積函數(shù)

卷積操作是卷積神經(jīng)網(wǎng)絡(CNN)的核心組件,用于提取數(shù)據(jù)的空間特征。

一維卷積

  1. import torch
  2. import torch.nn.functional as F
  3. ## 創(chuàng)建輸入張量 (batch_size, channels, length)
  4. inputs = torch.randn(20, 16, 50)
  5. ## 創(chuàng)建卷積核 (out_channels, in_channels, kernel_size)
  6. filters = torch.randn(33, 16, 3)
  7. ## 應用一維卷積
  8. output = F.conv1d(inputs, filters)
  9. print("輸入張量形狀:", inputs.shape)
  10. print("輸出張量形狀:", output.shape)

運行結果示例:

  1. 輸入張量形狀: torch.Size([20, 16, 50])
  2. 輸出張量形狀: torch.Size([20, 33, 48])

二維卷積

  1. ## 創(chuàng)建輸入張量 (batch_size, channels, height, width)
  2. inputs = torch.randn(1, 4, 5, 5)
  3. ## 創(chuàng)建卷積核 (out_channels, in_channels, kernel_height, kernel_width)
  4. filters = torch.randn(8, 4, 3, 3)
  5. ## 應用二維卷積,添加 padding
  6. output = F.conv2d(inputs, filters, padding=1)
  7. print("輸入張量形狀:", inputs.shape)
  8. print("輸出張量形狀:", output.shape)

運行結果示例:

  1. 輸入張量形狀: torch.Size([1, 4, 5, 5])
  2. 輸出張量形狀: torch.Size([1, 8, 5, 5])

三維卷積

  1. ## 創(chuàng)建輸入張量 (batch_size, channels, depth, height, width)
  2. inputs = torch.randn(20, 16, 50, 10, 20)
  3. ## 創(chuàng)建卷積核 (out_channels, in_channels, kernel_depth, kernel_height, kernel_width)
  4. filters = torch.randn(33, 16, 3, 3, 3)
  5. ## 應用三維卷積
  6. output = F.conv3d(inputs, filters)
  7. print("輸入張量形狀:", inputs.shape)
  8. print("輸出張量形狀:", output.shape)

運行結果示例:

  1. 輸入張量形狀: torch.Size([20, 16, 50, 10, 20])
  2. 輸出張量形狀: torch.Size([20, 33, 48, 8, 18])

2. 池化函數(shù)

池化操作用于對數(shù)據(jù)進行下采樣,減少數(shù)據(jù)量,同時保留重要特征。

平均池化

  1. ## 創(chuàng)建輸入張量 (batch_size, channels, length)
  2. inputs = torch.randn(1, 4, 50)
  3. ## 應用一維平均池化
  4. output = F.avg_pool1d(inputs, kernel_size=3, stride=2)
  5. print("輸入張量形狀:", inputs.shape)
  6. print("輸出張量形狀:", output.shape)

運行結果示例:

  1. 輸入張量形狀: torch.Size([1, 4, 50])
  2. 輸出張量形狀: torch.Size([1, 4, 24])

最大池化

  1. ## 創(chuàng)建輸入張量 (batch_size, channels, length)
  2. inputs = torch.randn(1, 4, 50)
  3. ## 應用一維最大池化
  4. output = F.max_pool1d(inputs, kernel_size=3, stride=2)
  5. print("輸入張量形狀:", inputs.shape)
  6. print("輸出張量形狀:", output.shape)

運行結果示例:

  1. 輸入張量形狀: torch.Size([1, 4, 50])
  2. 輸出張量形狀: torch.Size([1, 4, 24])

3. 激活函數(shù)

激活函數(shù)為神經(jīng)網(wǎng)絡引入非線性,使網(wǎng)絡能夠學習復雜的模式。

ReLU 激活函數(shù)

  1. ## 創(chuàng)建輸入張量
  2. inputs = torch.randn(2, 3)
  3. ## 應用 ReLU 激活函數(shù)
  4. output = F.relu(inputs)
  5. print("輸入張量:\n", inputs)
  6. print("輸出張量:\n", output)

運行結果示例:

  1. 輸入張量:
  2. tensor([[ 0.1234, -0.5678, 0.9012],
  3. [-1.2345, 0.6789, -0.3456]])
  4. 輸出張量:
  5. tensor([[ 0.1234, 0.0000, 0.9012],
  6. [ 0.0000, 0.6789, 0.0000]])

Sigmoid 激活函數(shù)

  1. ## 創(chuàng)建輸入張量
  2. inputs = torch.randn(2, 3)
  3. ## 應用 Sigmoid 激活函數(shù)
  4. output = F.sigmoid(inputs)
  5. print("輸入張量:\n", inputs)
  6. print("輸出張量:\n", output)

運行結果示例:

  1. 輸入張量:
  2. tensor([[ 0.1234, -0.5678, 0.9012],
  3. [-1.2345, 0.6789, -0.3456]])
  4. 輸出張量:
  5. tensor([[0.5312, 0.3622, 0.7109],
  6. [0.2242, 0.6642, 0.4156]])

4. 損失函數(shù)

損失函數(shù)用于衡量模型預測結果與真實值之間的差異。

均方誤差損失

  1. ## 創(chuàng)建預測值和真實值張量
  2. predictions = torch.randn(3, 5, requires_grad=True)
  3. targets = torch.randn(3, 5)
  4. ## 應用均方誤差損失
  5. loss = F.mse_loss(predictions, targets)
  6. print("損失值:", loss.item())

運行結果示例:

  1. 損失值: 0.8765

交叉熵損失

  1. ## 創(chuàng)建預測值和真實值張量
  2. predictions = torch.randn(3, 5, requires_grad=True)
  3. targets = torch.empty(3, dtype=torch.long).random_(5)
  4. ## 應用交叉熵損失
  5. loss = F.cross_entropy(predictions, targets)
  6. print("損失值:", loss.item())

運行結果示例:

  1. 損失值: 1.2345

三、代碼實操環(huán)節(jié)

實操 1:構建簡單的神經(jīng)網(wǎng)絡

  1. import torch
  2. import torch.nn as nn
  3. import torch.nn.functional as F
  4. ## 定義一個簡單的神經(jīng)網(wǎng)絡
  5. class SimpleNet(nn.Module):
  6. def __init__(self):
  7. super(SimpleNet, self).__init__()
  8. self.fc1 = nn.Linear(5, 10) # 輸入層到隱藏層
  9. self.fc2 = nn.Linear(10, 3) # 隱藏層到輸出層
  10. def forward(self, x):
  11. x = F.relu(self.fc1(x)) # 應用 ReLU 激活函數(shù)
  12. x = self.fc2(x)
  13. return x
  14. ## 創(chuàng)建網(wǎng)絡實例
  15. net = SimpleNet()
  16. ## 創(chuàng)建輸入數(shù)據(jù)
  17. input_data = torch.randn(2, 5)
  18. ## 前向傳播
  19. output = net(input_data)
  20. print("輸入數(shù)據(jù)形狀:", input_data.shape)
  21. print("輸出數(shù)據(jù)形狀:", output.shape)

運行結果示例:

  1. 輸入數(shù)據(jù)形狀: torch.Size([2, 5])
  2. 輸出數(shù)據(jù)形狀: torch.Size([2, 3])

實操 2:訓練神經(jīng)網(wǎng)絡

  1. ## 定義損失函數(shù)和優(yōu)化器
  2. criterion = nn.MSELoss()
  3. optimizer = torch.optim.SGD(net.parameters(), lr=0.01)
  4. ## 訓練數(shù)據(jù)
  5. train_data = torch.randn(100, 5)
  6. train_labels = torch.randn(100, 3)
  7. ## 訓練循環(huán)
  8. for epoch in range(100):
  9. # 前向傳播
  10. outputs = net(train_data)
  11. loss = criterion(outputs, train_labels)
  12. # 反向傳播和優(yōu)化
  13. optimizer.zero_grad()
  14. loss.backward()
  15. optimizer.step()
  16. if (epoch+1) % 10 == 0:
  17. print(f'Epoch [{epoch+1}/100], Loss: {loss.item():.4f}')

運行結果示例:

  1. Epoch [10/100], Loss: 0.8765
  2. Epoch [20/100], Loss: 0.7654
  3. ...
  4. Epoch [100/100], Loss: 0.1234

四、總結與展望

本教程從零基礎出發(fā),帶領大家認識了 PyTorch 環(huán)境,了解了 torch.nn.functional 模塊中的基本概念,包括卷積函數(shù)、池化函數(shù)、激活函數(shù)和損失函數(shù)等內容,并通過代碼實操環(huán)節(jié)加深了對所學知識的理解。后續(xù)可以繼續(xù)探索更多 PyTorch 相關知識,如自動梯度、神經(jīng)網(wǎng)絡的構建與訓練等。

希望這篇教程能夠幫助大家更好地入門 PyTorch,如果在學習過程中有任何疑問,歡迎訪問編程獅(W3Cschool)官網(wǎng)獲取更多資源和支持。

以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號