赞
踩
这次是简单的神经网络,因为层数比较少
关于环境配置,
这次处理的是数字识别,用到手写数字集
- # 导入相关的包
- import torch
- from torch import nn
- # 判断是否安装gpu版本的torch,若没有则使用cpu运算
- device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
- print("using {} device.".format(device))
- # 定义Lenet模型
- class LeNet(nn.Module):
- def __init__(self):
- super(LeNet, self).__init__()
- ## 定义网络结构
- self.conv = nn.Sequential(
- #在此处更改网络的结构,使网络在3232的输入大小下,可以输入2828的Mnist数据集。
-
- ## C1卷积层
- nn.Conv2d(3,6,(5,5),padding=(2,2)),# 输入通道3,输出通道6,卷积矩阵5x5
- # nn.Conv2d(3,6,(5,5)),# 输入通道3,输出通道6,卷积矩阵5x5
- nn.Sigmoid(),
- nn.MaxPool2d(2,2), # 池化2x2
- # NO.2
- nn.Conv2d(6,16,5),#
- nn.Sigmoid(),
- nn.MaxPool2d(2,2)
- )
- self.fc = nn.Sequential(
- nn.Linear(16*5*5,120),# 上面池化层的结果输入,输出
- # nn.Linear(16*4*4,120),# 上面池化层的结果输入,输出
- nn.Sigmoid(),
- nn.Linear(120,84),
- nn.Sigmoid(),
- nn.Linear(84,10)
- )
- ## 前向传播
- def forward(self, img):
- feature = self.conv(img)
- img = feature.view(img.shape[0],-1) # 把图矩阵拉成向量
- output = self.fc(img) # 得到长度为10 的向量
- return output

- # 查看模型
- net = LeNet()
- print(net)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。