How do I get the weights of a layer in Keras?

If you want to get weights and biases of all layers, you can simply use:

for layer in model.layers: print(layer.get_config(), layer.get_weights())

This will print all information that’s relevant.

If you want the weights directly returned as numpy arrays, you can use:

first_layer_weights = model.layers[0].get_weights()[0]
first_layer_biases  = model.layers[0].get_weights()[1]
second_layer_weights = model.layers[1].get_weights()[0]
second_layer_biases  = model.layers[1].get_weights()[1]

etc.

Leave a Comment