Created
September 28, 2018 09:37
-
-
Save jlopezpena/2cdd09c56afda5964990d5cf278bfd31 to your computer and use it in GitHub Desktop.
Barebones JSON serialization for simple (non-nested) sklearn models
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pandas.io import json | |
import numpy as np | |
def model_to_dict(model): | |
attrs = model.__dict__ | |
init_attrs = {key: val for key, val in attrs.items() if not key.endswith("_")} | |
fitted_attrs = {key: val for key, val in attrs.items() if key.endswith("_")} | |
name = model.__class__.__name__ | |
module = model.__module__ | |
return {'modelType': name, | |
'loadFrom': module, | |
'initParameters': init_attrs, | |
'fittedParameters': fitted_attrs} | |
def model_to_json(model): | |
return json.dumps(model_to_dict(model)) | |
def model_from_dict(model_desc): | |
mod = __import__(model_desc['loadFrom'], | |
fromlist=[model_desc['modelType']]) | |
Clf = getattr(mod, model_desc['modelType']) | |
clf = Clf(**model_desc['initParameters']) | |
for key, val in model_desc['fittedParameters'].items(): | |
if isinstance(val, list): | |
setattr(clf, key, np.array(val)) | |
else: | |
setattr(clf, key, val) | |
return clf | |
def model_from_json(json_str): | |
return model_from_dict(json.loads(json_str)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is some very hackish code I wrote to test the feasibility of providing JSON serialization for fitted sklearn models.
It doesn't always work, and it uses some questionable code practices like the manual call to
__import__
; needlessto say this should be kept away from any production environments!