1. 程式人生 > >Pytorch學習筆記(二)使用Pytorch的常見錯誤彙總

Pytorch學習筆記(二)使用Pytorch的常見錯誤彙總

那些年我們一起踩過的坑!

Error

標籤範圍問題

這個錯誤出現在我參考別人的原始碼來訓練一個車型識別模型,共196類,設定輸出num_classes = 196,結果報下面錯誤,原因是我的輸入的標籤是1-196,超出索引範圍,正確標籤範圍應該是[0,num_classes)

    _, pred = output.data.cpu().topk(1, dim=1)
RuntimeError: cuda runtime error (59) : device-side assert triggered at /pytorch/aten/src/THC/generic/THCTensorCopy.c:70

輸入影象大小不一的問題

資料集影象大小不一,載入訓練集時進行了Resize and Crop ,但是在測試時忘記了,因此出現了以下報錯資訊:

    for batch_idx, (input, target) in enumerate(loader):
  File "/usr/local/lib/python2.7/dist-packages/torch/utils/data/dataloader.py", line 264, in __next__
    batch = self.collate_fn([self.dataset[i] for i in indices])
  File
"/usr/local/lib/python2.7/dist-packages/torch/utils/data/dataloader.py", line 138, in default_collate return [default_collate(samples) for samples in transposed] File "/usr/local/lib/python2.7/dist-packages/torch/utils/data/dataloader.py", line 115, in default_collate return torch.stack(batch, 0, out=out) RuntimeError: invalid argument 0
: Sizes of tensors must match except in dimension 0. Got 182 and 360 in dimension 2 at /pytorch/aten/src/TH/generic/THTensorMath.c:3586

argument or attribute error

跑個官例手寫字型就報錯

TypeError: nll_loss() got an unexpected keyword argument 'reduction'

help(F.nll_loss) ,檢視文件,確實沒有該引數。跑到官方手冊檢視,有該引數,確認是版本差!
總結: 官例跟隨最新的版本,如果自己的是老版本,容易遇到一些argument or attribute error,這時候要根據官方手冊排查,確認之後可以選擇更新包或者自己recoding。

Warning

單值張量的索引問題

使用torch.Tensor.item()從包含單個值的張量中獲取Python數字:

UserWarning: invalid index of a 0-dim tensor. This will be an error in PyTorch 0.5. Use tensor.item() to convert a 0-dim tensor to a Python number

volatile was removed

UserWarning: volatile was removed and now has no effect. Use `with torch.no_grad():` instead.
  input_var = torch.autograd.Variable(input.cuda(async=True), volatile=True)

Attention

0.4版本之後TensorVariable合併

在此之前只有Variable支援backwardVariableTensor的封裝。

新版本中,torch.autograd.Variabletorch.Tensor將同屬一類。更確切地說,torch.Tensor 能夠跟蹤歷史並像舊版本的 Variable 那樣執行; Variable 封裝仍舊可以像以前一樣工作,但返回的物件型別是 torch.Tensor。 這意味著你不再需要程式碼中的所有變數封裝器。