写一个卷积神经网络的代码
时间: 2023-10-24 20:07:58 浏览: 34
好的,以下是一个使用 PyTorch 实现卷积神经网络 (Convolutional Neural Network, CNN) 的代码示例:
```
import torch
import torch.nn as nn
import torch.nn.functional as F
class ConvNet(nn.Module):
def __init__(self):
super(ConvNet, self).__init__()
self.conv1 = nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, stride=1, padding=1)
self.pool = nn.MaxPool2d(kernel_size=2, stride=2)
self.conv2 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=1, padding=1)
self.fc1 = nn.Linear(in_features=64 * 8 * 8, out_features=512)
self.fc2 = nn.Linear(in_features=512, out_features=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, 64 * 8 * 8)
x = F.relu(self.fc1(x))
x = self.fc2(x)
return x
model = ConvNet()
```
在这个代码中,我们定义了一个 `ConvNet` 类,它继承了 PyTorch 中的 `nn.Module` 类。在初始化函数中,我们定义了一些卷积层、池化层和全连接层,并在 `forward` 函数中定义了该模型的前向传播过程。
请注意,这仅仅是一个示例,您可以根据您的需求进行相应的修改。