import tensorflow as tf
from tensorflow.keras import layers, models
# Define the model architecture
model = models.Sequential([
layers.Dense(64, activation='relu', input_shape=(20,)),
layers.Dense(10, activation='softmax')
])
# Compile the model
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
# Generate dummy data for training and validation
import numpy as np
X_train = np.random.random((1000, 20))
y_train = np.random.randint(0, 10, 1000)
X_val = np.random.random((200, 20))
y_val = np.random.randint(0, 10, 200)
# Train the model
model.fit(X_train, y_train, epochs=5, batch_size=32, validation_data=(X_val, y_val))
# Save only the weights
weights_file = 'model_weights.weights.h5'
model.save_weights(weights_file)
# Create a new model instance with the same architecture
new_model = models.Sequential([
layers.Dense(64, activation='relu', input_shape=(20,)),
layers.Dense(10, activation='softmax')
])
# Compile the new model
new_model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
# Load the saved weights into the new model
new_model.load_weights(weights_file)
# Evaluate the new model on validation data
loss, accuracy = new_model.evaluate(X_val, y_val, verbose=0)
print(f'Validation accuracy after loading weights: {accuracy * 100:.2f}%')