import torch as t
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
'''
定义网络
'''
# 搭建的所有神经网络,都必须从nn.Module类继承
class Net(nn.Module):
def __init__(self):
# nn.Module 子类的函数必须在构造函数中执行父类的构造函数
# 下式等价于nn.module.__init__(self)
super(Net, self).__init__()
# Conv2d,二维卷积
# 卷积层'1'表示输入的图片为单通道。RGB图像通道数为'3'
# '6'表示输出通道数,
# '5'表示卷积核为 5*5。当卷积核不规则时,使用元组表示,例如(4, 5)
# 5*5 的卷积核里面的数据是pytorch自动生成的
self.conv1 = nn.Conv2d(1, 6, 5)
# 卷积层
self.conv2 = nn.Conv2d(6, 16, 5)
# 仿射层/全连接层, y = wx+b
# in_features由输入张量的形状决定,
# out_features则决定了输出张量的形状
self.fc1 = nn.Linear(16*5*5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84,10)
# 向前传播
# x 为输入
def forward(self, x):
# 卷积 -> 激活 -> 池化
# self.conv1(x) 卷积层,将 tensor() 与 5*5 方框依次相乘
# F.relu() 修正激活函数
# max_pool2d 最大池化层,选 2*2 方框中的最大值
x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
x = F.max_pool2d(F.relu(self.conv2(x)), 2)
# 相当于numpy中resize()的功能
# 再看一个例子:
# a = torch.Tensor([[[1, 2, 3], [4, 5, 6]]])
# print(a.view(3, 2))
# 将会得到:
# tensor([[1., 2.],
# [3., 4.],
# [5., 6.]])
# reshape为'-1'表示自适应
x = x.view(x.size()[0], -1)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
# 创建一个
net = Net()
print('net: \n' + str(net))
# 分割测试样例
print('-'*30)
params = list(net.parameters())
print('len(params): ' + str(len(params)))
# 分割测试样例
print('-'*30)
print('name:parameters.size(): ')
for name, parameters in net.named_parameters():
print(name, ':', parameters.size())
# 分割测试样例
print('-'*30)
input = t.randn(1, 1, 32, 32)
out = net(input)
print('out.size(): ' + str(out.size()))
# 分割测试样例
print('-'*30)
# 所有参数的梯度清零
net.zero_grad()
# 反向传播
out.backward(t.ones(1,10))
# torch.nn只支持mini-batches,不支持一次只输入一个样本,
# 即一次必须是一个batch
# 如果只想输入一个样本,可通过设置样本数目为1
'''
损失函数
'''
output = net(input)
target = t.arange(0, 10).view(1, 10).float()
# nn.MSELoss() 计算均方误差
criterion = nn.MSELoss()
loss = criterion(output, target)
print('loss: ' + str(loss))
# 分割测试样例
print('-'*30)
# 运行 .backward ,观察调用前和调用后的grad
# 把 net 中所有可学习传输的梯度清零
net.zero_grad()
print('反向传播之前 conv1.bias 的梯度: \n' + str(net.conv1.bias.grad))
loss.backward()
print('反向传播之后 conv1.bias 的梯度: \n' + str(net.conv1.bias.grad))
'''
优化器
'''
# 手动实现
learning_rate = 0.01
for f in net.parameters():
f.data.sub_(f.grad.data * learning_rate)
#新建一个优化器,指定要调整的参数和学习率
optimizer = optim.SGD(net.parameters(), lr = 0.01)
# 在训练过程中
# 先梯度清零(与net.zero_grad()效果一样)
optimizer.zero_grad()
# 计算损失
output = net(input)
loss = criterion(output, target)
#反向传播
loss.backward()
#更新参数
optimizer.step()
PyTorch学习——神经网络
最新推荐文章于 2022-05-04 16:08:58 发布