RuntimeError: Expected object of device type cuda but got device type cpu for argument pytorch数据位置
生活随笔
收集整理的這篇文章主要介紹了
RuntimeError: Expected object of device type cuda but got device type cpu for argument pytorch数据位置
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
RuntimeError: Expected object of device type cuda but got device type cpu for argument #2 ‘target’ in call to _thnn_binary_cross_entropy_forward
出錯誤背景:Pytorch 中想使用 CUDA 對程序計算進行加速
錯誤的意思:object 的 device 類型期望得到的是 cuda 類型,但是實際上的類型確實 cpu 類型,在調用二分類交叉熵損失進行前向計算的時候
檢查下面幾點:
- 模型是否放到了CUDA上
model = model.to(device)或model = model.cuda(device) - 輸入數據是否放到了CUDA上
data = data.to(device)或data = data.cuda(device) - 模型內部新建的張量是否放到了CUDA上
p = torch.tensor([1]).to(device)或p = torch.tensor([1]).cuda(device)
一般情況下應該是忘記了第三點,而根據提示也可以知道,在進行二分類交叉熵損失進行前向計算的過程中,存在沒有放到cuda上的張量,找到他,fix it !!!
其中:device = torch.device(“cuda” if torch.cuda.is_available() else “cpu”)
或者:寫一個方法,來判斷是否有cuda,然后決定是否放上去:
def trans_to_cuda(variable):if torch.cuda.is_available():return variable.cuda()else:return variable
總結
以上是生活随笔為你收集整理的RuntimeError: Expected object of device type cuda but got device type cpu for argument pytorch数据位置的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: openpyxl.utils.excep
- 下一篇: 熵,交叉熵,散度理解较为清晰