使用pytorch搭建一个三层卷积神经网络
时间: 2023-05-21 11:00:41 浏览: 266
fcn全卷积网络代码
好的,使用 PyTorch 搭建一个三层卷积神经网络的代码如下:
```python
import torch
import torch.nn as nn
class ConvNet(nn.Module):
def __init__(self):
super(ConvNet, self).__init__()
self.layer1 = nn.Sequential(
nn.Conv2d(1, 16, kernel_size=5, stride=1, padding=2),
nn.BatchNorm2d(16),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2))
self.layer2 = nn.Sequential(
nn.Conv2d(16, 32, kernel_size=5, stride=1, padding=2),
nn.BatchNorm2d(32),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2))
self.layer3 = nn.Sequential(
nn.Conv2d(32, 64, kernel_size=5, stride=1, padding=2),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2))
self.fc = nn.Linear(64 * 7 * 7, 10)
def forward(self, x):
out = self.layer1(x)
out = self.layer2(out)
out = self.layer3(out)
out = out.reshape(out.size(0), -1)
out = self.fc(out)
return out
```
这个三层卷积神经网络包含了三个卷积层和一个全连接层,其中每个卷积层都包含了卷积、批量归一化、ReLU 激活和最大池化操作。最后的全连接层将卷积层的输出展平并映射到输出类别的数量上。
阅读全文