【问题标题】:Indexing k-th dimension of tensor with another tensor in Tensorflow 2.0在 Tensorflow 2.0 中用另一个张量索引张量的第 k 维
【发布时间】:2020-09-23 06:05:04
【问题描述】:

我有一个张量probs,其形状为(None, None, 110),代表LSTM 中的(batch_size, sequence_length, 110)。 我有另一个张量indices,其形状为(None, None),其中包含要从probs 的第三维中选择的元素的索引。

我想使用indices 来索引张量probs

Numpy 等价物:

k, j = np.meshgrid(np.arange(probs.shape[1]), np.arange(probs.shape[0]))
indexed_probs = probs[j, k, indices]

由于probs 中的shape[0]shape[1] 未知,因此tf.meshgrid() 不是一个选项。 我找到了tf.gathertf.gather_ndtf.batch_gather,但它们似乎都没有按照我的意愿行事。

有人知道怎么做吗?

【问题讨论】:

    标签: python numpy tensorflow indexing tensorflow2.0


    【解决方案1】:

    您可以像这样使用tf.gather_nd 做到这一点:

    indexed_probs = tf.gather_nd(probs, tf.expand_dims(indices, axis=-1), batch_dims=2)
    

    顺便说一句,在 NumPy 中你可以使用 np.take_along_axis 来做同样的事情:

    indexed_probs = np.take_along_axis(probs, np.expand_dims(indices, axis=-1), axis=-1)[..., 0]
    

    【讨论】:

    • 您是否也知道如何在 Keras 中执行此操作?显然 tf.keras.backend.gather_nd() 还不存在...
    • 好吧,我发现了。 :) 您可以在 keras 模型中添加任何 tensorflow 操作作为 Lambda 层,如下所示: indexed_probs = tf.keras.layers.Lambda(lambda probs_and_indices: tf.gather_nd(probs_and_indices[0], probs_and_indices[1], batch_dims=2 ), name='gather')([probs, indices])
    猜你喜欢
    • 2018-03-03
    • 2016-06-20
    • 2020-10-26
    • 1970-01-01
    • 2021-01-22
    • 1970-01-01
    • 1970-01-01
    • 2018-08-23
    • 1970-01-01
    相关资源
    最近更新 更多