W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
PyTorch 是一款開源的機器學習框架,它具有動態(tài)計算圖、強大的 GPU 支持和易于使用的 API 等優(yōu)勢,廣泛應用于深度學習領域。
torch.nn.functional
是 PyTorch 中用于實現(xiàn)各種神經(jīng)網(wǎng)絡操作的函數(shù)集合。它提供了豐富的函數(shù)用于構建和訓練神經(jīng)網(wǎng)絡,包括卷積、池化、激活函數(shù)、損失函數(shù)等。
卷積操作是卷積神經(jīng)網(wǎng)絡(CNN)的核心組件,用于提取數(shù)據(jù)的空間特征。
import torch
import torch.nn.functional as F
## 創(chuàng)建輸入張量 (batch_size, channels, length)
inputs = torch.randn(20, 16, 50)
## 創(chuàng)建卷積核 (out_channels, in_channels, kernel_size)
filters = torch.randn(33, 16, 3)
## 應用一維卷積
output = F.conv1d(inputs, filters)
print("輸入張量形狀:", inputs.shape)
print("輸出張量形狀:", output.shape)
運行結果示例:
輸入張量形狀: torch.Size([20, 16, 50])
輸出張量形狀: torch.Size([20, 33, 48])
## 創(chuàng)建輸入張量 (batch_size, channels, height, width)
inputs = torch.randn(1, 4, 5, 5)
## 創(chuàng)建卷積核 (out_channels, in_channels, kernel_height, kernel_width)
filters = torch.randn(8, 4, 3, 3)
## 應用二維卷積,添加 padding
output = F.conv2d(inputs, filters, padding=1)
print("輸入張量形狀:", inputs.shape)
print("輸出張量形狀:", output.shape)
運行結果示例:
輸入張量形狀: torch.Size([1, 4, 5, 5])
輸出張量形狀: torch.Size([1, 8, 5, 5])
## 創(chuàng)建輸入張量 (batch_size, channels, depth, height, width)
inputs = torch.randn(20, 16, 50, 10, 20)
## 創(chuàng)建卷積核 (out_channels, in_channels, kernel_depth, kernel_height, kernel_width)
filters = torch.randn(33, 16, 3, 3, 3)
## 應用三維卷積
output = F.conv3d(inputs, filters)
print("輸入張量形狀:", inputs.shape)
print("輸出張量形狀:", output.shape)
運行結果示例:
輸入張量形狀: torch.Size([20, 16, 50, 10, 20])
輸出張量形狀: torch.Size([20, 33, 48, 8, 18])
池化操作用于對數(shù)據(jù)進行下采樣,減少數(shù)據(jù)量,同時保留重要特征。
## 創(chuàng)建輸入張量 (batch_size, channels, length)
inputs = torch.randn(1, 4, 50)
## 應用一維平均池化
output = F.avg_pool1d(inputs, kernel_size=3, stride=2)
print("輸入張量形狀:", inputs.shape)
print("輸出張量形狀:", output.shape)
運行結果示例:
輸入張量形狀: torch.Size([1, 4, 50])
輸出張量形狀: torch.Size([1, 4, 24])
## 創(chuàng)建輸入張量 (batch_size, channels, length)
inputs = torch.randn(1, 4, 50)
## 應用一維最大池化
output = F.max_pool1d(inputs, kernel_size=3, stride=2)
print("輸入張量形狀:", inputs.shape)
print("輸出張量形狀:", output.shape)
運行結果示例:
輸入張量形狀: torch.Size([1, 4, 50])
輸出張量形狀: torch.Size([1, 4, 24])
激活函數(shù)為神經(jīng)網(wǎng)絡引入非線性,使網(wǎng)絡能夠學習復雜的模式。
## 創(chuàng)建輸入張量
inputs = torch.randn(2, 3)
## 應用 ReLU 激活函數(shù)
output = F.relu(inputs)
print("輸入張量:\n", inputs)
print("輸出張量:\n", output)
運行結果示例:
輸入張量:
tensor([[ 0.1234, -0.5678, 0.9012],
[-1.2345, 0.6789, -0.3456]])
輸出張量:
tensor([[ 0.1234, 0.0000, 0.9012],
[ 0.0000, 0.6789, 0.0000]])
## 創(chuàng)建輸入張量
inputs = torch.randn(2, 3)
## 應用 Sigmoid 激活函數(shù)
output = F.sigmoid(inputs)
print("輸入張量:\n", inputs)
print("輸出張量:\n", output)
運行結果示例:
輸入張量:
tensor([[ 0.1234, -0.5678, 0.9012],
[-1.2345, 0.6789, -0.3456]])
輸出張量:
tensor([[0.5312, 0.3622, 0.7109],
[0.2242, 0.6642, 0.4156]])
損失函數(shù)用于衡量模型預測結果與真實值之間的差異。
## 創(chuàng)建預測值和真實值張量
predictions = torch.randn(3, 5, requires_grad=True)
targets = torch.randn(3, 5)
## 應用均方誤差損失
loss = F.mse_loss(predictions, targets)
print("損失值:", loss.item())
運行結果示例:
損失值: 0.8765
## 創(chuàng)建預測值和真實值張量
predictions = torch.randn(3, 5, requires_grad=True)
targets = torch.empty(3, dtype=torch.long).random_(5)
## 應用交叉熵損失
loss = F.cross_entropy(predictions, targets)
print("損失值:", loss.item())
運行結果示例:
損失值: 1.2345
import torch
import torch.nn as nn
import torch.nn.functional as F
## 定義一個簡單的神經(jīng)網(wǎng)絡
class SimpleNet(nn.Module):
def __init__(self):
super(SimpleNet, self).__init__()
self.fc1 = nn.Linear(5, 10) # 輸入層到隱藏層
self.fc2 = nn.Linear(10, 3) # 隱藏層到輸出層
def forward(self, x):
x = F.relu(self.fc1(x)) # 應用 ReLU 激活函數(shù)
x = self.fc2(x)
return x
## 創(chuàng)建網(wǎng)絡實例
net = SimpleNet()
## 創(chuàng)建輸入數(shù)據(jù)
input_data = torch.randn(2, 5)
## 前向傳播
output = net(input_data)
print("輸入數(shù)據(jù)形狀:", input_data.shape)
print("輸出數(shù)據(jù)形狀:", output.shape)
運行結果示例:
輸入數(shù)據(jù)形狀: torch.Size([2, 5])
輸出數(shù)據(jù)形狀: torch.Size([2, 3])
## 定義損失函數(shù)和優(yōu)化器
criterion = nn.MSELoss()
optimizer = torch.optim.SGD(net.parameters(), lr=0.01)
## 訓練數(shù)據(jù)
train_data = torch.randn(100, 5)
train_labels = torch.randn(100, 3)
## 訓練循環(huán)
for epoch in range(100):
# 前向傳播
outputs = net(train_data)
loss = criterion(outputs, train_labels)
# 反向傳播和優(yōu)化
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (epoch+1) % 10 == 0:
print(f'Epoch [{epoch+1}/100], Loss: {loss.item():.4f}')
運行結果示例:
Epoch [10/100], Loss: 0.8765
Epoch [20/100], Loss: 0.7654
...
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)獲取更多資源和支持。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
<center id="uao8w"></center>
更多建議: