【问题标题】:Indexing a Keras Tensor索引 Keras 张量
【发布时间】:2018-06-02 02:41:03
【问题描述】:

我的 Keras 函数模型的输出层是一个张量 x,维度为 (None, 1344, 2)。我希望从x 的第二维中提取n < 1344 条目并创建一个大小为(None, n, 2) 的新张量y

通过简单地访问x[:, :n,:] 来提取n 连续条目似乎很简单,但如果n 索引不连续,则(似乎)很困难。 Keras 有干净的方法吗?

这是我目前的方法。

实验 1(切片张量、连续索引、工作):

print('My tensor shape is', K.int_shape(x)) #my tensor 
(None, 1344, 2) # as printed in my code
print('Slicing first 5 entries, shape is', K.int_shape(x[:, :5, :]))
(None, 5, 2) # as printed in my code, works!

实验 2(在任意索引处索引张量,失败)

print('My tensor shape is', K.int_shape(x)) #my tensor 
(None, 1344, 2) # as printed in my code
foo = np.array([1,2,4,5,8])
print('arbitrary indexing, shape is', K.int_shape(x[:,foo,:]))

Keras 返回以下错误:

ValueError: Shapes must be equal rank, but are 1 and 0
From merging shape 1 with other shapes. for 'strided_slice_17/stack_1' (op: 
'Pack') with input shapes: [], [5], [].

实验3(张量流后端函数) 我也尝试过K.backend.gather,但它的用法尚不清楚,因为 1) Keras 文档指出索引应该是整数张量,如果我的目标是提取 x 中的条目满足某些条件和 2) K.backend.gather 似乎从 axis = 0 中提取条目,而我想从 x 的第二维中提取条目。

【问题讨论】:

    标签: python tensorflow keras keras-layer


    【解决方案1】:

    您正在寻找tf.gather_nd,它将基于索引数组进行索引:

    # From documentation
    indices = [[0, 0], [1, 1]]
    params = [['a', 'b'], ['c', 'd']]
    output = ['a', 'd']
    

    要在 Keras 模型中使用它,请确保将其包装在像 Lambda 这样的层中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-13
      • 1970-01-01
      • 2021-03-11
      • 2020-03-28
      • 2019-11-26
      • 1970-01-01
      • 1970-01-01
      • 2019-09-15
      相关资源
      最近更新 更多