In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
LinearRegression()
Although this particular model completed its training fairly quickly, it is normal for some more complicated models to take hours, days, or even weeks or months to train.
Once the training script has completed (or the training notebook has restarted its session), we unfortunately lose access to the trained model. And we would need to re-train the model to make more predictions.
To save time and avoid re-training the model each time we need to make predictions, we can train it once, and save the trained model with its learned weights. Then anytime we want to use the model again, we can load it from its saved state.
Saving Trained Models
To save and load models, we can use the pickle module, or the joblib package (preferred):
import osimport joblib# creating a directory to store the model:MODEL_DIRNAME ="grades-linear-regression"os.makedirs(MODEL_DIRNAME, exist_ok=True)# creating a filepath for the model in that directory:MODEL_FILEPATH = os.path.join(MODEL_DIRNAME, "model.joblib")# saving the model to the given filepath:joblib.dump(model, MODEL_FILEPATH)
['grades-linear-regression/model.joblib']
Model Naming Conventions
When using the joblib library and related tools to save and load models, it is a convention to call the saved model file “model.joblib” specifically. So to differentiate between models, this is why we customize the name of the directory where the model file is stored (in this case “grades-linear-regression”).
Loading Pre-trained Models
Once we have saved a pre-trained model to a given filepath, we can load it from file:
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
LinearRegression()
This model is the same as the one we previously trained, so we can use it to make predictions: