pytorch 等效 tf.gather

编程入门 行业动态 更新时间:2024-10-07 22:26:56
本文介绍了pytorch 等效 tf.gather的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我在将一些代码从 tensorflow 移植到 pytorch 时遇到了一些问题.

I'm having some trouble porting some code over from tensorflow to pytorch.

所以我有一个尺寸为 10x30 的矩阵,代表 10 个示例,每个示例具有 30 个特征.然后我有另一个维度为 10x5 的矩阵,其中包含第一个矩阵中每个示例的 5 个最接近示例的索引.我想使用第二个矩阵中包含的索引收集"第一个矩阵中每个示例的 5 个最接近的示例,留下形状为 10x5x30 的 3d 张量.

So I have a matrix with dimensions 10x30 representing 10 examples each with 30 features. Then I have another matrix with dimensions 10x5 containing indices of the the 5 closest examples for each examples in the first matrix. I want to 'gather' using the indices contained in the second matrix the 5 closet examples for each example in the first matrix leaving me with a 3d tensor of shape 10x5x30.

在 tensorflow 中,这是通过 tf.gather(matrix1, matrix2) 完成的.有谁知道我如何在 pytorch 中做到这一点?

In tensorflow this is done with tf.gather(matrix1, matrix2). Does anyone know how i could do this in pytorch?

推荐答案

这个怎么样?

matrix1 = torch.randn(10, 30)
matrix2 = torch.randint(high=10, size=(10, 5))
gathered = matrix1[matrix2]

它使用了用整数数组进行索引的技巧.

It uses the trick of indexing with an array of integers.

这篇关于pytorch 等效 tf.gather的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-05-01 01:03:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1402415.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:pytorch   tf   gather

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!