W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗(yàn)值獎勵(lì)
PyTorch 是一款開源的機(jī)器學(xué)習(xí)框架,它具有動態(tài)計(jì)算圖、強(qiáng)大的 GPU 支持和易于使用的 API 等優(yōu)勢,廣泛應(yīng)用于深度學(xué)習(xí)領(lǐng)域。
torch.nn
是 PyTorch 中用于構(gòu)建神經(jīng)網(wǎng)絡(luò)的核心模塊,它提供了各種神經(jīng)網(wǎng)絡(luò)層的實(shí)現(xiàn),如卷積層、線性層、池化層等,以及常用的激活函數(shù)和損失函數(shù)。
線性層是最基本的神經(jīng)網(wǎng)絡(luò)層之一,它對輸入數(shù)據(jù)進(jìn)行線性變換。
import torch
import torch.nn as nn
## 創(chuàng)建一個(gè)線性層,輸入特征數(shù)為 5,輸出特征數(shù)為 3
linear_layer = nn.Linear(5, 3)
## 創(chuàng)建一個(gè)輸入張量,形狀為 (2, 5)
input_tensor = torch.randn(2, 5)
## 通過線性層進(jìn)行前向傳播
output = linear_layer(input_tensor)
print("輸入張量形狀:", input_tensor.shape)
print("輸出張量形狀:", output.shape)
運(yùn)行結(jié)果示例:
輸入張量形狀: torch.Size([2, 5])
輸出張量形狀: torch.Size([2, 3])
卷積層是卷積神經(jīng)網(wǎng)絡(luò)(CNN)中的關(guān)鍵組件,用于提取數(shù)據(jù)的空間特征。
## 創(chuàng)建一個(gè)一維卷積層
conv1d_layer = nn.Conv1d(in_channels=16, out_channels=32, kernel_size=3, stride=1, padding=1)
## 創(chuàng)建一個(gè)輸入張量,形狀為 (10, 16, 50)
input_tensor = torch.randn(10, 16, 50)
## 通過卷積層進(jìn)行前向傳播
output = conv1d_layer(input_tensor)
print("輸入張量形狀:", input_tensor.shape)
print("輸出張量形狀:", output.shape)
運(yùn)行結(jié)果示例:
輸入張量形狀: torch.Size([10, 16, 50])
輸出張量形狀: torch.Size([10, 32, 50])
池化層用于對數(shù)據(jù)進(jìn)行下采樣,減少數(shù)據(jù)量,同時(shí)保留重要特征。
## 創(chuàng)建一個(gè)最大池化層
max_pool_layer = nn.MaxPool2d(kernel_size=2, stride=2)
## 創(chuàng)建一個(gè)輸入張量,形狀為 (20, 16, 50, 32)
input_tensor = torch.randn(20, 16, 50, 32)
## 通過池化層進(jìn)行前向傳播
output = max_pool_layer(input_tensor)
print("輸入張量形狀:", input_tensor.shape)
print("輸出張量形狀:", output.shape)
運(yùn)行結(jié)果示例:
輸入張量形狀: torch.Size([20, 16, 50, 32])
輸出張量形狀: torch.Size([20, 16, 25, 16])
激活函數(shù)為神經(jīng)網(wǎng)絡(luò)引入非線性,使網(wǎng)絡(luò)能夠?qū)W習(xí)復(fù)雜的模式。
ReLU(Rectified Linear Unit)是常用的激活函數(shù)之一,它將所有負(fù)值置零。
## 創(chuàng)建一個(gè) ReLU 激活函數(shù)
relu = nn.ReLU()
## 創(chuàng)建一個(gè)輸入張量
input_tensor = torch.randn(2, 3)
## 應(yīng)用 ReLU 激活函數(shù)
output = relu(input_tensor)
print("輸入張量:\n", input_tensor)
print("輸出張量:\n", output)
運(yùn)行結(jié)果示例:
輸入張量:
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]])
Sigmoid 函數(shù)將輸入值映射到 (0, 1) 區(qū)間,常用于二分類問題。
## 創(chuàng)建一個(gè) Sigmoid 激活函數(shù)
sigmoid = nn.Sigmoid()
## 創(chuàng)建一個(gè)輸入張量
input_tensor = torch.randn(2, 3)
## 應(yīng)用 Sigmoid 激活函數(shù)
output = sigmoid(input_tensor)
print("輸入張量:\n", input_tensor)
print("輸出張量:\n", output)
運(yùn)行結(jié)果示例:
輸入張量:
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ù)用于衡量模型預(yù)測結(jié)果與真實(shí)值之間的差異。
均方誤差損失是回歸問題中常用的損失函數(shù),它計(jì)算預(yù)測值與真實(shí)值之間的平方差的平均值。
## 創(chuàng)建一個(gè)均方誤差損失函數(shù)
mse_loss = nn.MSELoss()
## 創(chuàng)建預(yù)測值和真實(shí)值張量
predictions = torch.randn(3, 5, requires_grad=True)
targets = torch.randn(3, 5)
## 計(jì)算損失
loss = mse_loss(predictions, targets)
print("損失值:", loss.item())
運(yùn)行結(jié)果示例:
損失值: 0.8765
交叉熵?fù)p失常用于分類問題,它結(jié)合了 LogSoftmax 和 NLLLoss。
## 創(chuàng)建一個(gè)交叉熵?fù)p失函數(shù)
cross_entropy_loss = nn.CrossEntropyLoss()
## 創(chuàng)建預(yù)測值和真實(shí)值張量
predictions = torch.randn(3, 5, requires_grad=True)
targets = torch.empty(3, dtype=torch.long).random_(5)
## 計(jì)算損失
loss = cross_entropy_loss(predictions, targets)
print("損失值:", loss.item())
運(yùn)行結(jié)果示例:
損失值: 1.2345
## 定義一個(gè)簡單的神經(jīng)網(wǎng)絡(luò)
class SimpleNet(nn.Module):
def __init__(self):
super(SimpleNet, self).__init__()
self.fc1 = nn.Linear(5, 10) # 輸入層到隱藏層
self.fc2 = nn.Linear(10, 3) # 隱藏層到輸出層
self.relu = nn.ReLU() # ReLU 激活函數(shù)
def forward(self, x):
x = self.fc1(x)
x = self.relu(x)
x = self.fc2(x)
return x
## 創(chuàng)建網(wǎng)絡(luò)實(shí)例
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)
運(yùn)行結(jié)果示例:
輸入數(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)
## 訓(xùn)練數(shù)據(jù)
train_data = torch.randn(100, 5)
train_labels = torch.randn(100, 3)
## 訓(xùn)練循環(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}')
運(yùn)行結(jié)果示例:
Epoch [10/100], Loss: 0.8765
Epoch [20/100], Loss: 0.7654
...
Epoch [100/100], Loss: 0.1234
本教程從零基礎(chǔ)出發(fā),帶領(lǐng)大家認(rèn)識了 PyTorch 環(huán)境,了解了 torch.nn
模塊中的基本概念,包括神經(jīng)網(wǎng)絡(luò)層、激活函數(shù)和損失函數(shù)等內(nèi)容,并通過代碼實(shí)操環(huán)節(jié)加深了對所學(xué)知識的理解。后續(xù)可以繼續(xù)探索更多 PyTorch 相關(guān)知識,如自動梯度、神經(jīng)網(wǎng)絡(luò)的構(gòu)建與訓(xùn)練等。
希望這篇教程能夠幫助大家更好地入門 PyTorch,如果在學(xué)習(xí)過程中有任何疑問,歡迎訪問編程獅(W3Cschool)官網(wǎng)獲取更多資源和支持。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: