用pytorch写一个CNN
时间: 2024-05-10 20:20:25 浏览: 75
以下是一个基本的CNN模型的示例代码:
```python
import torch
import torch.nn as nn
class SimpleCNN(nn.Module):
def __init__(self):
super(SimpleCNN, self).__init__()
self.conv1 = nn.Conv2d(in_channels=3, out_channels=16, kernel_size=3, stride=1, padding=1)
self.relu1 = nn.ReLU()
self.pool1 = nn.MaxPool2d(kernel_size=2)
self.conv2 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size=3, stride=1, padding=1)
self.relu2 = nn.ReLU()
self.pool2 = nn.MaxPool2d(kernel_size=2)
self.conv3 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=1, padding=1)
self.relu3 = nn.ReLU()
self.pool3 = nn.MaxPool2d(kernel_size=2)
self.fc1 = nn.Linear(64 * 4 * 4, 10)
def forward(self, x):
out = self.conv1(x)
out = self.relu1(out)
out = self.pool1(out)
out = self.conv2(out)
out = self.relu2(out)
out = self.pool2(out)
out = self.conv3(out)
out = self.relu3(out)
out = self.pool3(out)
out = out.view(out.size(0), -1)
out = self.fc1(out)
return out
```
这是一个简单的CNN模型,包含3个卷积层、3个ReLU激活函数和3个最大池化层,最后是一个全连接层输出10个类别的概率分布。在forward函数中,我们按照顺序运行每一层,并使用view函数将输出的张量展平成一个一维向量。这个模型可以用于图像分类任务。
阅读全文