0
0
ML Pythonml~5 mins

Model versioning in ML Python

Choose your learning style9 modes available
Introduction
Model versioning helps keep track of different versions of a machine learning model so you can compare, update, or go back to earlier versions easily.
When you improve your model and want to save the new version without losing the old one.
When you want to test different model settings and compare their results.
When you deploy a model and need to update it later without breaking the system.
When working in a team so everyone knows which model version is being used.
When you want to reproduce past results exactly by using the same model version.
Syntax
ML Python
Save model: model.save('model_v1.h5')
Load model: model = keras.models.load_model('model_v1.h5')
Model files can be named with version numbers or dates to keep track.
Use clear and consistent naming to avoid confusion.
Examples
Save the first version of the model to a file named 'model_v1.h5'.
ML Python
model.save('model_v1.h5')
Save an improved model as version 2.
ML Python
model.save('model_v2.h5')
Load the first version of the model to use or test it.
ML Python
model = keras.models.load_model('model_v1.h5')
Sample Model
This code trains a simple model twice, saving two versions. Then it loads each version and shows their accuracy to compare.
ML Python
import tensorflow as tf
from tensorflow import keras

# Create a simple model
model = keras.Sequential([
    keras.layers.Dense(10, activation='relu', input_shape=(5,)),
    keras.layers.Dense(1, activation='sigmoid')
])

model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

# Dummy data
import numpy as np
X = np.random.random((100, 5))
y = np.random.randint(2, size=(100, 1))

# Train model version 1
model.fit(X, y, epochs=2, verbose=0)

# Save version 1
model.save('model_v1.h5')

# Train more for version 2
model.fit(X, y, epochs=2, verbose=0)

# Save version 2
model.save('model_v2.h5')

# Load version 1 and evaluate
model_v1 = keras.models.load_model('model_v1.h5')
loss1, acc1 = model_v1.evaluate(X, y, verbose=0)

# Load version 2 and evaluate
model_v2 = keras.models.load_model('model_v2.h5')
loss2, acc2 = model_v2.evaluate(X, y, verbose=0)

print(f"Version 1 accuracy: {acc1:.4f}")
print(f"Version 2 accuracy: {acc2:.4f}")
OutputSuccess
Important Notes
Always save your model after training to keep a record of that version.
Use version numbers or timestamps in filenames to organize models clearly.
Loading an older model version lets you reproduce past results exactly.
Summary
Model versioning means saving different copies of your model as you improve it.
It helps you compare, update, and reproduce models easily.
Use clear file names and save models regularly during development.