1、指定GPU編號
2、查看模型每層輸出詳情
3、梯度裁剪
4、擴展單張圖片維度
5、one hot編碼
6、防止驗證模型時爆顯存
7、學習率衰減
8、凍結某些層的參數
9、對不同層使用不同學習率
10、模型相關操作
11、Pytorch內置one hot函數
12、網絡參數初始化
13、加載內置預訓練模型
設置當前使用的GPU設備僅為0號設備,設備名稱為 /gpu:0:os.environ["CUDA_VISIBLE_DEVICES"] = "0"
設置當前使用的GPU設備為0,1號兩個設備,名稱依次為 /gpu:0、/gpu:1:os.environ["CUDA_VISIBLE_DEVICES"] = "0,1" ,根據順序表示優先使用0號設備,然後使用1號設備。
指定GPU的命令需要放在和神經網絡相關的一系列操作的前面。from torchsummary import summarysummary(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()nn.utils.clip_grad_norm_ 的參數:parameters – 一個基於變量的迭代器,會進行梯度歸一化norm_type – 規定範數的類型,默認為L2@不橢的橢圓 提出:梯度裁剪在某些任務上會額外消耗大量的計算時間,可移步評論區查看詳情。
4、擴展單張圖片維度因為在訓練時的數據維度一般都是 (batch_size, c, h, w),而在測試時只輸入一張圖片,所以需要擴展維度,擴展維度有多個方法:import cv2import 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 cv2import 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 cv2import 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])tensor.unsqueeze(dim):擴展維度,dim指定擴展哪個維度。tensor.squeeze(dim):去除dim指定的且size為1的維度,維度大於1時,squeeze()不起作用,不指定dim時,去除所有size為1的維度。
5、獨熱編碼在PyTorch中使用交叉熵損失函數的時候會自動把label轉化成onehot,所以不用手動轉化,而使用MSE需要手動轉化成onehot編碼。import torchclass_num = 8batch_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、防止驗證模型時爆顯存驗證模型時不需要求導,即不需要梯度計算,關閉autograd,可以提高速度,節約內存。如果不關閉可能會爆顯存。with torch.no_grad(): # 使用model進行預測的代碼 pass感謝@zhaz 的提醒,我把 torch.cuda.empty_cache() 的使用原因更新一下。Pytorch 訓練時無用的臨時變量可能會越來越多,導致 out of memory ,可以使用下面語句來清理這些不需要的變量。Releases all unoccupied cached memory currently held by the caching allocator so that those can be used in other GPU application and visible innvidia-smi. torch.cuda.empty_cache()意思就是PyTorch的緩存分配器會事先分配一些固定的顯存,即使實際上tensors並沒有使用完這些顯存,這些顯存也不能被其他應用使用。這個分配過程由第一次CUDA內存訪問觸發的。而 torch.cuda.empty_cache() 的作用就是釋放緩存分配器當前持有的且未佔用的緩存顯存,以便這些顯存可以被其他GPU應用程式中使用,並且通過 nvidia-smi命令可見。注意使用此命令不會釋放tensors佔用的顯存。對於不用的數據變量,Pytorch 可以自動進行回收從而釋放相應的顯存。更詳細的優化可以查看 優化顯存使用 和 顯存利用問題。
7、學習率衰減import torch.optim as optimfrom 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() ...可以隨時查看學習率的值:optimizer.param_groups[0]['lr']。scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda epoch:1/(epoch+1))lr_scheduler.ReduceLROnPlateau()提供了基於訓練中某些測量值使學習率動態下降的方法,它的參數說明到處都可以查到。
提醒一點就是參數 mode='min' 還是'max',取決於優化的的損失還是準確率,即使用 scheduler.step(loss)還是scheduler.step(acc) 。8、凍結某些層的參數
參考:https://www.zhihu.com/question/311095447/answer/589307812在加載預訓練模型的時候,我們有時想凍結前面幾層,使其參數在訓練過程中不發生變化。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: Truename: cnn.VGG_16.convolution1_1.bias, grad: Truename: cnn.VGG_16.convolution1_2.weight, grad: Truename: cnn.VGG_16.convolution1_2.bias, grad: Truename: cnn.VGG_16.convolution2_1.weight, grad: Truename: cnn.VGG_16.convolution2_1.bias, grad: Truename: cnn.VGG_16.convolution2_2.weight, grad: Truename: cnn.VGG_16.convolution2_2.bias, grad: True後面的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 = Truename: cnn.VGG_16.convolution1_1.weight, grad: Falsename: cnn.VGG_16.convolution1_1.bias, grad: Falsename: cnn.VGG_16.convolution1_2.weight, grad: Falsename: cnn.VGG_16.convolution1_2.bias, grad: Falsename: cnn.VGG_16.convolution2_1.weight, grad: Truename: cnn.VGG_16.convolution2_1.bias, grad: Truename: cnn.VGG_16.convolution2_2.weight, grad: Truename: cnn.VGG_16.convolution2_2.bias, grad: True可以看到前兩層的weight和bias的requires_grad都為False,表示它們不可訓練。最後在定義優化器時,只對requires_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對 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`。也可以在列表外設置一個全局學習率,當各部分字典裡設置了局部學習率時,就使用該學習率,否則就使用列表外的全局學習率。10、模型相關操作
這個內容比較多,我寫成了一篇文章:https://zhuanlan.zhihu.com/p/7389318711、Pytorch內置one_hot函數
感謝@yangyangyang 補充:Pytorch 1.1後,one_hot可以直接用torch.nn.functional.one_hot。然後我將Pytorch升級到1.2版本,試用了下 one_hot 函數,確實很方便。import torch.nn.functional as Fimport torch
tensor = torch.arange(0, 5) % 3 # tensor([0, 1, 2, 0, 1])one_hot = F.one_hot(tensor)
# 輸出:# tensor([[1, 0, 0],# [0, 1, 0],# [0, 0, 1],# [1, 0, 0],# [0, 1, 0]])F.one_hot會自己檢測不同類別個數,生成對應獨熱編碼。我們也可以自己指定類別數:tensor = torch.arange(0, 5) % 3 # tensor([0, 1, 2, 0, 1])one_hot = F.one_hot(tensor, num_classes=5)
# 輸出:# tensor([[1, 0, 0, 0, 0],# [0, 1, 0, 0, 0],# [0, 0, 1, 0, 0],# [1, 0, 0, 0, 0],# [0, 1, 0, 0, 0]])升級 Pytorch (cpu版本)的命令:conda install pytorch torchvision \-c pytorch神經網絡的初始化是訓練流程的重要基礎環節,會對模型的性能、收斂性、收斂速度等產生重要的影響。(1) 使用pytorch內置的torch.nn.init方法。常用的初始化操作,例如正態分布、均勻分布、xavier初始化、kaiming初始化等都已經實現,可以直接使用。具體詳見PyTorch 中 torch.nn.init 中文文檔。init.xavier_uniform(net1[0].weight)(2) 對於一些更加靈活的初始化方法,可以藉助numpy。對於自定義的初始化方法,有時tensor的功能不如numpy強大靈活,故可以藉助numpy實現初始化方法,再轉換到tensor上使用。for layer in net1.modules(): if isinstance(layer, nn.Linear): # 判斷是否是線性層 param_shape = layer.weight.shape layer.weight.data = torch.from_numpy(np.random.normal(0, 0.5, size=param_shape)) # 定義為均值為 0,方差為 0.5 的正態分布 13、加載內置預訓練模型torchvision.models模塊的子模塊中包含以下模型:import torchvision.models as modelsresnet18 = models.resnet18()alexnet = models.alexnet()vgg16 = models.vgg16()有一個很重要的參數為pretrained,默認為False,表示只導入模型的結構,其中的權重是隨機初始化的。如果pretrained 為 True,表示導入的是在ImageNet數據集上預訓練的模型。import torchvision.models as modelsresnet18 = models.resnet18(pretrained=True)alexnet = models.alexnet(pretrained=True)vgg16 = models.vgg16(pretrained=True)更多的模型可以查看:https://pytorch-cn.readthedocs.io/zh/latest/torchvision/torchvision-models/