import torch
a0 = torch.ones(6)
print(a0)
运行结果:
tensor([1., 1., 1., 1., 1., 1.])
a1 = a0.numpy()
print(a1)
运行结果:
[1. 1. 1. 1. 1. 1.]
①转换后的tensor与numpy指向同一地址,所以对其中一个变量的值改变另一方也会随之改变。
a0.add_(1)
print('a0=',a0)
print('a1=',a1)
运行结果:
a0= tensor([3., 3., 3., 3., 3., 3.])
a1= [3. 3. 3. 3. 3. 3.]
②如果想把CUDA tensor格式的数据改成numpy时,需要先将其转换成cpu float-tensor随后再转到numpy格式。
numpy不能直接读取CUDA tensor,需要将它转化为 CPU tensor。
import torch
a=torch.ones(6)
if torch.cuda.is_available():
a=a.cuda()
print(a)
运行结果:
tensor([1., 1., 1., 1., 1., 1.], device=‘cuda:0’)
a=a.numpy()
运行结果:
TypeError: can’t convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.
a=a.cpu().numpy()
print(a)
运行结果:
[1. 1. 1. 1. 1. 1.]
import numpy as np
a = np.ones(6)
b = torch.from_numpy(a)
np.add(a, 1, out=a)
print('a=',a)
print('b=',b)
print('typea=',a.dtype)
print('typeb=',b.dtype)
运行结果:
a= [2. 2. 2. 2. 2. 2.]
b= tensor([2., 2., 2., 2., 2., 2.], dtype=torch.float64)
typea= float64
typeb= torch.float64
注意: 转换后的tensor与numpy指向同一地址,所以对其中一个变量的值改变另一方也会随之改变。且转换后的数据类型与源类型一致。
import numpy as np
a = np.ones(6)
b = torch.Tensor(a)
np.add(a, 1, out=a)
print('a=',a)
print('b=',b)
print('typea=',a.dtype)
print('typeb=',b.dtype)
运行结果:
a= [2. 2. 2. 2. 2. 2.]
b= tensor([1., 1., 1., 1., 1., 1.])
typea= float64
typeb= torch.float32
注意: 转换后的tensor与numpy不指向同一地址,所以对其中一个变量的值改变另一方不会随之改变。且不论源数据类型是什么,转换后的数据类型均为float32。
①torch.Tensor和torch.from.numpy都可以将numpy类转化为tensor类,但torch.from.numpy更加安全,使用torch.Tensor在非float类型下会与预期不符。
也就是说,党转换的源是float类型,torch.Tensor与torch.from.numpy会共享一块内存,且转换后的结果类型都是torch.float32。
当转换的源不是float类型,torch.Tensor得到的是torch.float32,而torch.from_numpy则是与源类型一致。
②除chartensor外所有tensor都可以转换为numpy