Examine learned weights
Inspecting parameters
Keras · Module
Model.get_weights() retrieves a model's current weights as a flat list of NumPy arrays. It is useful for inspecting or transferring weight values in memory.
model.get_weights() reads the model's tracked weights and returns their current values as a flat list of NumPy arrays. The arrays correspond to the model's weights in Keras' established weight ordering and can be inspected or transferred to another compatible object.
Model.get_weights()A flat list of NumPy arrays containing the model's weight values.
set_weights() to copy in-memory weight values between compatible Keras objects.import numpy as np
import keras
model = keras.Sequential([
keras.layers.Dense(3, input_shape=(2,)),
keras.layers.Dense(1),
])
weights = model.get_weights()
print(len(weights))
print([w.shape for w in weights])Creates a model, retrieves its weights as NumPy arrays, and prints the number and shape of each array.
Inspecting parameters
In-memory transfer
Debugging initialization
Model.get_weights() return?It returns the current values of the model's weights as a flat list of NumPy arrays. The list is suitable for inspecting or transferring model state in memory.
Follow-up: How would you restore those values? Use set_weights(weights) on a compatible model or layer, with matching weight structure and shapes.
get_weights() differ from accessing weights?The method returns values rather than variable objects. Consequently, the result is convenient for NumPy-based inspection and for passing weight values to a compatible Keras object.
Follow-up: What distinction matters when inspecting variables directly? Layer properties such as weights expose weight variables, while get_weights() returns their values as NumPy arrays.
get_weights() instead of saving weights?Call it after the model has been built when you need the model's initialized or learned parameters. The returned arrays represent the model's current state at the time of the call.
Follow-up: How can the values be persisted? Use the documented weights-only saving APIs when storage on disk is required rather than keeping arrays only in memory.
Model.set_weightsLayer.get_weightsLayer.set_weightsModel.save_weightsModel.load_weights