This code trains a simple model, saves only its weights, then creates a new model with the same structure and loads the saved weights. Finally, it evaluates the new model to show the weights were loaded correctly.
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}')