如何在张量流中对张量进行子集化?
Posted
技术标签:
【中文标题】如何在张量流中对张量进行子集化?【英文标题】: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]
【问题讨论】:
这能回答你的问题吗? What is the tensorflow equivalent of numpy tuple/array indexing? @Lescurel 谢谢你的链接,我已经按照那里的说明,弄清楚如何为我的案例获取子集。gather_nd()
做这项工作。我将基于此发布解决方案。
【参考方案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的细节
【讨论】:
以上是关于如何在张量流中对张量进行子集化?的主要内容,如果未能解决你的问题,请参考以下文章