Example of how to save in a file with joblib a model developed with scikit learn in python:
Generate random numbers
from sklearn import linear_model
from pylab import figure
import matplotlib.pyplot as plt
import numpy as np
x = np.random.uniform(0,8,100)
sigma = np.random.randn(100) * 4.1
y = 4.0 * x + 2.0 + sigma
fig = figure(num=None, figsize=(12, 10), dpi=80, facecolor='w', edgecolor='k')
plt.scatter(x,y)
plt.title(r'Linear regression with scikit learn in python')
plt.xlabel('x')
plt.ylabel('y')
plt.xlim(0,8)
plt.savefig("linear_regression_01.png", bbox_inches='tight')
Train a model
reg = linear_model.LinearRegression()
x = x[:, np.newaxis]
y = y[:, np.newaxis]
reg.fit(x,y)
xp = np.arange(0,8,0.2)
xp = xp[:, np.newaxis]
yp = reg.predict(xp)
plt.plot(xp,yp, color='coral')
plt.title(r'Linear regression with scikit learn in python')
plt.xlabel('x')
plt.ylabel('y')
plt.xlim(0,8)
plt.savefig("linear_regression_02.png", bbox_inches='tight')
plt.show()
Save the model in a file
from joblib import dump, load
dump(reg, 'regression_model_saved.joblib')
Load the model from the file
reg_loaded = load('regression_model_saved.joblib')
xp = np.arange(0,8,0.2)
xp = xp[:, np.newaxis]
yp = reg_loaded.predict(xp)
plt.scatter(x,y)
plt.plot(xp,yp, color='coral')
plt.title(r'Linear regression with scikit learn in python')
plt.xlabel('x')
plt.ylabel('y')
plt.xlim(0,8)
plt.show()
Save multiple models in a same file
Create two models
fig = figure(num=None, figsize=(12, 10), dpi=80, facecolor='w', edgecolor='k')
x = np.random.uniform(0,8,100)
sigma = np.random.randn(100) * 4.1
y = 4.0 * x + 2.0 + sigma
plt.scatter(x,y, color='coral')
reg = linear_model.LinearRegression()
x = x[:, np.newaxis]
y = y[:, np.newaxis]
reg1 = reg.fit(x,y)
x = np.random.uniform(0,8,100)
sigma = np.random.randn(100) * 4.1
plt.plot(xp,reg1.predict(xp), color='coral')
y = 6.0 * x - 2.0 + sigma
x = x[:, np.newaxis]
y = y[:, np.newaxis]
reg = linear_model.LinearRegression()
reg2 = reg.fit(x,y)
xp = np.arange(0,8,0.2)
xp = xp[:, np.newaxis]
plt.scatter(x,y, color='lightblue')
plt.plot(xp,reg2.predict(xp), color='lightblue')
plt.title(r'Linear regression with scikit learn in python')
plt.xlabel('x')
plt.ylabel('y')
plt.xlim(0,8)
plt.savefig("linear_regression_03.png", bbox_inches='tight')
plt.show()
Save the two models in a file:
dump([reg1, reg2], 'regression_model_saved.joblib', compress=1)
Use loaded models
reg1_loaded, reg2_loaded = load('regression_model_saved.joblib')
xp = np.arange(0,8,0.2)
xp = xp[:, np.newaxis]
plt.plot(xp,reg1_loaded.predict(xp), color='coral')
plt.plot(xp,reg2_loaded.predict(xp), color='lightblue')
plt.title(r'Linear regression with scikit learn in python')
plt.xlabel('x')
plt.ylabel('y')
plt.xlim(0,8)
plt.show()