Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keras - get weight of trained layer

I'm trying to get the values of a layer in a trained network. I can get the layer as a TensorFlow Tensor, but I'm unable to access its values in an array shape:

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 ??
like image 782
Guig Avatar asked May 09 '17 07:05

Guig


2 Answers

.get_weights() will return the weights of a specific layer or model as a numpy array

layer_dict[layer_name].get_weights()

If you want the output of the layer, check the answers on the question here.

like image 110
Wilmar van Ommeren Avatar answered Sep 22 '22 12:09

Wilmar van Ommeren


If you use the tensorflow backend, you can evaluate the value of a tensor using the current session sess and feeding the correct input

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})

If you just want to retrieve the weights, you can evaluate the weights of a layers using:

weights = [w.eval(K.get_session) for w in layer_dict['model_1'][layer_name].weights]
like image 44
Thomas Moreau Avatar answered Sep 21 '22 12:09

Thomas Moreau