提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
- 前言
- 搭建小网络和sequential的使用
- 一、 第一种形式如下:
- 二、第二种方式,使用sequential
前言
至此,神经网络的基础部分就基本结束了。
搭建小网络和sequential的使用
- 搭建一个完整的网络,网络结构如下:
一、 第一种形式如下:
import torch
from torch import nnclass Model(nn.Module):def __init__(self):super(Model, self).__init__()self.conv1 = nn.Conv2d(3,32,5,padding=2)self.maxpool1 = nn.MaxPool2d(2)self.conv2 = nn.Conv2d(32,32,5,padding=2)self.maxpool2 = nn.MaxPool2d(2)self.conv3 = nn.Conv2d(32,64,5,padding=2)self.maxpool3 = nn.MaxPool2d(2)self.flatten = nn.Flatten()self.linear1 = nn.Linear(1024,64)self.linear2 = nn.Linear(64,10)def forward(self,x):x = self.conv1(x)x = self.maxpool1(x)x = self.conv2(x)x = self.maxpool2(x)x = self.conv3(x)x = self.maxpool3(x)x = self.flatten(x)x = self.linear1(x)x = self.linear2(x)return xmodel = Model()
print(model)
二、第二种方式,使用sequential
import torch
from torch import nnclass Model(nn.Module):def __init__(self):super(Model, self).__init__()self.model1 = nn.Sequential(nn.Conv2d(3, 32, 5, padding=2),nn.MaxPool2d(2),nn.Conv2d(32, 32, 5, padding=2),nn.MaxPool2d(2),nn.Conv2d(32, 64, 5, padding=2),nn.MaxPool2d(2),nn.Flatten(),nn.Linear(1024, 64),nn.Linear(64, 10))def forward(self,x):x = self.model1return xmodel = Model()
print(model)