栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Pytorch中Tensor和numpy数组的互相转化

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Pytorch中Tensor和numpy数组的互相转化

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/272757.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号