Prev

[Python][Error] ImportError: cannot import name ‘if_delegate_has_method’ from ‘sklearn.utils.metaestimators’

@ 2025.04.27 08:19:32

As part of my ML training code, I installed ‘eli5’ using pip install eli5

from eli5.sklearn import PermutationImportance
import eli5

importing eli5 as shown above raises the following error.

ImportError: cannot import name 'if_delegate_has_method' from 'sklearn.utils.metaestimators'

Detailed information on the fix can be found at the following link

https://github.com/manuel-calzolari/sklearn-genetic/commit/12ee9b2e591ec379793bcff1966095b43dac10c6


Summary:

We first cd to the following directory within our venv.

/home/users/anaconda3/envs/[your_venv]/lib/python3.10/site-packages/eli5/sklearn/

We then open permutation_importance.py using your editor of choice.

In permutation_importance.py, we make the following changes:

# before
from sklearn.utils.metaestimators import if_delegate_has_method
# after
from sklearn.utils.metaestimators import available_if

append the following to the end of the file:

def _estimator_has(attr):
    """Check if we can delegate a method to the underlying estimator.
    First, we check the first fitted estimator if available, otherwise we
    check the unfitted estimator.
    """
    return lambda self: (
        hasattr(self.estimator_, attr)
        if hasattr(self, "estimator_")
        else hasattr(self.estimator, attr)
    )
# before
@if_delegate_has_method(delegate='estimator')
# after
@available_if(_estimator_has("score"))
# before
@if_delegate_has_method(delegate='estimator')
# after
@available_if(_estimator_has("predict"))
# before
@if_delegate_has_method(delegate='estimator')
# after
@available_if(_estimator_has("predict_proba"))
# before
@if_delegate_has_method(delegate='estimator')
# after
@available_if(_estimator_has("predict_log_proba"))
# before
@if_delegate_has_method(delegate='estimator')
# after
@available_if(_estimator_has("decision_function"))

The file should end up looking like this: