Saving and Loading a TensorFlow Model
Introduction
Welcome to this next lesson on Saving and Loading a TensorFlow Model. By the end of this lesson, you’ll be able to understand the importance of saving and loading models, how to save a trained TensorFlow model, load it from the saved file format, and validate the loaded model. This will give you a full cycle understanding and hands-on knowledge on how to handle models when training is done. With the provided code examples that train, save, load, and test a model, let's start our lesson!
The Importance of Saving and Loading Models
When building machine learning models, it's important to save your models for various reasons. The most obvious one is efficiency - once you trained an intricate model that could take hours or even days to train, you want to keep the learned weights to avoid re-training. So, you’d save the model for reuse later without the need to retrain.
Not only that, but the saved model can be shared with others - if you're collaborating with other professionals or even publishing your results, it aids in reproducibility of your results by others. Finally, when deploying a model to production you'll need to load the trained model to make predictions on new data.
In the previous lessons, we trained a TensorFlow model. Now, let's save it!
Quick Refresh: Loading Data and Training the Model
Before we focus on saving our model, let's briefly revisit the key steps we took to load our data and train the model. Here's the code snippet we used to preprocess the Iris dataset:
And to train a model with our preprocessed data:
In summary:
- We began by loading the preprocessed data using the
load_preprocessed_data()function from ourdata_preprocessing.pyfile to get our datasets:X_train,X_test,y_train, andy_test. - We constructed a sequential model with TensorFlow's Keras API, with the input shape tailored to our dataset, including several dense layers with ReLU and Softmax activations.
- The model was then compiled using the Adam optimizer and the categorical crossentropy loss function, with accuracy as a metric.
- Finally, we trained the model for 150 epochs with a batch size of 5, validating its performance on the test data throughout the training process.
With our training steps revisited, let's move on to saving our well-trained model.
