Retrieving the weights of a specific layer in Keras can be accomplished through a few straightforward steps. First, ensure you have a trained model. Then, use the model's get_layer() method to access the desired layer, followed by the get_weights() method to retrieve the layer's weights. Here is a specific example:
Assume you have built and trained a simple neural network model named model, and now you want to retrieve the weights of the first hidden layer in this model.
pythonfrom keras.models import Sequential from keras.layers import Dense # Build the model model = Sequential([ Dense(32, input_shape=(10,), activation='relu'), # First hidden layer Dense(1, activation='sigmoid') ]) # Compile the model model.compile(optimizer='sgd', loss='binary_crossentropy') # Assume you have trained the model # Retrieve the weights of a specific layer layer = model.get_layer(index=0) # Or model.get_layer(name='dense') weights = layer.get_weights() # Returns a list where weights[0] is the weight matrix and weights[1] is the bias term
In this example, the get_layer() method specifies the target layer using either its name or index. The get_weights() method returns a list containing the weight matrix and bias term. Additionally, you can examine the weights of different layers to aid in analyzing and understanding the model's operation.