Skip to content

Instantly share code, notes, and snippets.

@paulphys
Last active December 11, 2019 00:15
Show Gist options
  • Save paulphys/f6f034b40ce58ecb00ba6693ec568a15 to your computer and use it in GitHub Desktop.
Save paulphys/f6f034b40ce58ecb00ba6693ec568a15 to your computer and use it in GitHub Desktop.
Code Snippets for saving and loading different machine learning models
#Keras Models
#---Save---#
json_file = model.to_json()
with open(json_file_path, "w") as file:
file.write(json_file)
model.save_weights(h5_file)
#---Load---#
from keras.models import model_from_json
file = open(json_file, 'r')
model_json = file.read()
file.close()
loaded_model = model_from_json(model_json)
loaded_model.load_weights(h5_file)
#Scikit-Learn Models
#---Save---#
from sklearn.linear_model import LogisticRegression
import pickle
model = LogisticRegression()
model.fit(xtrain, ytrain)
pickle.dump(model, open(model_file_path, 'wb'))
#---Load---#
model = pickle.load(open(model_file_path, 'rb'))
result_val = model.score(xval, yval)
result_test = model.score(xtest, ytest)
#StatsModel Models
#---Save---#
import statsmodels.api as sm
model = sm.tsa.ARIMA([1,5,9,12], order=(1, 0, 1))
my_model= model.fit()
my_model.save(myfile)
#---Load---#
from statsmodels.tsa.arima_model import ARIMAResults
loaded = ARIMAResults.load(my_file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment