【PyTorch】Tricks 集锦
阅读原文时间:2023年07月13日阅读:1

声明:本文大部分内容是从知乎、博客等知识分享站点摘录而来,以方便查阅学习。具体摘录地址已在文章底部引用部分给出。


from torchsummary import summary
summary(your_model, input_size=(channels, H, W))

import torch.nn as nn

outputs = model(inputs)
loss= criterion(outputs, target)
optimizer.zero_grad()
loss.backward()
nn.utils.clip_grad_norm_(model.parameters(), max_norm=20, norm_type=2) # max_norm:梯度的最大范数;norm_type:规定范数的类型,默认为L2
optimizer.step()

因为训练时数据维度一般为(batch_size, c, h,, w),而测试时如果只输入一张图片,则需要进行维度扩展。

方法一:(h, w, c) -> (1, h, w, c)

import cv2
import torch

image = cv2.imread(img_path)
image = torch.tensor(image)

img = image.view(1, *image.size())

方法二:(h, w, c) -> (1, h, w, c)

import cv2
import numpy as np

image = cv2.imread(img_path)
img = image[np.newaxis, :, :, :]

方法三:

import cv2
import torch

image = cv2.imread(img_path)
image = torch.tensor(image)

img = image.unsqueeze(dim=0) # 扩展维度,dim指定扩展哪个维度;torch.Size([(h, w, c)]) -> torch.Size([(1, h, w, c)])

img = img.squeeze(dim=0) # 去除dim指定的且size为1的维度,维度大于1时,squeeze()不起作用,不指定dim时,去除所有size为1的维度; torch.Size([(1, h, w, c)]) -> torch.Size([(h, w, c)])

在PyTorch中使用交叉熵损失函数的时候会自动把label转化成onehot,所以不用手动转化,而使用MSE需要手动转化成onehot编码。

import torch
class_num = 8
batch_size = 4

def one_hot(label):
"""
将一维列表转换为独热编码
"""
label = label.resize_(batch_size, 1)
m_zeros = torch.zeros(batch_size, class_num)
# 从 value 中取值,然后根据 dim 和 index 给相应位置赋值
onehot = m_zeros.scatter_(1, label, 1) # (dim,index,value)
return onehot.numpy() # Tensor -> Numpy

label = torch.LongTensor(batch_size).random_() % class_num # 对随机数取余
print(one_hot(label))

output:

# label = tensor([3, 7, 0, 6])
# [[0. 0. 0. 1. 0. 0. 0. 0.]
# [0. 0. 0. 0. 0. 0. 0. 1.]
# [1. 0. 0. 0. 0. 0. 0. 0.]
# [0. 0. 0. 0. 0. 0. 1. 0.]]

验证模型时不需要求导,即不需要梯度计算,关闭autograd,可以提高速度,节约内存。如果不关闭可能会爆显存。

with torch.no_grad():
# 使用model进行预测的代码
pass

由于 PyTorch 的缓存分配器会事先分配一些固定的显存,即使实际上 tensors 并没有使用完这些显存,这些显存也不能被其他应用使用。因此 torch.cuda.empty_cache() 的作用就是释放缓存分配器当前持有的且未占用的缓存显存,以便这些显存可以被其他GPU应用程序中使用,并且通过 nvidia-smi命令可见。注意使用此命令不会释放 tensors 占用的显存。对于不用的数据变量,Pytorch 可以自动进行回收从而释放相应的显存。

import torch.optim as optim
from torch.optim import lr_scheduler

训练前的初始化

optimizer = optim.Adam(net.parameters(), lr=0.001)
scheduler = lr_scheduler.StepLR(optimizer, 10, 0.1) # # 每过10个epoch,学习率乘以0.1

训练过程中

for n in n_epoch:
scheduler.step()

在加载预训练模型的时候,我们有时想冻结前面几层,使其参数在训练过程中不发生变化。

1) 我们首先需要知道每一层的名字,通过如下代码打印:

model = Network() # 获取自定义网络结构
for name, value in model.named_parameters():
print('name: {0},\t grad: {1}'.format(name, value.requires_grad))

假设前几层信息如下:

name: cnn.VGG_16.convolution1_1.weight, grad: True
name: cnn.VGG_16.convolution1_1.bias, grad: True
name: cnn.VGG_16.convolution1_2.weight, grad: True
name: cnn.VGG_16.convolution1_2.bias, grad: True
name: cnn.VGG_16.convolution2_1.weight, grad: True
name: cnn.VGG_16.convolution2_1.bias, grad: True
name: cnn.VGG_16.convolution2_2.weight, grad: True
name: cnn.VGG_16.convolution2_2.bias, grad: True

2) 定义一个要冻结的层的列表

no_grad = [
'cnn.VGG_16.convolution1_1.weight',
'cnn.VGG_16.convolution1_1.bias',
'cnn.VGG_16.convolution1_2.weight',
'cnn.VGG_16.convolution1_2.bias'
]

3) 冻结方法如下

net = Net.CTPN() # 获取网络结构
for name, value in net.named_parameters():
if name in no_grad:
value.requires_grad = False
else:
value.requires_grad = True

再打印每层信息:

name: cnn.VGG_16.convolution1_1.weight, grad: False
name: cnn.VGG_16.convolution1_1.bias, grad: False
name: cnn.VGG_16.convolution1_2.weight, grad: False
name: cnn.VGG_16.convolution1_2.bias, grad: False
name: cnn.VGG_16.convolution2_1.weight, grad: True
name: cnn.VGG_16.convolution2_1.bias, grad: True
name: cnn.VGG_16.convolution2_2.weight, grad: True
name: cnn.VGG_16.convolution2_2.bias, grad: True

4) 最后在定义优化器时,只对requires_grad为True的层的参数进行更新。

optimizer = optim.Adam(filter(lambda p: p.requires_grad, net.parameters()), lr=0.01)

1)首先获取网络结构每一层的名字

net = Network() # 获取自定义网络结构
for name, value in net.named_parameters():
print('name: {}'.format(name))

# 输出:

# name: cnn.VGG_16.convolution1_1.weight

# name: cnn.VGG_16.convolution1_1.bias

# name: cnn.VGG_16.convolution1_2.weight

# name: cnn.VGG_16.convolution1_2.bias

# name: cnn.VGG_16.convolution2_1.weight

# name: cnn.VGG_16.convolution2_1.bias

# name: cnn.VGG_16.convolution2_2.weight

# name: cnn.VGG_16.convolution2_2.bias

2)对 convolution1 和 convolution2 设置不同的学习率,首先将它们分开,即放到不同的列表里:

conv1_params = []
conv2_params = []

for name, parms in net.named_parameters():
if "convolution1" in name:
conv1_params += [parms]
else:
conv2_params += [parms]

然后在优化器中进行如下操作:

optimizer = optim.Adam(
[
{"params": conv1_params, 'lr': 0.01},
{"params": conv2_params, 'lr': 0.001},
],
weight_decay=1e-3,
)

我们将模型划分为两部分,存放到一个列表里,每部分就对应上面的一个字典,在字典里设置不同的学习率。当这两部分有相同的其他参数时,就将该参数放到列表外面作为全局参数,如上面的 weight_decay。

我们也可以在列表外设置一个全局学习率,当各部分字典里设置了局部学习率时,就使用该学习率,否则就使用列表外的全局学习率。

References:

[1] PyTorch trick 集锦