Pytorch知識點與問題解決

文|Seraph

01 | 知識點

  1. torcht.is_tensor(a) 判斷是否爲張量
  2. Pytorch GPU環境是否正常測試代碼:
import torch
flag = torch.cuda.is_available()
print(flag)

ngpu= 1
# Decide which device we want to run on
device = torch.device("cuda:0" if (torch.cuda.is_available() and ngpu > 0) else "cpu")
print(device)
print(torch.cuda.get_device_name(0))
print(torch.rand(3,3).cuda())
  1. cuDNN使用非確定算法設置torch.backends.cudnn.enabled = False可以關閉。
    當設置
torch.backends.cudnn.enabled = true
torch.backends.cudnn.benchmark = true

cuDNN使用的非確定性算法就會自動尋找最適合當前配置的高效算法,來達到優化運行效率的問題。
適用場景是網絡結構固定、輸入形狀不變的情況。如卷積層的設置一直變化,會導致程序不斷再優化,從而耗費更多的時間。

  1. torch.manual_seed(args.seed) #爲CPU設置種子用於生成隨機數
    torch.cuda.manual_seed(args.seed)#爲當前GPU設置隨機種子;如果使用多個GPU,應該使用torch.cuda.manual_seed_all()爲所有的GPU設置種子。
    之所以設置種子,是因爲可以復現結果。

99 | 問題解決

  1. 執行loss.data[0]報錯:IndexError: invalid index of a 0-dim tensor. Use tensor.item() to convert a 0-dim tensor to a Python number
    解決:將loss.data[0]換成loss.item()
  2. 使用DistributedSampler()後再Dataloader()參數中加入了shuffle=True報錯:Dataloader BUG ValueError: sampler option is mutually exclusive with shuffle
    解決:去掉該參數。因爲torch.utils.data.distributed.DistributedSampler是默認使用shuffle=True的,所以不能多次使用。
  3. Expected object of scalar type Float but got scalar type Long for argument #2 ‘target’
    解決:將target類型轉換爲float:
    target = target.float()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章