【问题标题】:How to subset a tensor in tensorflow?如何在张量流中对张量进行子集化?
【发布时间】:2021-07-08 04:20:16
【问题描述】:

我已经使用带有 TensorFlow 后端的 Keras 训练了一个 CNN 模型。 训练模型后。我正在尝试获取第 n 层输出的子集。 我可以使用以下方法访问第 n 层输出:

Model.layers[n].output 

这是

<tf.Tensor 'dense_2_1/Identity:0' shape=(None, 64) dtype=float32>

我可以通过这样的命令得到它的子集连续范围:

Model.layers[n].output[...,1:5]

现在,我正在尝试对张量进行子集化,仅考虑 64 个索引中的几个(例如 1、5、10)

任何想法我该怎么做?

这是参考代码:

n                   = 15   
sub_indexes         = [1,5,10]
final_fmap_index    = 10
penultimate_output  = Model.layers[final_fmap_index].output
layer_input         = Model.input
loss                = Model.layers[n].output[...,sub_indexes]
grad_wrt_fmap       = K.gradients(loss,penultimate_output)[0]
grad_wrt_fmap_fn    = K.function([layer_input,K.learning_phase()],
                                      [penultimate_output,grad_wrt_fmap])

这给了我这个错误:

TypeError: Only integers, slices (`:`), ellipsis (`...`), tf.newaxis (`None`) and scalar tf.int32/tf.int64 tensors are valid indices, got [1, 5, 10]

【问题讨论】:

标签: python tensorflow keras tensor slide


【解决方案1】:

使用gather_nd() 我可以获得张量的子集。 基本上为某些索引 [a,b,c] 子集张量 它需要采用 [[0,a],[1,b],[2,c]] 格式 然后使用gather_nd() 获取子集。

indexes = [[0,a],[1,b],[2,c]]
subset  = gather_nd(MyTensor, indexes, 0)

更多关于函数https://www.tensorflow.org/api_docs/python/tf/gather_nd的细节

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-10
    相关资源
    最近更新 更多