numpy转为tensor
import torch
import numpy as np
arr1 = np.array([1,2,3], dtype=np.float32)
arr2 = np.array([4,5,6])
print(arr1.dtype)
print("nunpy中array的默认数据类型为:", arr2.dtype)
##########四种方法###########
'''
numpy中array默认的数据格式是int64类型,而torch中tensor默认的数据格式是float32类型。
as_tensor和from_numpy是浅拷贝,而tensor和Tensor则是属于深拷贝,浅拷贝是直接共享内存内存空间的,这样效率更高,而深拷贝是直接创建一个新的副本。
'''
tensor = torch.tensor(arr2)
Tensor = torch.Tensor(arr2)
as_tensor = torch.as_tensor(arr2)
from_numpy = torch.from_numpy(arr2)
print(tensor.dtype, "|",Tensor.dtype, "|",as_tensor.dtype, "|",from_numpy.dtype)
arr2[0] = 10
print(tensor, Tensor, as_tensor, from_numpy)
'''
结果为:
float32
numpy中array的默认数据类型为: int64
torch.int64 | torch.float32 | torch.int64 | torch.int64
tensor([4, 5, 6]) tensor([4., 5., 6.]) tensor([10, 5, 6]) tensor([10, 5, 6])
'''
tensor转为numpy
import torch
import numpy as np
a = torch.ones(5)
b = a.numpy()
b[0] = 2
print(a)
print(b)
'''
tensor([2., 1., 1., 1., 1.])
[2. 1. 1. 1. 1.]
numpy() 方法将tensor转numpy的array也是内存共享的
'''
转自:(60条消息) 【Pytorch】numpy数组与tensor互相转换的多种方法_numpy转tensor_郝同学的博客-CSDN博客