一、简化前馈网络LeNet
import torch as t
class LeNet(t.nn.Module):
def __init__(self):
super(LeNet, self).__init__()
self.features = t.nn.Sequential(
t.nn.Conv2d(3, 6, 5),
t.nn.ReLU(),
t.nn.MaxPool2d(2, 2),
t.nn.Conv2d(6, 16, 5),
t.nn.ReLU(),
t.nn.MaxPool2d(2, 2)
)
# 由于调整shape并不是一个class层,
# 所以在涉及这种操作(非nn.Module操作)需要拆分为多个模型
self.classifiter = t.nn.Sequential(
t.nn.Linear(16*5*5, 120),
t.nn.ReLU(),
t.nn.Linear(120, 84),
t.nn.ReLU(),
t.nn.Linear(84, 10)
)
def forward(self, x):
x = self.features(x)
x = x.view(-1, 16*5*5)
x = self.classifiter(x)
return x
net = LeNet()
二、优化器基本使用方法
建立优化器实例
循环:
清空梯度
向前传播
计算Loss
反向传播
更新参数<