votes up 5

'estimator' must be a fitted regressor or classifier.

Package:
Exception Class:
ValueError

Raise code

""" from sklearn.ensemble import GradientBoostingClassifier
    >>> gb = GradientBoostingClassifier(random_state=0).fit(X, y)
    >>> partial_dependence(gb, features=[0], X=X, percentiles=(0, 1),
    ...                    grid_resolution=2) # doctest: +SKIP
    (array([[-4.52...,  4.52...]]), [array([ 0.,  1.])])
    """
    if not (is_classifier(estimator) or is_regressor(estimator)):
        raise ValueError(
            "'estimator' must be a fitted regressor or classifier."
        )

    if isinstance(estimator, Pipeline):
        # TODO: to be removed if/when pipeline get a `steps_` attributes
        # assuming Pipeline is the only estimator that does not store a new
        # attribute
        
😲 Agile task management is now easier than calling a taxi. #Tracklify

Ways to fix

votes up 1 votes down

Summary: This exception occurs when the function partial_dependence is called and the first value passed as a parameter is not a classifier or regressor. If the value passed is anything else, then this exception occurs.

A useful classifier object that can be used in this case is GradientBoostingClassifier imported from sklearn.ensemble.

Code to Reproduce the Error (WRONG):

from sklearn.inspection._partial_dependence import partial_dependence
X = [[0, 0, 2], [1, 0, 0]]
y = [0, 1]
classifier = None # Leads to Exception
partial_dependence(classifier, features=[0], X=X, percentiles=(0, 1),grid_resolution=2)

Error Output:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-51-0ea94c5b783b> in <module>()
      4 from sklearn.ensemble import GradientBoostingClassifier
      5 gb = GradientBoostingClassifier(random_state=0).fit(X, y)
----> 6 partial_dependence(None, features=[0], X=X, percentiles=(0, 1),grid_resolution=2) # doctest: +SKIP

/usr/local/lib/python3.7/dist-packages/sklearn/inspection/_partial_dependence.py in partial_dependence(estimator, X, features, response_method, percentiles, grid_resolution, method)
    305     if not (is_classifier(estimator) or is_regressor(estimator)):
    306         raise ValueError(
--> 307             "'estimator' must be a fitted regressor or classifier."
    308         )
    309 

ValueError: 'estimator' must be a fitted regressor or classifier.

Working Version (Fixed):

from sklearn.inspection._partial_dependence import partial_dependence
from sklearn.ensemble import GradientBoostingClassifier
X = [[0, 0, 2], [1, 0, 0]]
y = [0, 1]
classifier = GradientBoostingClassifier(random_state=0).fit(X, y)
partial_dependence(classifier, features=[0], X=X, percentiles=(0, 1),grid_resolution=2)


Successful Output:

(array([[-4.39701555,  4.39701555]]), [array([0., 1.])])
Jul 10, 2021 codingcomedyig answer

Add a possible fix

Please authorize to post fix