【Pytorch】numpy数组与tensor互相转换的多种方法

时间:2025-02-28 09:21:59
一、numpy数组转化为torch中的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)

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])
'''

上述中可以看出来:

  1. numpy中array默认的数据格式是int64类型,而torch中tensor默认的数据格式是float32类型
  2. as_tensor和from_numpy是浅拷贝,而tensor和Tensor则是属于深拷贝,浅拷贝是直接共享内存内存空间的,这样效率更高,而深拷贝是直接创建一个新的副本。
二、torch中的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也是内存共享的。