Keras - 获得训练层的重量

时间:2017-05-09 07:10:03

标签: python tensorflow neural-network keras keras-layer

我试图在训练有素的网络中获取图层的值。我可以将图层作为TensorFlow Tensor获取,但我无法以数组形状访问其值:

from keras.models import load_model

model = load_model('./model.h5')
layer_dict = dict([(layer.name, layer) for layer in model.layers])

layer_name = 'block5_sepconv1_act'
filter_index = 0

layer_output = layer_dict['model_1'][layer_name].output
# <tf.Tensor 'block5_sepconv1_act/Relu:0' shape=(?, 16, 16, 728) dtype=float32>
layer_filter = layer_output[:, :, :, filter_index]
# <tf.Tensor 'strided_slice_11:0' shape=(?, 16, 16) dtype=float32>
# how do I get the 16x16 values ??

2 个答案:

答案 0 :(得分:3)

.get_weights()会将特定图层或模型的权重作为numpy数组返回

layer_dict[layer_name].get_weights()

如果您想要图层的输出,请检查问题here上的答案。

答案 1 :(得分:1)

如果您使用tensorflow后端,则可以使用当前会话sess评估张量值并输入正确的输入

import keras.backend as K

input_value = np.zeros(size=(batch_size, input_dim))
sess = K.get_session()
output = sess.run(layer_output, feed_dict={model.input: input_value})

如果您只想检索权重,可以使用以下方法评估图层的权重:

weights = [w.eval(K.get_session) for w in layer_dict['model_1'][layer_name].weights]