2020/8/24LeNet(pytorch入门与实战)

LeNet

import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import torch as t
import torch.optim as optim


class Net(nn.Module):
    def __init__(self):
        # nn.Module子类的函数必须在构造函数中执行父类的构造函数
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(1, 6, 5)
        self.conv2 = nn.Conv2d(6, 16, 5)
        self.fc1 = nn.Linear(16*5*5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)

    def forward(self, x):
        x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))   # 6*28*28  --> 6*14*14
        x = F.max_pool2d(F.relu(self.conv2(x)), 2)        # 16*10*10 --> 16*5*5
        x = x.view(x.size()[0], -1)                       # 400*1
        x = F.relu(self.fc1(x))                           # 120*1
        x = F.relu(self.fc2(x))                           # 84*1
        x = self.fc3(x)                                   # 10*1
        return x


net = Net()
print(net)

# 网络的可学习参数
params = list(net.parameters())
print(len(params))
for name, parameters in net.named_parameters():
    print(name, ":", parameters.size())

# forward的输入都是可用于求导的Variable
input = Variable(t.randn(1, 1, 32, 32))  # nSample*nChannel*Height*Width
output = net(input)
print(output.size())
"""
# 梯度会累计,需要梯度清零
print("没有更新之前的net.conv1.bias", net.conv1.bias.grad)
net.zero_grad()
output.backward(Variable(t.ones(1, 10)))   # 自动求导
print(net.conv1.bias.grad)"""

# input-->conv1-->relu-->maxpool2d-->conv2-->relu-->maxpool2d
# -->view-->linear-->relu-->linear-->relu-->linear
# -->MESLoss
# -->loss
# 计算损失函数
target = Variable(t.arange(0, 10))
criterion = nn.MSELoss()
loss = criterion(output, target.float())  # 之前显示输入backward的类型错误,通过修改target为浮点型解决
print("loss:", loss)

# 优化损失函数,更新可学习参数
optimizer = optim.SGD(net.parameters(), lr=0.01)
optimizer.zero_grad()
print("没有更新之前", net.conv1.bias.grad)
loss.backward()    # 反向传播, 求导
optimizer.step()   # 更新参数 net.conv1.bias.data.sub_(net.conv1.bias.grad.data*lr)
print("更新之后", net.conv1.bias.grad)

运行结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值