h2oai / h2o-3

H2O is an Open Source, Distributed, Fast & Scalable Machine Learning Platform: Deep Learning, Gradient Boosting (GBM) & XGBoost, Random Forest, Generalized Linear Modeling (GLM with Elastic Net), K-Means, PCA, Generalized Additive Models (GAM), RuleFit, Support Vector Machine (SVM), Stacked Ensembles, Automatic Machine Learning (AutoML), etc.
http://h2o.ai
Apache License 2.0
6.87k stars 1.99k forks source link

Fix plotting in explain: FigureCanvasAgg is non-interactive, and thus cannot be shown plt.show() #16274

Closed tomasfryda closed 4 months ago

tomasfryda commented 4 months ago

There is a bug in our matplotlib wrapper. Workaround is to use the following code right after h2o import (before plotting anything):

def get_matplotlib_pyplot(server, raise_if_not_available=False):
    try:
        # noinspection PyUnresolvedReferences
        import matplotlib
        if server:
            matplotlib.use("Agg")
        try:
            # noinspection PyUnresolvedReferences
            import matplotlib.pyplot as plt
        except ImportError as e:
            if server:
                raise e
            import warnings
            # Possibly failed due to missing tkinter in old matplotlib in python 2.7
            warnings.warn(
                "An error occurred while importing matplotlib with backend \"{}\". Trying again with Agg backend."
                    .format(matplotlib.get_backend()))
            plt = get_matplotlib_pyplot(True, raise_if_not_available)
        return plt
    except ImportError as e:
        if raise_if_not_available:
            raise e
        print("`matplotlib` library is required for this function!")
        return None

h2o.plot._matplotlib.get_matplotlib_pyplot = get_matplotlib_pyplot
h2o.plot.get_matplotlib_pyplot = get_matplotlib_pyplot
h2o.explanation._explain.get_matplotlib_pyplot = get_matplotlib_pyplot