从张量流中的张量中提取特定元素

编程入门 行业动态 更新时间:2024-10-08 06:20:50
本文介绍了从张量流中的张量中提取特定元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我在 python 上使用 tensorflow我有一个形状为 [?, 5, 37] 的数据张量和一个形状为 [?, 5] 的 idx 张量

I'm using tensorflow on python I have a data tensor of shape [?, 5, 37], and a idx tensor of shape [?, 5]

我想从数据中提取元素并获得形状为 [?, 5] 的输出:

I'd like to extract elements from data and get an output of shape [?, 5] such that:

output[i][j] = data[i][j][idx[i, j]] for all i in range(?) and j in range(5)

看起来 tf.gather_nd() 函数最接近我的需要,但我不知道如何使用它...

It looks loke the tf.gather_nd() function is the closest to my needs, but I don't see how to use it it my case...

谢谢!

我设法用gather_nd做到了,如下所示,但有更好的选择吗?(好像有点霸道)

EDIT : I managed to do it with gather_nd as shown below, but is there a better option ? (it seems a bit heavy-handed)

    nRows = tf.shape(length_label)[0] ==> ?
    nCols = tf.constant(MAX_LENGTH_INPUT + 1, dtype=tf.int32) ==> 5
    m1 = tf.reshape(tf.tile(tf.range(nCols), [nRows]),
                                           shape=[nRows, nCols])
    m2 = tf.transpose(tf.reshape(tf.tile(tf.range(nRows), [nCols]),
                                            shape=[nCols, nRows]))
    indices = tf.pack([m2, m1, idx], axis=-1)
    # indices should be of shape [?, 5, 3] with indices[i,j]==[i,j,idx[i,j]]
    output = tf.gather_nd(data, indices=indices)

推荐答案

我设法用 gather_nd 做到了,如下所示

I managed to do it with gather_nd as shown below

nRows = tf.shape(length_label)[0] # ==> ?
nCols = tf.constant(MAX_LENGTH_INPUT + 1, dtype=tf.int32) # ==> 5
m1 = tf.reshape(tf.tile(tf.range(nCols), [nRows]),
                                       shape=[nRows, nCols])
m2 = tf.transpose(tf.reshape(tf.tile(tf.range(nRows), [nCols]),
                                        shape=[nCols, nRows]))
indices = tf.pack([m2, m1, idx], axis=-1)
# indices should be of shape [?, 5, 3] with indices[i,j]==[i,j,idx[i,j]]
output = tf.gather_nd(data, indices=indices)

这篇关于从张量流中的张量中提取特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

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

发布评论

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

>www.elefans.com

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