Pytorch中Tensor和Numpy数组的相互转化分为两种,第一种转化前后的对象共享相同的内存区域(即修改其中另外一个也会改变);第二种是二者并不共享内存区域。

共享内存区域的转化

这种涉及到numpy()from_numpy()两个函数。

使用numpy()函数可以将Tensor转化为Numpy数组:

a=torch.ones(5)
b=a.numpy()
print(type(a))
print(type(b))

输出:

<class 'torch.Tensor'>
<class 'numpy.ndarray'>

与这个过程相反,使用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()总会进行数据拷贝,如果我们有一个Tensor数据并且希望避免数据拷贝,那么需要使用torch.Tensor.requires_grad_()或torch.Tensor.detach()。如果我们有一个Numpy ndarray数据并且希望避免数据拷贝,那么需要使用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.
  • device (torch.device, optional) – the desired device of returned tensor. Default: if None, uses the current device for the default tensor type (see torch.set_default_tensor_type()). device will be the CPU for CPU tensor types and the current CUDA device for CUDA tensor types.
  • requires_grad (bool, optional) – If autograd should record operations on the returned tensor. Default: False.
  • pin_memory (bool, optional) – If set, returned tensor would be allocated in the pinned memory. Works only for CPU tensors. Default: False.

使用示例:

#根据输入数据创建tensor
torch.tensor([[0.1,1.2],[2.2,3.1],[4.9,5.2]])#创建tensor时指定数据类型及device
torch.tensor([[0.1111,0.2222,0.3333]],dtype=torch.float64,device=torch.device('cuda:0'))#创建一个空tensor
torch.tensor([])

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

  1. pytorch中tensor、numpy.array、list三者互相转换

    1.1 list 转 numpy ndarray = np.array(list) 1.2 numpy 转 list list = ndarray.tolist() 2.1 list 转 torch. ...

  2. Pytorch中Tensor的索引,切片以及花式索引(fancy indexing)

    目录 理解Tensor的dim 索引 简单索引 用1维的list,numpy,tensor索引 用booltensor索引 切片 花式索引 结语 前一段时间遇到一个花式索引的问题,在搜索良久之后没有找 ...

  3. python代码转换为pytorch_python基础教程Pytorch之Tensor和Numpy之间的转换的实现方法...

    为什么要相互转换: 1. 要对tensor进行操作,需要先启动一个Session,否则,我们无法对一个tensor比如一个tensor常量重新赋值或是做一些判断操作,所以如果将它转化为numpy数组就 ...

  4. pytorch tensor查找0_在PyTorch中Tensor的查找和筛选例子

    本文源码基于版本1.0,交互界面基于0.4.1 import torch 按照指定轴上的坐标进行过滤 index_select() 沿着某tensor的一个轴dim筛选若干个坐标 >>&g ...

  5. pytorch中tensor类型转换

    转载自:https://www.jb51.net/article/177575.htm,做简要记录 1.tensor与numpy数组: # tensor转numpy tensor.numpy() # ...

  6. Pytorch中tensor.view().permute().contiguous()函数理解

    Pytorch中tensor.view().permute().contiguous()函数理解 yolov3中有一行这样的代码,在此记录一下三个函数的含义 # 例子中batch_size为整型,le ...

  7. Pytorch中tensor.expand()和tensor.expand_as()函数

    Pytorch中tensor.expand函数 Tensor.expand()函数详解 Tensor.expand_as()函数 Tensor.expand()函数详解 函数语法: # 官方解释: D ...

  8. Pytorch中tensor维度和torch.max()函数中dim参数的理解

    Pytorch中tensor维度和torch.max()函数中dim参数的理解 维度 参考了 https://blog.csdn.net/qq_41375609/article/details/106 ...

  9. pyTorch中tensor运算

    文章目录 PyTorch的简介 PyTorch中主要的包 PyTorch的安装 使用GPU的原因 使数据在GPU上运行 什么使Tensor(张量) 一些术语介绍 Tensor的属性介绍(Rank,ax ...

  10. PyTorch中tensor介绍

          PyTorch中的张量(Tensor)如同数组和矩阵一样,是一种特殊的数据结构.在PyTorch中,神经网络的输入.输出以及网络的参数等数据,都是使用张量来进行描述.       torc ...

最新文章

  1. 运行ORB-SLAM笔记_编译篇(一)
  2. 中文版开源!这或许是最经典的Python编程教材
  3. Binary Tree Postorder Traversal
  4. 开发75条(写的不错) 选择自 churujianghu 的 Blog
  5. Django虚拟环境的安装和创建
  6. C++无符号整数的反转位的实现算法(附完整源码)
  7. Zabbix3.0安装文档
  8. 阿里的下一个15年:大数据是核心
  9. sql递归查询上级_递归的实际业务场景之MySQL 递归查询
  10. Keil 使用教程(详解)
  11. android日记论文摘要,(毕业论文)基于android的日记本的设计与开发.doc
  12. 一窥朝鲜的计算机技术发展,操作系统,平板,杀毒软件,都有!
  13. 搭建FTP资源服务器
  14. python 拦截windows弹窗广告_Win10如何拦截桌面弹窗广告?流氓软件怎么彻底清除?...
  15. MTK6762 安卓 4g 核心板不同配置区别对比
  16. Jenkins 前端 自动化发版/CICD
  17. ttbf 慢 php,連接數據庫不同方式會影響TTBF快慢
  18. 笔记本电脑无法连上WiFi的解决办法
  19. java nanotime 转秒_[Java] System.nanoTime()返回结果nanoSeconds和seconds之间的转换
  20. 华为、H3C、锐捷三家交换机配置命令详解

热门文章

  1. ENVI中利用平均波谱角的方法进行分类
  2. ENVI5.3.1使用Landsat 8影像进行灰度分割(密度分割)
  3. 实习踩坑之路:JSON格式错误,导致Java异常JSON parse error: Cannot deserialize instance of `java.util.ArrayList` out o
  4. Vue学习笔记----基础
  5. 使用SQL语句操作数据库-01
  6. 方正电脑如何关闭网络启动计算机,方正电脑怎么进安全模式
  7. 程序员的每个阶段,都应该需要思考自己要什么?
  8. Android支付实践(一)之支付宝支付详解与demo
  9. 计算机开机无法定位,开机提示无法定位程序输入点...于动态链接库CommFunc.dll上...
  10. 类图中表达总体与局部的关系_软件工程测试题3