python - 将 Tenor 的索引和值组合成一个新的张量
问题描述
我有一个像a = torch.tensor([1,2,0,1,2])
. 我想计算一个具有张量b
索引和值的张量a
:
b = tensor([ [0,1], [1,2], [2,0], [3,1], [4,2] ])
.
编辑:a[i] is >= 0
。
解决方案
一种方法是:
b = torch.IntTensor(list(zip(range(0, list(a.size())[0], 1), a.numpy())))
输出:
tensor([[0, 1],
[1, 2],
[2, 0],
[3, 1],
[4, 2]], dtype=torch.int32)
或者,您也可以使用torch.cat()
如下:
a = torch.tensor([1,2,0,1,2])
indices = torch.arange(0, list(a.size())[0])
res = torch.cat([indices.view(-1, 1), a.view(-1, 1)], 1)
输出:
tensor([[0, 1],
[1, 2],
[2, 0],
[3, 1],
[4, 2]])
推荐阅读
- amazon-web-services - 没有卷附加到正在运行的 mysql docker 容器 - AWS Elastic beanstalk 多容器 docker 应用程序
- c# - 作为 Stripe 更新的一部分,如何用 statement_descriptor_suffix 替换 statement_descriptor 参数
- python-3.x - 如何使用循环以及如何将值保存在新变量中
- javascript - 如何将两个下载的数组合并为一个 JSON 数组?
- javascript - 如何将 AWS Mobile Hub 与 NativeScript 结合使用
- css - ios Mobile复选框边框错误
- java - 有没有办法让套接字线程在多个活动中运行?
- css - 在条件下为引导多选中的选项添加颜色
- php - 如何在 PHP 中使用 file_get_contents 从变量中回显
- google-analytics - 将自定义数据导入GA,自定义维度数据不显示