PyTorch trick 集锦

2019-08-27  本文已影响0人  顾北向南

https://mp.weixin.qq.com/s/o-V07uM5NBn-0kQOQYrImw
本文仅作为学术分享,如果侵权,会删文处理

1.指定GPU编号

2.查看模型每层输出详情

from torchsummary import summary
summary(your_model, input_size=(channels, H, W))
# input_size 是根据你自己的网络模型的输入尺寸进行设置。

3.梯度裁剪(Gradient Clipping)

import torch.nn as nn

outputs = model(data)
loss= loss_fn(outputs, target)
optimizer.zero_grad()
loss.backward()
nn.utils.clip_grad_norm_(model.parameters(), max_norm=20, norm_type=2)
optimizer.step()

4.扩展单张图片维度

import cv2
import torch

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

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

# output:
# torch.Size([h, w, c])
# torch.Size([1, h, w, c])

import cv2
import numpy as np

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

# output:
# (h, w, c)
# (1, h, w, c)

import cv2
import torch

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

img = image.unsqueeze(dim=0)  
print(img.size())

img = img.squeeze(dim=0)
print(img.size())

# output:
# torch.Size([(h, w, c)])
# torch.Size([1, h, w, c])
# torch.Size([h, w, c])

5.独热编码

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:
[[0. 0. 0. 1. 0. 0. 0. 0.]
 [0. 0. 0. 0. 1. 0. 0. 0.]
 [0. 0. 1. 0. 0. 0. 0. 0.]
 [0. 1. 0. 0. 0. 0. 0. 0.]]

6.防止验证模型时爆显存

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

Pytorch 训练时无用的临时变量可能会越来越多,导致 out of memory ,可以使用下面语句来清理这些不需要的变量。就是PyTorch的缓存分配器会事先分配一些固定的显存,即使实际上tensors并没有使用完这些显存,这些显存也不能被其他应用使用。这个分配过程由第一次CUDA内存访问触发的。

7.学习率衰减

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(

8.冻结某些层的参数

net = Network()  # 获取自定义网络结构
for name, value in net.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
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'
]
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
optimizer = optim.Adam(filter(lambda p: p.requires_grad, net.parameters()), lr=0.01)

9.对不同层使用不同学习率

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
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,
)

上一篇 下一篇

猜你喜欢

热点阅读