Pytorch中Tensor和Numpy数组的相互转化分为两种,第一种转化前后的对象共享相同的内存区域(即修改其中另外一个也会改变);第二种是二者并不共享内存区域。
首先介绍第一种共享内存区域的转化方式,涉及到numpy()和from_numpy()两个函数。
使用numpy()函数可以将Tensor转化为Numpy数组:
a=torch.ones(5) b=a.numpy() print(type(a)) print(type(b))
输出:
与这个过程相反,使用from_numpy()函数可以将Numpy数组转化为Tensor:
a=np.ones(5) b=torch.from_numpy(a)
第二种方式就是通过torch.tensor()将Numpy转化为Tensor,这种方式会进行数据的拷贝,返回的Tensor与原来的数据并不共享内存。
这个函数的具体介绍如下:
函数原型:
torch.tensor(data, *, dtype=None, device=None, requires_grad=False, pin_memory=False) → Tensor
注意事项:
torch.tensor() always copies data. If you have a Tensor data and want to avoid a copy, use torch.Tensor.requires_grad_() or torch.Tensor.detach(). If you have a NumPy ndarray and want to avoid a copy, use torch.as_tensor().
When data is a tensor x, torch.tensor() reads out ‘the data’ from whatever it is passed, and constructs a leaf variable. Therefore torch.tensor(x) is equivalent to x.clone().detach() and torch.tensor(x, requires_grad=True) is equivalent to x.clone().detach().requires_grad_(True). The equivalents using clone() and detach() are recommended.
参数:
- data:(array_like) – Initial data for the tensor. Can be a list, tuple, NumPy ndarray, scalar, and other types.
- dtype (torch.dtype, optional) – the desired data type of returned tensor. Default: if None, infers data type from data.
待补充
https://pytorch.org/docs/stable/generated/torch.tensor.html?highlight=torch%20tensor#torch.tensor



