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.
Saving and loading models in 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.
my_model.h5.model.save('my_model.h5')my_model.h5.from tensorflow.keras.models import load_model model = load_model('my_model.h5')
model.save_weights('weights.h5') model.load_weights('weights.h5')
This code trains a simple model on dummy data, saves it, loads it back, and makes predictions to show it works the same.
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])
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.
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.
Practice
Solution
Step 1: Understand model saving
Saving a model stores its learned parameters so it can be reused later.Step 2: Identify the main benefit
This avoids retraining, saving time and resources.Final Answer:
To reuse the model later without retraining -> Option BQuick Check:
Saving = reuse without retraining [OK]
- Thinking saving improves accuracy automatically
- Confusing saving with speeding up training
- Believing saving deletes data
model to a file called my_model.h5?Solution
Step 1: Recall Keras save syntax
Keras models are saved usingmodel.save(filename).Step 2: Match correct syntax
model.save('my_model.h5') matches this syntax exactly.Final Answer:
model.save('my_model.h5') -> Option AQuick Check:
model.save(filename) saves model [OK]
- Using incorrect function names like save_model or save
- Swapping argument order
- Calling save_model as a method on model
from tensorflow.keras.models import load_model
model = load_model('saved_model.h5')
predictions = model.predict([[5.1, 3.5, 1.4, 0.2]])
print(predictions)Solution
Step 1: Understand load_model usage
load_model loads a saved Keras model from a file.Step 2: Predict method output
model.predict returns a numpy array of prediction probabilities for input data.Final Answer:
A numpy array of prediction probabilities -> Option DQuick Check:
load_model + predict = numpy array output [OK]
- Thinking load_model only loads from directories
- Expecting printed model architecture from predict
- Assuming predict returns class labels directly
load_model('model.h5') but get an error: OSError: Unable to open file (file signature not found). What is the most likely cause?Solution
Step 1: Analyze the error message
OSError about file signature means the file is not recognized as a valid HDF5 model file.Step 2: Identify common causes
This usually happens if the file is corrupted or not a saved model file.Final Answer:
The file 'model.h5' is corrupted or not a valid model file -> Option CQuick Check:
File signature error = corrupted or invalid file [OK]
- Assuming Python version mismatch causes this error
- Forgetting to import but error message differs
- Thinking file size causes signature errors
model_v1.h5. You want to load it, continue training on new data, then save the updated model as model_v2.h5. Which code snippet correctly does this?Solution
Step 1: Load the saved model correctly
Useload_model('model_v1.h5')from tensorflow.keras.models to load the model.Step 2: Continue training and save updated model
Callmodel.fit()with new data, then save withmodel.save('model_v2.h5').Final Answer:
from tensorflow.keras.models import load_model model = load_model('model_v1.h5') model.fit(new_data, new_labels, epochs=5) model.save('model_v2.h5') -> Option AQuick Check:
Load, fit, save = from tensorflow.keras.models import load_model model = load_model('model_v1.h5') model.fit(new_data, new_labels, epochs=5) model.save('model_v2.h5') [OK]
- Using undefined functions like load or save_model
- Forgetting to import load_model
- Not calling fit before saving updated model
Ready to prove it?
Pass the test and this pattern moves unknown
