作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
让 a
成为 (n, d, l)
张量。让 indices
成为 (n, 1)
张量,包含索引。我要从a
收集在来自 indices
给出的索引的中间维度张量中.因此,生成的张量的形状为 (n, l)
.
n = 3
d = 2
l = 3
a = tensor([[[ 0, 1, 2],
[ 3, 4, 5]],
[[ 6, 7, 8],
[ 9, 10, 11]],
[[12, 13, 14],
[15, 16, 17]]])
indices = tensor([[0],
[1],
[0]])
# Shape of result is (n, l)
result = tensor([[ 0, 1, 2], # a[0, 0, :] since indices[0] == 0
[ 9, 10, 11], # a[1, 1, :] since indices[1] == 1
[12, 13, 14]]) # a[2, 0, :] since indices[2] == 0
这确实类似于
a.gather(1, indices)
,但是
gather
将无法工作,因为
indices
与
a
的形状不同.我如何使用
gather
在这种情况下?或者我应该用什么?
最佳答案
您可以手动创建索引。 indices
如果张量具有示例数据的形状,则必须将其展平。
a[torch.arange(len(a)),indices.view(-1)]
# equal to a[[0,1,2],[0,1,0]]
出去:
tensor([[ 0, 1, 2],
[ 9, 10, 11],
[12, 13, 14]])
关于python - torch 聚中维,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65378968/
我是一名优秀的程序员,十分优秀!