在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'>
'''
在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'>
'''