Convert between tensor and numpy

convert numpy to 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])
'''

convert tensor to 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也是内存共享的
'''

Reposted from: (60 messages) [Pytorch] Multiple ways to convert numpy arrays to tensors_numpy to tensor_Hao's Blog-CSDN Blog

Guess you like

Origin blog.csdn.net/swx595182208/article/details/130061292