索引操作

Tensor支持与numpy.ndarray类似的索引操作,语法上也类似,下面通过一些例子,讲解常用的索引操作。如无特殊说明,索引出来的结果与原tensor共享内存,也即修改一个,另一个会跟着修改。

In [31]:

a = t.randn(3, 4)
a
Out[31]:
tensor([[ 1.1741,  1.4335, -0.8156,  0.7622],[-0.6334, -1.4628, -0.7428,  0.0410],[-0.6551,  1.0258,  2.0572,  0.3923]])

In [32]:

a[0] # 第0行(下标从0开始)

Out[32]:

tensor([ 1.1741,  1.4335, -0.8156,  0.7622])

In [33]:

a[:, 0] # 第0列

Out[33]:

tensor([ 1.1741, -0.6334, -0.6551])

In [34]:

a[0][2] # 第0行第2个元素,等价于a[0, 2]

Out[34]:

tensor(-0.8156)

In [35]:

a[0, -1] # 第0行最后一个元素

Out[35]:

tensor(0.7622)

In [36]:

a[:2] # 前两行

Out[36]:

tensor([[ 1.1741,  1.4335, -0.8156,  0.7622],[-0.6334, -1.4628, -0.7428,  0.0410]])

In [37]:

a[:2, 0:2] # 前两行,第0,1列

Out[37]:

tensor([[ 1.1741,  1.4335],[-0.6334, -1.4628]])

In [38]:

print(a[0:1, :2]) # 第0行,前两列
print(a[0, :2]) # 注意两者的区别:形状不同
Out[38]:
tensor([[1.1741, 1.4335]])
tensor([1.1741, 1.4335])

In [39]:

# None类似于np.newaxis, 为a新增了一个轴
# 等价于a.view(1, a.shape[0], a.shape[1])
a[None].shape

Out[39]:

torch.Size([1, 3, 4])

In [40]:

a[None].shape # 等价于a[None,:,:]

Out[40]:

torch.Size([1, 3, 4])

In [41]:

a[:,None,:].shape

Out[41]:

torch.Size([3, 1, 4])

In [42]:

a[:,None,:,None,None].shape

Out[42]:

torch.Size([3, 1, 4, 1, 1])

In [43]:

a > 1 # 返回一个ByteTensor

Out[43]:

tensor([[1, 1, 0, 0],[0, 0, 0, 0],[0, 1, 1, 0]], dtype=torch.uint8)

In [44]:

a[a>1] # 等价于a.masked_select(a>1)
# 选择结果与原tensor不共享内存空间

Out[44]:

tensor([1.1741, 1.4335, 1.0258, 2.0572])

In [45]:

a[t.LongTensor([0,1])] # 第0行和第1行

Out[45]:

tensor([[ 1.1741,  1.4335, -0.8156,  0.7622],[-0.6334, -1.4628, -0.7428,  0.0410]])

其它常用的选择函数如表3-2所示。

表3-2常用的选择函数

函数 功能
index_select(input, dim, index) 在指定维度dim上选取,比如选取某些行、某些列
masked_select(input, mask) 例子如上,a[a>0],使用ByteTensor进行选取
non_zero(input) 非0元素的下标
gather(input, dim, index) 根据index,在dim维度上选取数据,输出的size与index一样

gather是一个比较复杂的操作,对一个2维tensor,输出的每个元素如下:

out[i][j] = input[index[i][j]][j]  # dim=0
out[i][j] = input[i][index[i][j]]  # dim=1

三维tensor的gather操作同理,下面举几个例子。

In [46]:

a = t.arange(0, 16).view(4, 4)
a

Out[46]:

tensor([[ 0,  1,  2,  3],[ 4,  5,  6,  7],[ 8,  9, 10, 11],[12, 13, 14, 15]])

In [47]:

# 选取对角线的元素
index = t.LongTensor([[0,1,2,3]])
a.gather(0, index)

Out[47]:

tensor([[ 0,  5, 10, 15]])

In [48]:

# 选取反对角线上的元素
index = t.LongTensor([[3,2,1,0]]).t()
a.gather(1, index)

