python - 将 1d 张量连同 pytorch 中 2d 张量的对角线展开为 2d 张量
问题描述
在 Pytorch 中有什么方法可以将 1dtensor([[1., 2., 3., 4.]])
转换为
tensor([[1., 2., 3., 4.],
[2., 1., 2., 3.],
[3., 2., 1., 2.],
[4., 3., 2., 1.]])
解决方案
torch.roll
不幸的是,只适用于维度,所以你将不得不expand
使用类似的东西torch.gather
,以及一组索引移位:
t = tensor([[1., 2., 3., 4.]])
idx = torch.arange(4)
idx = torch.stack([torch.roll(idx, shift) for shift in range(0,-4,-1)])
torch.gather(t.expand(4,-1), 1, idx)
推荐阅读
- javascript - 如何从模拟模块模拟多个值?
- php - 我有一个可以提交的表单,但是当我添加文件上传功能时它不起作用
- java - Spring Data/JPA:如何保存具有多个子集合的项目?
- java - 我有一个休眠问题。启动我的应用程序时速度很慢,使用休眠启动第一个 sessionFactory 需要 2 分钟
- java - iText 7如何为整个文档设置字体
- python - 在 64 位 Mac OSX 上的 64 位 python 解释器上构建“orjson”时,requirement.txt 安装失败
- excel - 我们可以在连接的 Excel 文件打开时修改数据库吗?
- c++ - 什么决定了 constexpr 函数是否是常量表达式?
- r - 外连接与 R 中的条件
- sparql - 如何在 SPARQL (Wikidata) 中任意分组值?