导读

在使用pytorch的时候我们经常会用到将numpy array转为tensor,以及将tensor转为numpy array的情况。pytroch内置了几种不同的方法可以方便我们将numpy array转换称为tensor,那么这些方法之间究竟有何异同呢?下面我们就来介绍一下

实践

import torch
import numpy as np#创建一个numpy array的数组
array = np.array([1,2,3,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(array.dtype)      #int64
#查看torch默认的数据类型
print(torch.get_default_dtype())    #torch.float32#对比几种不同方法之间的异同
print(tensor.dtype)     #torch.int64
print(Tensor.dtype)     #torch.float32
print(as_tensor.dtype)  #torch.int64
print(from_array.dtype) #torch.int64

我们通过初步的实践分析发现,只有Tensor方法创建的tensor使用了torch的默认数据类型,而其他三种方法都使用了numpy array中的int64数据类型

接下来我们进一步分析,如果我们改变数组的值,会发生什么事情

#创建一个numpy array的数组
array = np.array([1,2,3,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)#修改数组的值
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])

通过上面的例子发现,as_tensor方法from_array方法转换的tensor的值都发生了改变,说明其实它们使用的数据和numpy array使用的数据是一样的,也就是说它们和numpy array其实是共享内存的。而Tensor方法tensor方法在转换的时候,则是开辟了新的内存空间来存储tensor的。

总结:所以as_tensorfrom_array是浅拷贝,而tensorTensor则是属于深拷贝,如果我们不会去改变数组里面的数据时,建议采用浅拷贝,这样效率会更高点,因为它们是共享内存的。但是,如果我们有对转换后的tensor做类似fill_scatter_这样的操作时,就需要注意是否能够使用as_tensorfrom_array了。

关于torch中的fill_和scatter_

torh里面包含了很多类似于fill_scatter_方法,带_的方法都是直接修改tensor的内容的。如果我们再转换numpy array时采用的是from_arrayas_tensor就会导致numpy array里面的值也被修改

#创建一个numpy array的数组
array = np.array([1,2,3,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)# 修改tensor的内容
fill_tensor = tensor.fill_(0)
print(fill_tensor)          #tensor([0, 0, 0, 0])
print(array)                #[1 2 3 4]
fill_Tensor = Tensor.fill_(1)
print(fill_Tensor)          #tensor([1., 1., 1., 1.])
print(array)                #[1 2 3 4]
fill_as_tensor = as_tensor.fill_(2)
print(fill_as_tensor)       #tensor([2, 2, 2, 2])
print(array)                #[2 2 2 2]
fill_from_array = from_array.fill_(3)
print(fill_from_array)      #tensor([3, 3, 3, 3])
print(array)                #[3 3 3 3]

因为from_arrayas_tensor和numpy array是共享内存的,所以当修改tensor里面的值时numpy array也会被修改

torch里面的Tensor、as_tensor、tensor以及from_numpy究竟有何区别?相关推荐

  1. PyTorch里面的torch.nn.Parameter()

    在刷官方Tutorial的时候发现了一个用法self.v = torch.nn.Parameter(torch.FloatTensor(hidden_size)),看了官方教程里面的解释也是云里雾里, ...

  2. Python 基础torch.stack(tensors: Union[Tuple[Tensor, ...], List[Tensor]], dim: _int=0, *, out: Option)

    stack(inputs, dim=) :沿着一个新维度对输入张量序列进行连接. 序列中所有的张量都应该为相同形状. np.stack() import numpy as np a=np.array( ...

  3. RCAR会议:我的RTFA算法里面的generate_detections.py文件

    地址: nk_DeepSortYolo/deep_sort_yolov3-master/tools/generate_detections.py # vim: expandtab:ts=4:sw=4 ...

  4. Pytorch List Tensor转Tensor,,reshape拼接等操作

    Pytorch List Tensor转Tensor,reshape拼接等操作 持续更新一些常用的Tensor操作,比如List,Numpy,Tensor之间的转换,Tensor的拼接,维度的变换等操 ...

  5. python和pytorch是什么关系_【PyTorch】Tensor和tensor的区别

    本文列举的框架源码基于PyTorch1.0,交互语句在0.4.1上测试通过 import torch 在PyTorch中,Tensor和tensor都能用于生成新的张量: >>> a ...

  6. 解决IndexError: invalid index of a 0-dim tensor. Use tensor.item() to convert a 0-dim tensor to a Pyth

    解决IndexError: invalid index of a 0-dim tensor. Use tensor.item() to convert a 0-dim tensor to a Pyth ...

  7. YDOOK AI : Pytorch :使用 tensor.zeros() tensor.zeros_like() 生成定义 全零数组 全0数组

    YDOOK AI : Pytorch :使用 tensor.zeros() tensor.zeros_like() 生成定义 全零数组 全0数组 1_1. tensor.zeros() 函数: tor ...

  8. invalid index of a 0-dim tensor. Use `tensor.item()`

    使用1.7.1版本的torch框架运行代码时出现问题报错如下: invalid index of a 0-dim tensor. Use tensor.item() in Python or tens ...

  9. UserWarning: This overload of nonzero is deprecated: nonzero(Tensor input, Tensor out) 解决

    问题: ../torch/csrc/utils/python_arg_parser.cpp:738: UserWarning: This overload of nonzero is deprecat ...

最新文章

  1. Static与函数指针 转
  2. 面试题整理17 输入一个字符串判断一个字符串是否是有效ip地址
  3. 判断一个字符串是否全部不相同
  4. Ubuntu 防火墙 ufw
  5. RabbitMq入门(七)消息处理(消息持久化autoDelete、消息确认ACK机制)
  6. 五项技术创新 创造未来出行新体验
  7. python获取时间戳毫秒级_Python获取秒级时间戳与毫秒级时间戳
  8. python图像对比_Python多种图像处理库的比较与比较
  9. Elasticsearch6.x和Kibana6.x的安装
  10. 三维重建_对比几个三维重建系统(大部分开源)
  11. 如何让你的SQL运行得更快(二)
  12. 打乱 数字_“142857”金字塔中的神秘数字,其中隐藏什么秘密?
  13. Git版本控制管理(七)--提交和查看提交历史
  14. mysql登录框万能密码_网站登录万能密码
  15. Spark入门到精通
  16. File Systems Unfit as Distributed Storage Backends 开发十年Ceph的经验:文件系统不适合作为分布式存储后端
  17. 如何写一篇综述论文、浅谈
  18. 第一课 程小奔之晃一晃
  19. 如何营造游戏的打击感(一)
  20. 全方面对比流行报表开发工具,哪一个才是你的菜?

热门文章

  1. 【毕业设计】基于SSM实现酒店管理系统(论文+源码+ppt+视频)
  2. 微信开发之服务号设置
  3. 计算机网络实验三 路由协议的配置
  4. 送您一份《学编程笔记本电脑选购指南》,建议收藏!
  5. Android JNI for Android Studio 2.2 or higher
  6. 安卓root本质操作
  7. M资源,每个进程最多N个资源,最多几个进程不会发生死锁
  8. 51单片机 AT24C02 PROTEUS 读写程序 源码
  9. Windows系统配置
  10. 网络三维虚拟展馆开发优势