Out[48]:

tensor([[ 3],[ 6],[ 9],[12]])

In [49]:

# 选取反对角线上的元素,注意与上面的不同
index = t.LongTensor([[3,2,1,0]])
a.gather(0, index)

Out[49]:

tensor([[12,  9,  6,  3]])

In [50]:

# 选取两个对角线上的元素
index = t.LongTensor([[0,1,2,3],[3,2,1,0]]).t()
b = a.gather(1, index)
b

Out[50]:

tensor([[ 0,  3],[ 5,  6],[10,  9],[15, 12]])

gather相对应的逆操作是scatter_gather把数据从input中按index取出,而scatter_是把取出的数据再放回去。注意scatter_函数是inplace操作。

out = input.gather(dim, index)
-->近似逆操作
out = Tensor()
out.scatter_(dim, index)

In [51]:

# 把两个对角线元素放回去到指定位置
c = t.zeros(4,4)
c.scatter_(1, index, b.float())

Out[51]:

tensor([[ 0.,  0.,  0.,  3.],[ 0.,  5.,  6.,  0.],[ 0.,  9., 10.,  0.],[12.,  0.,  0., 15.]])

对tensor的任何索引操作仍是一个tensor,想要获取标准的python对象数值,需要调用tensor.item(), 这个方法只对包含一个元素的tensor适用

In [52]:

a[0,0] #依旧是tensor)

Out[52]:

tensor(0)

In [53]:

a[0,0].item() # python float

Out[53]:

0

In [54]:

d = a[0:1, 0:1, None]
print(d.shape)
d.item() # 只包含一个元素的tensor即可调用tensor.item,与形状无关
torch.Size([1, 1, 1])

Out[54]:

0

In [55]:

# a[0].item()  ->
# raise ValueError: only one element tensors can be converted to Python scalars

高级索引

PyTorch在0.2版本中完善了索引操作,目前已经支持绝大多数numpy的高级索引1。高级索引可以看成是普通索引操作的扩展,但是高级索引操作的结果一般不和原始的Tensor共享内存。


  1. https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing↩

In [56]:

x = t.arange(0,27).view(3,3,3)
x

Out[56]:

tensor([[[ 0,  1,  2],[ 3,  4,  5],[ 6,  7,  8]],[[ 9, 10, 11],[12, 13, 14],[15, 16, 17]],[[18, 19, 20],[21, 22, 23],[24, 25, 26]]])

In [57]:

x[[1, 2], [1, 2], [2, 0]] # x[1,1,2]和x[2,2,0]

Out[57]:

tensor([14, 24])

In [58]:

x[[2, 1, 0], [0], [1]] # x[2,0,1],x[1,0,1],x[0,0,1]

Out[58]:

tensor([19, 10,  1])

In [59]:

x[[0, 2], ...] # x[0] 和 x[2]

Out[59]:

tensor([[[ 0,  1,  2],[ 3,  4,  5],[ 6,  7,  8]],[[18, 19, 20],[21, 22, 23],[24, 25, 26]]])

