详解PyTorch中Tensor的高阶操作

作者:Steven·简谈 时间:2021-11-24 12:08:00 

条件选取:torch.where(condition, x, y) → Tensor

返回从 x 或 y 中选择元素的张量,取决于 condition

操作定义:

详解PyTorch中Tensor的高阶操作

举个例子:


>>> import torch
>>> c = randn(2, 3)
>>> c
tensor([[ 0.0309, -1.5993, 0.1986],
   [-0.0699, -2.7813, -1.1828]])
>>> a = torch.ones(2, 3)
>>> a
tensor([[1., 1., 1.],
   [1., 1., 1.]])
>>> b = torch.zeros(2, 3)
>>> b
tensor([[0., 0., 0.],
   [0., 0., 0.]])
>>> torch.where(c > 0, a, b)
tensor([[1., 0., 1.],
   [0., 0., 0.]])

把张量中的每个数据都代入条件中,如果其大于 0 就得出 a,其它情况就得出 b,同样是把 a 和 b 的相同位置的数据导出。

查表搜集:torch.gather(input, dim, index, out=None) → Tensor

沿给定轴 dim,将输入索引张量 index 指定位置的值进行聚合

对一个3维张量,输出可以定义为:

  • out[i][j][k] = tensor[index[i][j][k]][j][k] # dim=0

  • out[i][j][k] = tensor[i][index[i][j][k]][k] # dim=1

  • out[i][j][k] = tensor[i][j][index[i][j][k]] # dim=3

举个例子:


>>> a = torch.randn(4, 10)
>>> b = a.topk(3, dim = 1)
>>> b
(tensor([[ 1.0134, 0.8785, -0.0373],
   [ 1.4378, 1.4022, 1.0115],
   [ 0.8985, 0.6795, 0.6439],
   [ 1.2758, 1.0294, 1.0075]]), tensor([[5, 7, 6],
   [2, 5, 8],
   [5, 9, 2],
   [7, 9, 6]]))
>>> index = b[1]
>>> index
tensor([[5, 7, 6],
   [2, 5, 8],
   [5, 9, 2],
   [7, 9, 6]])
>>> label = torch.arange(10) + 100
>>> label
tensor([100, 101, 102, 103, 104, 105, 106, 107, 108, 109])
>>> torch.gather(label.expand(4, 10), dim=1, index=index.long()) # 进行聚合操作
tensor([[105, 107, 106],
   [102, 105, 108],
   [105, 109, 102],
   [107, 109, 106]])

把 label 扩展为二维数据后,以 index 中的每个数据为索引,取出在 label 中索引位置的数据,再以 index 的的位置摆放。

比如,最后得出的结果中,第一行的 105 就是 label.expand(4, 10) 中第一行中索引为 5 的数据,提取出来后放在 5 所在的位置。

来源:https://blog.csdn.net/weixin_44613063/article/details/89741267

标签:PyTorch,Tensor,高阶操作
0
投稿

猜你喜欢

  • Keras 切换后端方式(Theano和TensorFlow)

    2023-05-30 22:35:03
  • oracle下加密存储过程的方法

    2009-02-28 10:50:00
  • 改进评论提交表单

    2009-03-25 20:37:00
  • ASP(JScript)构建SQL语句“类”

    2008-04-30 07:12:00
  • 发散后的期望

    2008-07-31 18:32:00
  • Python3.7基于hashlib和Crypto实现加签验签功能(实例代码)

    2023-03-25 16:23:00
  • 段正淳的css笔记(7)-表单在各浏览器的表现统一

    2008-01-14 02:47:00
  • python判断、获取一张图片主色调的2个实例

    2022-07-26 18:27:00
  • Python使用base64模块进行二进制数据编码详解

    2023-08-26 20:13:13
  • 下拉列表两级连动的新方法(一)

    2009-06-04 18:18:00
  • Python字典 dict几种遍历方式

    2023-01-14 19:48:28
  • Python 利用邮件系统完成远程控制电脑的实现(关机、重启等)

    2023-12-23 19:32:54
  • Python3.6 之后字典是有序的?

    2021-02-14 08:27:53
  • SQL Server数据库入门学习总结

    2012-08-21 11:01:33
  • Python全栈之字符串和列表相关操作

    2022-02-04 04:15:25
  • Selenium定位元素操作示例

    2022-01-21 04:23:56
  • php中session_unset与session_destroy的区别分析

    2023-07-17 21:34:56
  • asp如何使用Office Chart 9.0 制作图表?

    2010-06-05 12:41:00
  • python 基于Appium控制多设备并行执行

    2022-12-11 12:00:06
  • PHPMyadmin2.10中文显示为乱码的解决办法

    2007-08-22 08:18:00
  • asp之家 网络编程 m.aspxhome.com