微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在张量流中对张量进行子集化?

如何解决如何在张量流中对张量进行子集化?

我已经使用 Keras 和 TensorFlow 后端训练了一个 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,10]

解决方法

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

indexes = [[0,c]]
subset  = gather_nd(MyTensor,indexes,0)

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。