0
0
ML Pythonml~5 mins

Saving and loading models in ML Python

Choose your learning style9 modes available
Introduction

Saving a model lets you keep it after training so you can use it later without retraining. Loading a model lets you bring it back to use or improve it.

You trained a model on your computer and want to use it later without retraining.
You want to share your trained model with a friend or colleague.
You want to deploy your model in an app or website.
You want to pause training and continue later from where you left off.
You want to test your model on new data without retraining.
Syntax
ML Python
model.save('filename.h5')

from tensorflow.keras.models import load_model
model = load_model('filename.h5')

Use save to save the whole model including architecture and weights.

Use load_model to load the saved model back into your program.

Examples
Saves the model to a file named my_model.h5.
ML Python
model.save('my_model.h5')
Loads the saved model from the file my_model.h5.
ML Python
from tensorflow.keras.models import load_model
model = load_model('my_model.h5')
Saves and loads only the model weights, not the architecture.
ML Python
model.save_weights('weights.h5')
model.load_weights('weights.h5')
Sample Model

This code trains a simple model on dummy data, saves it, loads it back, and makes predictions to show it works the same.

ML Python
import numpy as np
from tensorflow.keras.models import Sequential, load_model
from tensorflow.keras.layers import Dense

# Create simple model
model = Sequential([Dense(5, activation='relu', input_shape=(3,)), Dense(1, activation='sigmoid')])
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

# Dummy data
X = np.array([[0,0,0],[1,1,1],[0,1,0],[1,0,1]])
y = np.array([0,1,0,1])

# Train model
model.fit(X, y, epochs=3, verbose=0)

# Save model
model.save('test_model.h5')

# Load model
loaded_model = load_model('test_model.h5')

# Predict with loaded model
predictions = loaded_model.predict(X)

# Print predictions rounded
print([round(float(p[0]), 2) for p in predictions])
OutputSuccess
Important Notes

Always save your model after training to avoid losing work.

Loading a model restores its architecture, weights, and optimizer state.

File extensions like .h5 are common for saved models but can vary.

Summary

Saving models lets you keep and reuse trained models without retraining.

Loading models brings saved models back into your program for predictions or further training.

Use model.save() and load_model() for easy saving and loading.