要使用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)
self.pool = nn.MaxPool2d(kernel_size=2, stride=2)
self.conv2 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size=3)
self.fc1 = nn.Linear(32 * 6 * 6, 128)
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 32 * 6 * 6)
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, (inputs, labels) in enumerate(train_loader):
outputs = model(inputs)
loss = criterion(outputs, labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
這樣,你就可以使用PyTorch搭建卷積神經網絡并進行訓練了。記得根據你的具體問題和數據集進行相應的調整和優化。