在PyTorch中搭建卷積神經網絡通常包括以下幾個步驟:
import torch
import torch.nn as nn
import torch.nn.functional as F
nn.Module
的自定義卷積神經網絡類:class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
# 定義卷積層
self.conv1 = nn.Conv2d(in_channels=1, out_channels=16, kernel_size=3, stride=1, padding=1)
# 定義池化層
self.pool = nn.MaxPool2d(kernel_size=2, stride=2)
# 定義全連接層
self.fc1 = nn.Linear(16*14*14, 128) # 假設輸入圖像大小為28x28
self.fc2 = nn.Linear(128, 10) # 10為輸出類別數
forward
方法,定義網絡的前向傳播過程: def forward(self, x):
x = F.relu(self.conv1(x))
x = self.pool(x)
x = x.view(-1, 16*14*14)
x = F.relu(self.fc1(x))
x = self.fc2(x)
return x
model = CNN()
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
optimizer.zero_grad()
outputs = model(images)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
if (i+1) % 100 == 0:
print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'
.format(epoch+1, num_epochs, i+1, total_step, loss.item()))
以上是一個簡單的卷積神經網絡的搭建過程,你可以根據自己的需求和問題的復雜度進行更復雜的網絡設計和訓練。