在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()))
以上是一个简单的卷积神经网络的搭建过程,你可以根据自己的需求和问题的复杂度进行更复杂的网络设计和训练。