張量與數組運算報錯(Use Tensor.cpu() to copy the tensor to host memory first;RuntimeError: Expected all tensors to be on the same device)


結論:1.張量與數組運算,張量必須在cpu上,產生結果為cpu上的張量,可繼續與數組運算(張量必須在gpu上)

   2.張量與張量運算,cpu上的張量與gpu上的張量是無法運行的,必須在相同的gpu上或cpu上,猜想不同型號的gpu因該也不行。

 

 

 

一.張量與數組運算,前提張量必須在cpu上(如果張量在gpu上,則會報錯(我認為數組本身在cpu上,因此2個操作在cpu上,就可以默認運行)),運算結果將會轉到cpu上,具體操作如下:

注:報錯代碼 TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.

代碼如下:

b=np.array(9) # numpy 數組
a = torch.ones((2, 2)) # 張量
print('a in device :',a.device)
c=a*b # 數組與張量運算,其中張量在cpu上
print('c in device:{};value{}'.format(c.device,c))



結果如圖:

 

 報錯結果:

 

 

繼續探討張量與數組運算:

b=np.array(9) # numpy 數組
a = torch.ones((2,2)) # 張量
print('a in device :',a.device)
c=a*b # 數組與張量運算,其中張量在cpu上
print('c in device:{};value:{}'.format(c.device,c))
d=np.array(8)
e=c*d # 繼續驗證數組與產生的張量運算
print('e in device:{};value:{}'.format(e.device, e))

結果如圖:

 

 二.張量與張量運算,若在不同設備會報錯,RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!,結論很清楚,而具體過程如下:

  代碼如下:

b=torch.ones((2,2)) # numpy 數組
b=b.cpu()
a = torch.ones((2,2)) # 張量
a=a.cuda()
print('a in device :{};b in device :{}'.format(a.device,b.device))
c=a*b # 數組與張量運算,其中張量在cpu上
print('c in device:{};value:{}'.format(c.device,c))

結果如下:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM