Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[NotForMerging]Add mlflow loader for glassbox models #123

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions python/interpret-core/dev-requirements.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
# Required dependencies
.[required,debug,notebook,plotly,lime,sensitivity,shap,ebm,linear,decisiontree,treeinterpreter,dash,skoperules,testing]
mlflow
1 change: 1 addition & 0 deletions python/interpret-core/interpret/glassbox/mlflow/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
mlruns
76 changes: 76 additions & 0 deletions python/interpret-core/interpret/glassbox/mlflow/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import json
import os
import yaml

from tempfile import TemporaryDirectory

import interpret


def load_model(*args, **kwargs):
import mlflow.pyfunc
return mlflow.pyfunc.load_model(*args, **kwargs)


def _sanitize_explanation_data(data): # TODO Explanations should have a to_json()
if isinstance(data, dict):
for key, val in data.items():
data[key] = _sanitize_explanation_data(data[key])
return data

elif isinstance(data, list):
return [_sanitize_explanation_data[x] for x in data]
else:
# numpy type conversion to python https://stackoverflow.com/questions/9452775 primitive
return data.item() if hasattr(data, "item") else data


def _load_pyfunc(path):
import cloudpickle as pickle
with open(os.path.join(path, "model.pkl"), "rb") as f:
return pickle.load(f)


def _save_model(model, output_path):
import cloudpickle as pickle
if not os.path.exists(output_path):
os.mkdir(output_path)
with open(os.path.join(output_path, "model.pkl"), "wb") as stream:
pickle.dump(model, stream)
try:
with open(os.path.join(output_path, "global_explanation.json"), "w") as stream:
data = model.explain_global().data(-1)["mli"]
if isinstance(data, list):
data = data[0]
if "global" not in data["explanation_type"]:
raise Exception("Invalid explanation, not global")
for key in data:
if isinstance(data[key], list):
data[key] = [float(x) for x in data[key]]
json.dump(data, stream)
except ValueError as e:
raise Exception("Unsupported glassbox model type {}. Failed with error {}.".format(type(model), e))

def log_model(path, model):
try:
import mlflow.pyfunc
except ImportError as e:
raise Exception("Could not log_model to mlflow. Missing mlflow dependency, pip install mlflow to resolve the error: {}.".format(e))
import cloudpickle as pickle

with TemporaryDirectory() as tempdir:
_save_model(model, tempdir)

conda_env = {"name": "mlflow-env",
"channels": ["defaults"],
"dependencies": ["pip",
{"pip": [
"interpret=={}".format(interpret.version.__version__),
"cloudpickle=={}".format(pickle.__version__)]
}
]
}
conda_path = os.path.join(tempdir, "conda.yaml") # TODO Open issue and bug fix for dict support
with open(conda_path, "w") as stream:
yaml.dump(conda_env, stream)
mlflow.pyfunc.log_model(path, loader_module="interpret.glassbox.mlflow", data_path=tempdir, conda_env=conda_path)
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Copyright (c) 2019 Microsoft Corporation
# Distributed under the MIT software license

import json
import os

import pytest

from sklearn.datasets import load_breast_cancer, load_boston
from sklearn.linear_model import LogisticRegression as SKLogistic
from sklearn.linear_model import Lasso as SKLinear

from interpret.glassbox.linear import LogisticRegression, LinearRegression
from interpret.glassbox.mlflow import load_model, log_model


@pytest.fixture()
def glassbox_model():
boston = load_boston()
return LinearRegression(feature_names=boston.feature_names, random_state=1)


@pytest.fixture()
def model():
return SKLinear(random_state=1)


def test_linear_regression_save_load(glassbox_model, model):
boston = load_boston()
X, y = boston.data, boston.target

model.fit(X, y)
glassbox_model.fit(X, y)

save_location = "save_location"
log_model(save_location, glassbox_model)


import mlflow
glassbox_model_loaded = load_model("runs:/{}/{}".format(mlflow.active_run().info.run_id, save_location))

name = "name"
explanation_glassbox_data = glassbox_model.explain_global(name).data(-1)["mli"]
explanation_glassbox_data_loaded = glassbox_model_loaded.explain_global(name).data(-1)["mli"]
assert explanation_glassbox_data == explanation_glassbox_data_loaded