1、pytorch与numpy 函数对比
2、array 转换为 tensor
torch.Tensor(array)
torch.tensor(array)
torch.as_tensor(array)
torch.from_array(array)
import torch
import numpy as np
array = np.array([1,2,3,4])
print(array.dtype) #int64
# 用4种方式 将numpy array转换为torch tensor
tensor = torch.tensor(array)
Tensor = torch.Tensor(array)
as_tensor = torch.as_tensor(array)
from_array = torch.from_numpy(array)
# ====== 对比几种不同方法之间的异同 =========
print(tensor.dtype) #torch.int64
print(Tensor.dtype) #torch.float32
print(as_tensor.dtype) #torch.int64
print(from_array.dtype) #torch.int64
# ========== 判断是否共享内存 ===========
#修改数组的值
array[0] = 10
print(tensor) #tensor([1, 2, 3, 4])
print(Tensor) #tensor([1., 2., 3., 4.])
print(as_tensor) #tensor([10, 2, 3, 4])
print(from_array) #tensor([10, 2, 3, 4])
结论:
1)torch.Tensor() 和 torch.tensor() 在转换的时候,是开辟了新的内存空间来存储tensor的。
- torch.Tensor 在生成tensor的时候,默认生成 float数据类型
- torch.tensor 是根据的情况来推断长生什么样的数据类型。
2)torch.as_tensor() 和 torch.from_array() 转换的tensor,和 numpy array 是共享内存的;所以数据肯定也是一致的。
3、tensor 转换为 array
import numpy as np
import torch
a = torch.tensor([1, 2, 3])
b = np.array(a)
print(a) # tensor([1, 2, 3])
print(b) # [1 2 3]