.numpy() 与 .item()
这两个可以归为一类,是将Tensor变量转换为非Tensor变量。
t.numpy()
将Tensor变量转换为ndarray变量,其中t是一个Tensor变量,可以是标量,也可以是向量,转换后dtype与Tensor的dtype一致。
a = torch.tensor(1)
b = torch.tensor(1.)
c = torch.tensor([[1,2]])
d = torch.tensor([[1.,2.]])
aaa = a.numpy()
bbb = b.numpy()
ccc = c.numpy()
ddd = d.numpy()
t.item()
将Tensor变量转换为python标量(int float等),其中t是一个Tensor变量,只能是标量,转换后dtype与Tensor的dtype一致。
aa=a.item()
bb=b.item()
cc=c.item() # 报错:ValueError: only one element tensors can be converted to Python scalars
dd=d.item() #报错:ValueError: only one element tensors can be converted to Python scalars
.cpu()
将数据的处理设备从其他设备(如.cuda()拿到cpu上),不会改变变量类型,转换后仍然是Tensor变量。