栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python-Keras,如何获得每一层的输出?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python-Keras,如何获得每一层的输出?

你可以使用以下命令轻松获取任何图层的输出:

model.layers[index].output

对于所有图层,请使用以下命令:

from keras import backend as Kinp = model.input          # input placeholderoutputs = [layer.output for layer in model.layers]          # all layer outputsfunctors = [K.function([inp, K.learning_phase()], [out]) for out in outputs]    # evaluation functions# Testingtest = np.random.random(input_shape)[np.newaxis,...]layer_outs = [func([test, 1.]) for func in functors]print layer_outs

注:为了模拟差使用learning_phase如1.在layer_outs以其它方式使用0.

编辑:(基于评论)

K.function
创建
theano / tensorflow
张量函数,该函数随后用于从给定输入的符号图中获取输出。

现在

K.learning_phase()
需要输入作为输入,因为许多Keras层(如
Dropout / Batchnomalization
)都依赖它来在训练和测试期间更改行为。

因此,如果你删除代码中的辍学层,则可以简单地使用:

from keras import backend as Kinp = model.input          # input placeholderoutputs = [layer.output for layer in model.layers]          # all layer outputsfunctors = [K.function([inp], [out]) for out in outputs]    # evaluation functions# Testingtest = np.random.random(input_shape)[np.newaxis,...]layer_outs = [func([test]) for func in functors]print layer_outs

编辑2:更优化

我刚刚意识到,先前的答案并不是针对每个函数评估进行优化的,因为数据将被传输到CPU-> GPU内存中,并且还需要对低层进行n-n-over的张量计算。

相反,这是一种更好的方法,因为你不需要多个函数,而只需一个函数即可为你提供所有输出的列表:

from keras import backend as Kinp = model.input          # input placeholderoutputs = [layer.output for layer in model.layers]          # all layer outputsfunctor = K.function([inp, K.learning_phase()], outputs )   # evaluation function# Testingtest = np.random.random(input_shape)[np.newaxis,...]layer_outs = functor([test, 1.])print layer_outs


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/456399.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号