笔记笔记
  • Home
  • AI&ML
  • Example
  • Zoo
  • 关于
⌘ K
简单的使用
自动微分
神经网络
图像分类
最后更新时间:
Copyright © 2023-2024 | Powered by dumi | GuoDapeng | 冀ICP备20004032号-1 | 冀公网安备 冀公网安备 13024002000293号

TABLE OF CONTENTS

‌
‌
‌
‌

神经网络 - 回到 PyTorch 笔记

定义神经网络

import torch.nn as nn
import torch.nn.functional as f
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 6, 5) # 卷积操作;提取特征
self.conv2 = nn.Conv2d(6, 16, 5) # torch.Size([1, 16, 5, 5]), 所以 线性变换需要一个 16 * 5 * 5 = 400 的入口
self.fc1 = nn.Linear(400, 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)) # f.relu() 激活函数:这里负数全部变成零了
x = f.max_pool2d(f.relu(self.conv2(x)), (2, 2)) # f.max_pool2d 池化操作;降维处理
x = x.view(-1, 400) # 改变形状
x = f.relu(self.fc1(x))
x = f.relu(self.fc2(x))
return self.fc3(x)
net = Net()
print(net)
print(net.conv2)

输出:

Net(
(conv1): Conv2d(1, 6, kernel_size=(5, 5), stride=(1, 1))
(conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))
(fc1): Linear(in_features=400, out_features=120, bias=True)
(fc2): Linear(in_features=120, out_features=84, bias=True)
(fc3): Linear(in_features=84, out_features=10, bias=True)
)
Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))

parameters()

net = Net()
# parameters() 方法用于获取一个 nn.Module 实例的参数,并返回一个参数列表,其中每个参数都是一个 torch.Tensor 对象。
params = list(net.parameters())
print(len(params))
print(params[0].shape)

输出:

10
torch.Size([6, 1, 5, 5])

反向传播

net = Net()
# 这个可以理解一个 32 * 32 大小的,一个颜色通道的图片。这里生成了一张这种图片。
image = torch.randn(1, 1, 32, 32)
target = torch.randn(1, 10) # 定义一个目标
out = net(image)
net.zero_grad() # 重置所有模型参数的梯度
out.backward(target) # 反向传播
output = net(image)
criterion = nn.MSELoss()
loss = criterion(output, target) # 计算损失
print(loss)
print('\nnet.conv1.bias.grad:')
print(net.conv1.bias.grad)
net.zero_grad()
loss.backward()
print('\nnet.conv1.bias.grad:')
print(net.conv1.bias.grad)

精炼的例子

import torch
import torch.nn as nn
import torch.nn.functional as f
import torch.optim as optim
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 6, 5) # 卷积操作;提取特征
self.conv2 = nn.Conv2d(6, 16, 5) # torch.Size([1, 16, 5, 5]), 所以 线性变换需要一个 16 * 5 * 5 = 400 的入口
self.fc1 = nn.Linear(400, 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)) # f.relu() 激活函数:这里负数全部变成零了
x = f.max_pool2d(f.relu(self.conv2(x)), (2, 2)) # f.max_pool2d 池化操作;降维处理
x = x.view(-1, 400) # 改变形状
x = f.relu(self.fc1(x))
x = f.relu(self.fc2(x))
return self.fc3(x)
# 这个可以理解一个 32 * 32 大小的,一个颜色通道的图片。这里生成了一张这种图片。
image = torch.randn(1, 1, 32, 32)
net = Net() # 创建神经网络
target = torch.randn(1, 10) # 定义一个目标
out = net(image)
optimizer = optim.SGD(net.parameters(), lr=0.01) # 创建优化器
optimizer.zero_grad() # 重置所有模型参数的梯度
criterion = nn.MSELoss() # 指定损失函数
loss = criterion(out, target) # 计算损失
loss.backward() # 反向传播
optimizer.step() # 更新规则