<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          【深度學習】PyTorch 常用 Tricks 總結

          共 6383字,需瀏覽 13分鐘

           ·

          2022-05-27 21:25

          作者:z.defying

          轉載自:Datawhale


          目錄:

          1 指定GPU編號

          2 查看模型每層輸出詳情

          3 梯度裁剪

          4 擴展單張圖片維度

          5 獨熱編碼

          6 防止驗證模型時爆顯存

          7 學習率衰減

          8 凍結某些層的參數(shù)

          9 對不同層使用不同學習率


          1. 指定GPU編號


          設置當前使用的GPU設備僅為0號設備,設備名稱為?/gpu:0
          os.environ["CUDA_VISIBLE_DEVICES"] = "0"


          設置當前使用的GPU設備為0, 1號兩個設備,名稱依次為?/gpu:0、/gpu:1:?
          os.environ["CUDA_VISIBLE_DEVICES"] = "0,1"?,根據(jù)順序表示優(yōu)先使用0號設備,然后使用1號設備。


          指定GPU的命令需要放在和神經(jīng)網(wǎng)絡相關的一系列操作的前面。


          2. 查看模型每層輸出詳情


          Keras有一個簡潔的API來查看模型的每一層輸出尺寸,這在調試網(wǎng)絡時非常有用?,F(xiàn)在在PyTorch中也可以實現(xiàn)這個功能。


          使用很簡單,如下用法:


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


          input_size?是根據(jù)你自己的網(wǎng)絡模型的輸入尺寸進行設置。


          https://github.com/sksq96/pytorch-summary


          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_?的參數(shù):

          • parameters?– 一個基于變量的迭代器,會進行梯度歸一化

          • max_norm?– 梯度的最大范數(shù)

          • norm_type?– 規(guī)定范數(shù)的類型,默認為L2


          知乎用戶 @不橢的橢圓 提出:梯度裁剪在某些任務上會額外消耗大量的計算時間。


          4. 擴展單張圖片維度


          因為在訓練時的數(shù)據(jù)維度一般都是 (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)

          或(感謝知乎用戶?@coldleaf?的補充)

          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中使用交叉熵損失函數(shù)的時候會自動把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 中取值,然后根據(jù) 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 # 對隨機數(shù)取余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.]]


          https://discuss.pytorch.org/t/convert-int-into-one-hot-format/507/3


          6. 防止驗證模型時爆顯存


          驗證模型時不需要求導,即不需要梯度計算,關閉autograd,可以提高速度,節(jié)約內存。如果不關閉可能會爆顯存。


          with torch.no_grad():    # 使用model進行預測的代碼????pass

          感謝知乎用戶 @zhaz 的提醒,我把?torch.cuda.empty_cache()?的使用原因更新一下。


          這是原回答:

          Pytorch 訓練時無用的臨時變量可能會越來越多,導致 out of memory ,可以使用下面語句來清理這些不需要的變量。


          官網(wǎng)上的解釋為:

          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內存訪問觸發(fā)的。


          ?torch.cuda.empty_cache()?的作用就是釋放緩存分配器當前持有的且未占用的緩存顯存,以便這些顯存可以被其他GPU應用程序中使用,并且通過?nvidia-smi命令可見。注意使用此命令不會釋放tensors占用的顯存。


          對于不用的數(shù)據(jù)變量,Pytorch 可以自動進行回收從而釋放相應的顯存。


          更詳細的優(yōu)化可以查看:
          優(yōu)化顯存使用:
          https://blog.csdn.net/qq_28660035/article/details/80688427
          顯存利用問題:
          https://oldpan.me/archives/pytorch-gpu-memory-usage-track


          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() ...

          8. 凍結某些層的參數(shù)


          參考:Pytorch 凍結預訓練模型的某一層
          https://www.zhihu.com/question/311095447/answer/589307812


          在加載預訓練模型的時候,我們有時想凍結前面幾層,使其參數(shù)在訓練過程中不發(fā)生變化。


          我們需要先知道每一層的名字,通過如下代碼打?。?/span>


          net = Network()  # 獲取自定義網(wǎng)絡結構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表示該層的參數(shù)可訓練,然后我們定義一個要凍結的層的列表:


          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()  # 獲取網(wǎng)絡結構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: 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,表示它們不可訓練。


          最后在定義優(yōu)化器時,只對requires_grad為True的層的參數(shù)進行更新。


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

          9. 對不同層使用不同學習率


          我們對模型的不同層使用不同的學習率。


          還是使用這個模型作為例子:


          net = Network()  # 獲取自定義網(wǎng)絡結構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]
          # 然后在優(yōu)化器中進行如下操作:optimizer = optim.Adam( [ {"params": conv1_params, 'lr': 0.01}, {"params": conv2_params, 'lr': 0.001}, ], weight_decay=1e-3,)

          我們將模型劃分為兩部分,存放到一個列表里,每部分就對應上面的一個字典,在字典里設置不同的學習率。當這兩部分有相同的其他參數(shù)時,就將該參數(shù)放到列表外面作為全局參數(shù),如上面的`weight_decay`。


          也可以在列表外設置一個全局學習率,當各部分字典里設置了局部學習率時,就使用該學習率,否則就使用列表外的全局學習率。

          往期精彩回顧




          瀏覽 41
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  免费中文字幕免日本美中文字幕日免 | 丁香婷婷色 | 一区二区三区四区在线播放 | 4080yy午夜理论片成人 | 亚洲AV永久无码精品久久麻豆 |