1. CPU tensor转GPU tensor:
cpu_imgs.cuda()
2. GPU tensor 转CPU tensor:
gpu_imgs.cpu()
3. numpy转为CPU tensor:
torch.from_numpy( imgs )
4.CPU tensor转为numpy数据:
cpu_imgs.numpy()
5. note:GPU tensor不能直接转为numpy数组,必须先转到CPU tensor。
6. 如果tensor是标量的话,可以直接使用 item() 函数(只能是标量)将值取出来:
print loss_output.item()
类型转换
和numpy中的astype函数一样,是返回值才是改变类型后的结果,调用的变量类型不变
newtensor = tensor.long() #将tensor投射为long类型
newtensor = tensor.half() #将tensor投射为半精度浮点类型
newtensor = tensor.int() #将该tensor投射为int类型
newtensor = tensor.double() #将该tensor投射为double类型
newtensor = tensor.float() #将该tensor投射为float类型
newtensor = tensor.char() #将该tensor投射为char类型
newtensor = tensor.byte() #将该tensor投射为byte类型
newtensor = tensor.short() #将该tensor投射为short类型