从张量流中的张量中提取特定元素 [英] Extracting specific elements from a tensor in tensorflow

查看:68
本文介绍了从张量流中的张量中提取特定元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