突破Pytorch核心點(diǎn),優(yōu)化器 ??!
嗨,我是小壯!
今兒咱們聊聊Pytorch中的優(yōu)化器。
優(yōu)化器在深度學(xué)習(xí)中的選擇直接影響模型的訓(xùn)練效果和速度。不同的優(yōu)化器適用于不同的問題,其性能的差異可能導(dǎo)致模型更快、更穩(wěn)定地收斂,或者在某些任務(wù)上表現(xiàn)更好。
因此,選擇合適的優(yōu)化器是深度學(xué)習(xí)模型調(diào)優(yōu)中的一個(gè)關(guān)鍵決策,能夠顯著影響模型的性能和訓(xùn)練效率。
PyTorch本身提供了許多優(yōu)化器,用于訓(xùn)練神經(jīng)網(wǎng)絡(luò)時(shí)更新模型的權(quán)重。
常見優(yōu)化器
咱們先列舉PyTorch中常用的優(yōu)化器,以及簡(jiǎn)單介紹:
(1) SGD (Stochastic Gradient Descent)
隨機(jī)梯度下降是最基本的優(yōu)化算法之一。它通過計(jì)算損失函數(shù)關(guān)于權(quán)重的梯度,并沿著梯度的負(fù)方向更新權(quán)重。
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
(2) Adam
Adam是一種自適應(yīng)學(xué)習(xí)率的優(yōu)化算法,結(jié)合了AdaGrad和RMSProp的思想。它能夠自適應(yīng)地為每個(gè)參數(shù)計(jì)算不同的學(xué)習(xí)率。
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
(3) Adagrad
Adagrad是一種自適應(yīng)學(xué)習(xí)率的優(yōu)化算法,根據(jù)參數(shù)的歷史梯度調(diào)整學(xué)習(xí)率。但由于學(xué)習(xí)率逐漸減小,可能導(dǎo)致訓(xùn)練過早停止。
optimizer = torch.optim.Adagrad(model.parameters(), lr=learning_rate)
(4) RMSProp
RMSProp也是一種自適應(yīng)學(xué)習(xí)率的算法,通過考慮梯度的滑動(dòng)平均來調(diào)整學(xué)習(xí)率。
optimizer = torch.optim.RMSprop(model.parameters(), lr=learning_rate)
(5) Adadelta
Adadelta是一種自適應(yīng)學(xué)習(xí)率的優(yōu)化算法,是RMSProp的改進(jìn)版本,通過考慮梯度的移動(dòng)平均和參數(shù)的移動(dòng)平均來動(dòng)態(tài)調(diào)整學(xué)習(xí)率。
optimizer = torch.optim.Adadelta(model.parameters(), lr=learning_rate)
一個(gè)完整案例
在這里,咱們聊聊如何使用PyTorch訓(xùn)練一個(gè)簡(jiǎn)單的卷積神經(jīng)網(wǎng)絡(luò)(CNN)來進(jìn)行手寫數(shù)字識(shí)別。
這個(gè)案例使用的是MNIST數(shù)據(jù)集,并使用Matplotlib庫繪制了損失曲線和準(zhǔn)確率曲線。
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
import matplotlib.pyplot as plt
# 設(shè)置隨機(jī)種子
torch.manual_seed(42)
# 定義數(shù)據(jù)轉(zhuǎn)換
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))])
# 下載和加載MNIST數(shù)據(jù)集
train_dataset = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
test_dataset = datasets.MNIST(root='./data', train=False, download=True, transform=transform)
train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=1000, shuffle=False)
# 定義簡(jiǎn)單的卷積神經(jīng)網(wǎng)絡(luò)模型
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.conv1 = nn.Conv2d(1, 32, kernel_size=3, stride=1, padding=1)
self.relu = nn.ReLU()
self.pool = nn.MaxPool2d(kernel_size=2, stride=2)
self.conv2 = nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1)
self.fc1 = nn.Linear(64 * 7 * 7, 128)
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
x = self.conv1(x)
x = self.relu(x)
x = self.pool(x)
x = self.conv2(x)
x = self.relu(x)
x = self.pool(x)
x = x.view(-1, 64 * 7 * 7)
x = self.fc1(x)
x = self.relu(x)
x = self.fc2(x)
return x
# 創(chuàng)建模型、損失函數(shù)和優(yōu)化器
model = CNN()
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
# 訓(xùn)練模型
num_epochs = 5
train_losses = []
train_accuracies = []
for epoch in range(num_epochs):
model.train()
total_loss = 0.0
correct = 0
total = 0
for inputs, labels in train_loader:
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
total_loss += loss.item()
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
accuracy = correct / total
train_losses.append(total_loss / len(train_loader))
train_accuracies.append(accuracy)
print(f"Epoch {epoch+1}/{num_epochs}, Loss: {train_losses[-1]:.4f}, Accuracy: {accuracy:.4f}")
# 繪制損失曲線和準(zhǔn)確率曲線
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.plot(train_losses, label='Training Loss')
plt.title('Training Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.subplot(1, 2, 2)
plt.plot(train_accuracies, label='Training Accuracy')
plt.title('Training Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.tight_layout()
plt.show()
# 在測(cè)試集上評(píng)估模型
model.eval()
correct = 0
total = 0
with torch.no_grad():
for inputs, labels in test_loader:
outputs = model(inputs)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
accuracy = correct / total
print(f"Accuracy on test set: {accuracy * 100:.2f}%")
上述代碼中,我們定義了一個(gè)簡(jiǎn)單的卷積神經(jīng)網(wǎng)絡(luò)(CNN),使用交叉熵?fù)p失和Adam優(yōu)化器進(jìn)行訓(xùn)練。
在訓(xùn)練過程中,我們記錄了每個(gè)epoch的損失和準(zhǔn)確率,并使用Matplotlib庫繪制了損失曲線和準(zhǔn)確率曲線。
我是小壯,下期見!