Tensor:索引操作相关推荐

  1. PyTorch 笔记(06)— Tensor 索引操作(index_select、masked_select、non_zero、gather)

    Tensor 支持与 numpy.ndarray 类似的索引操作,如无特殊说明,索引出来的结果与源 tensor 共享内存,即修改一个,另外一个也会跟着改变. In [65]: a = t.arang ...

  2. 深入解析Tensor索引中的Indexing Multi-dimensional arrays问题

    写在前面 最近小弟做了一些实验,但是发现我写的代码虽然能够跑通,但是对于gpu的利用率始终在一个比较低的水平,这就很难受,别人的代码2h就跑完了,我得10h,经过排查发现究其原因就是代码的并行化成都不 ...

  3. 【Pandas库】(6) 索引操作--改、查、高级索引

    各位同学好,今天我和大家分享一下Pandas库的索引操作中的修改值.查找值.高级索引. 首先,我们先定义两个变量ps1存放Series数据,pd1存放DataFrame数据,以便后续操作. impor ...

  4. 【Pandas库】(5) 索引操作--增、删

    各位同学好,今天我向大家介绍一下pandas库中的索引操作--增.删. 1. 增加 1.1 对series操作 方法一:在原有数据上增加,改变原有数据. Series名[新标签名] = 新标签名对应的 ...

  5. 【Pandas库】(4) 索引操作--重新生成索引

    各位同学好,今天和大家分享一下pandas库的索引操作--重新生成索引. 本文主要介绍如何重新生成Series类型和DataFrame类型的索引. (1)Series类型重新生成索引 方法: 变量 = ...

  6. Mongodb的索引操作

    Mongodb的索引操作 1. 为什么mongdb需要创建索引 加快查询速度 进行数据的去重 2. mongodb创建简单的索引方法 语法:db.集合名.ensureIndex({属性:1}),1表示 ...

  7. 数据分析工具Pandas(2):Pandas的索引操作

    数据分析工具Pandas(1):Pandas的数据结构 数据分析工具Pandas(2):Pandas的索引操作 Pandas的索引操作 索引对象Index 1. Series和DataFrame中的索 ...

  8. elasticsearch建立索引操作的API

    Elastic Search API Index.简单的介绍了使用Elastic Search 如何建立索引. ElasticSearch-API-Index 索引创建API允许初始化一个索引.Ela ...

  9. SQL2K数据库开发二十三之索引操作重建索引

    1.可以使用下面的语句创建索引,重建索引应使用DROP_EXISTING选项. 2.在SQL Server查询分析器中输入如下的SQL语句,点击工具栏上的执行查询图标. 3.查询语句执行完毕后,结果窗 ...

最新文章

  1. html盒子移动动画代码,HTML5/Canvas 盒子追踪动画
  2. myeclipse新建映射文件xxx.hbm.xml
  3. 有很多人都想知道SSD201开放了openwrt到底有什么好处?为什么好多开发者都盼着要呢?
  4. 仁慈型dea matlab程序,数据包络分析(DEA)方法..docx
  5. ux设计师怎样找同类产品_没有预算? 别找借口。 便宜的UX上的UX 2:让我们开始构建。...
  6. map key char*
  7. 程序员求助:被领导强行要求写Bug该怎么办?网友的回答让我笑翻
  8. 用python画三维图、某区域的高程,python - 在PyQt中绘制具有高程和降低效果的3D矩形/多边形 - SO中文参考 - www.soinside.com...
  9. html5jqueryl轮播图,基于JQuery的实现图片轮播效果(焦点图)
  10. matlab有限体积网格,用Matlab实现简单有限体积求解器
  11. EF异常:“System.InvalidOperationException”类型的未经处理的异常在 mscorlib.dll 中发生
  12. 干货 | 你是不是希望一月入门深度学习,三月中一篇顶会?-- 关于做科研的态度和方法的一点感想...
  13. 57. web 攻击技术
  14. Flash cs4 for mac 序列号
  15. 多年 iOS 开发经验总结
  16. adams如何保存_实用的Adams使用技巧
  17. 中间件——《中间件技术原理及应用》考试复习重点
  18. 记一次Exception in thread main java.lang.NullPointerException异常
  19. DDU(Display Driver Uninstaller) 18.0.3.5 显卡驱动彻底卸载清理工具,支持卸载NVIDIA, AMD, Intel
  20. [湖南大学程序设计实训训练作业一]7.F1方程式冠军(灵活运用下标来简化代码)

热门文章

  1. 第76节:Java中的基础知识
  2. docker运行dubbo-admin
  3. __gnu_cxx::hash_map使用中的一些问题
  4. UVA 620 - Cellular Structure
  5. [转载]:C#两种不同的存储过程调用方法
  6. xml引入约束示例(xsd文件)
  7. python为什么那么多人点赞_python为何会火遍全球?它究竟是什么呢?阿里大佬告诉你答案...
  8. grDevices | R语言中的配色方法汇总(Ⅱ-2)
  9. 做web前端的小伙伴注意了,未来这些发展方向可以试试!
  10. mysql数据库执行事务日志_第十章 MySQL事务及其日志介绍