PyTorch使用常見(jiàn)異常和解決辦法匯總
文章目錄
1.使用conda安裝PyTorch后同時(shí)在Jupyter導(dǎo)入失敗No module named ‘torch’
通過(guò)Conda安裝PyTorch,同時(shí)在Jupyter中導(dǎo)入PyTorch,會(huì)報(bào)錯(cuò)No module named 'torch'
。
分析:
原因就是在使用Jupyter Notebook的時(shí)候,加載的仍然是默認(rèn)的Python Kernel。
解決:
(1)在Conda中切換到安裝PyTorch的虛擬環(huán)境,然后執(zhí)行conda install nb_conda_kernels
安裝Jupyter內(nèi)核切換工具。
安裝完成后,再重啟Jupyter Notebook,在新建腳本時(shí)就能選擇Kernal:
也可以對(duì)建好的文件切換Kernal:
2.PyTorch使用張量時(shí)報(bào)錯(cuò)expected scalar type Double but found Float
有時(shí)候,使用張量Tensor會(huì)報(bào)錯(cuò):
RuntimeError: expected scalar type Double but found Float
分析:
這是因?yàn)閺埩康臄?shù)據(jù)類(lèi)型不正確。
解決:
此時(shí)需要先進(jìn)行類(lèi)型轉(zhuǎn)換,將數(shù)據(jù)類(lèi)型轉(zhuǎn)為float32,再進(jìn)行操作,如下:
tensor = tensor.to(torch.float32)
3.PyTorch創(chuàng)建Embedding時(shí)報(bào)錯(cuò)IndexError: index out of range in self
PyTorch中很多時(shí)候都會(huì)用到Embedding嵌入,特別是在NLP任務(wù)中,用于存儲(chǔ)一個(gè)簡(jiǎn)單的存儲(chǔ)固定大小的詞典的嵌入向量的查找表,按時(shí)在創(chuàng)建EMbedding時(shí)有時(shí)候會(huì)出錯(cuò),如下:
File "E:\Anaconda3\envs\pytorchbase\Lib\site-packages\torch\nn\modules\module.py", line 1102, in _call_impl
return forward_call(*input, **kwargs)
File "E:\Anaconda3\envs\pytorchbase\Lib\site-packages\torch\nn\modules\sparse.py", line 158, in forward
return F.embedding(
File "E:\Anaconda3\envs\pytorchbase\Lib\site-packages\torch\nn\functional.py", line 2044, in embedding
return torch.embedding(weight, input, padding_idx, scale_grad_by_freq, sparse)
IndexError: index out of range in self
分析:
這是因?yàn)閚um_embeddings(詞典的詞個(gè)數(shù))不夠大,進(jìn)行詞嵌入的時(shí)候字典從1, …, n,映射所有的詞(或者字)num_embeddings =n是夠用的,但是會(huì)考慮pad,pad默認(rèn)一般是0,所以我們會(huì)重新處理一下映射字典0, 1, 2, …, n一共n+1個(gè)值,此時(shí)num_embeddings=n+1才夠映射。
解決:
修改參數(shù)num_embeddings的值為實(shí)際詞個(gè)數(shù)+1即可解決這個(gè)問(wèn)題。
掃碼進(jìn)群: