Introduction
Saving weights only lets you keep just the learned parts of a model. This saves space and lets you reuse the model structure later.
model.save_weights('path_to_file') model.load_weights('path_to_file')
model.save_weights('weights.h5') model.load_weights('weights.h5')
model.save_weights('checkpoints/weights') model.load_weights('checkpoints/weights')
import tensorflow as tf # Create a simple model model = tf.keras.Sequential([ tf.keras.layers.Dense(5, activation='relu', input_shape=(3,)), tf.keras.layers.Dense(2, activation='softmax') ]) # Compile the model model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) # Dummy data import numpy as np x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.float32) y = np.array([0, 1, 1], dtype=np.int32) # Train the model model.fit(x, y, epochs=2, verbose=0) # Save weights only model.save_weights('my_weights') # Create a new model with the same architecture new_model = tf.keras.Sequential([ tf.keras.layers.Dense(5, activation='relu', input_shape=(3,)), tf.keras.layers.Dense(2, activation='softmax') ]) # Compile new model new_model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) # Load saved weights new_model.load_weights('my_weights') # Evaluate new model on same data loss, accuracy = new_model.evaluate(x, y, verbose=0) print(f'Loss: {loss:.4f}, Accuracy: {accuracy:.4f}')
model to a file weights.h5?model.save_weights(filepath).model.save_weights('weights.h5') uses correct method and argument format. model.save('weights.h5') saves full model, C is invalid TensorFlow syntax, A uses wrong argument name.import tensorflow as tf
model = tf.keras.Sequential([
tf.keras.layers.Dense(5, input_shape=(3,))
])
model.save_weights('w.h5')
new_model = tf.keras.Sequential([
tf.keras.layers.Dense(5, input_shape=(3,))
])
new_model.load_weights('w.h5')
print(new_model.get_weights()[0].shape)model.save_weights('w.h5'). When loading weights with new_model.load_weights('w.h5'), you get an error about mismatched shapes. What is the most likely cause?model.save_weights() to save only learned parameters without model structure.load_weights().Pass the test and this pattern moves unknown