上QQ阅读APP看书,第一时间看更新
How to do it…
Let's see how to achieve model persistence in Python:
- Add the following lines to the regressor.py file:
import pickle
output_model_file = "3_model_linear_regr.pkl"
with open(output_model_file, 'wb') as f:
pickle.dump(linear_regressor, f)
- The regressor object will be saved in the saved_model.pkl file. Let's look at how to load it and use it, as follows:
with open(output_model_file, 'rb') as f:
model_linregr = pickle.load(f)
y_test_pred_new = model_linregr.predict(X_test)
print("New mean absolute error =", round(sm.mean_absolute_error(y_test, y_test_pred_new), 2))
The following result is returned:
New mean absolute error = 241907.27
Here, we just loaded the regressor from the file into the model_linregr variable. You can compare the preceding result with the earlier result to confirm that it's the same.