如何將torch.tensor數據類型轉化爲python的內置類型?

在tensor後面加.item()即可。

import torch

a = torch.LongTensor([10])
b = a.data      # 還是tensor
c = a.item()    # int類型,而且只有單個元素纔可以用.item()轉化
print(b, type(b))
print(c, type(c))

'''輸出
tensor([10]) <class 'torch.Tensor'>
10 <class 'int'>
'''
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章