要使用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搭建卷积神经网络并进行训练了。记得根据你的具体问题和数据集进行相应的调整和优化。