G15
G15

Reputation: 11

ImportError: cannot import name 'safe_indexing' from 'sklearn.utils'

Whenever I try to run the following line of code:

from imblearn.under_sampling import NearMiss

for under-sampling (or over-sampling) imbalanced data on Jupyter notebook, I get this error:

ImportError Traceback (most recent call last)
<ipython-input-21-c701341dce49> in <module>
----> 1 from imblearn.under_sampling import NearMiss

~\anaconda3\lib\site-packages\imblearn\under_sampling\__init__.py in <module>
        4 """
        5 
----> 6 from ._prototype_generation import ClusterCentroids
        7 
        8 from ._prototype_selection import RandomUnderSampler

~\anaconda3\lib\site-packages\imblearn\under_sampling\_prototype_generation\__init__.py in <module>
        4 """
        5 
----> 6 from ._cluster_centroids import ClusterCentroids
        7 
        8 __all__ = ['ClusterCentroids']

~\anaconda3\lib\site-packages\imblearn\under_sampling\_prototype_generation\_cluster_centroids.py in <module>
        15 from sklearn.cluster import KMeans
        16 from sklearn.neighbors import NearestNeighbors
---> 17 from sklearn.utils import safe_indexing
        18 
        19 from ..base import BaseUnderSampler

ImportError: cannot import name 'safe_indexing' from 'sklearn.utils' (C:\Users\anaconda3\lib\site-packages\sklearn\utils\__init__.py)

Upvotes: 1

Views: 3534

Answers (3)

Charanjit Gill
Charanjit Gill

Reputation: 11

Edit ..\Anaconda3\Lib\site-packages\sklearn\utils\ __init__.py.

Copy def _safe_indexing ... till next def and paste the code with renaming to def safe_indexing... .

Keep previous _safe_indexing as it is.

It solved the issue in this way.

Upvotes: 1

In ~\Anaconda3\Lib\site-packages\yellowbrick\classifier\threshold.py module replace:

from sklearn.utils import indexable, safe_indexing

with

from sklearn.utils import indexable, _safe_indexing

After that, restart the kernel.

Upvotes: 0

neuagem
neuagem

Reputation: 11

For imblearn.under_sampling, did you try reinstalling the package?:

pip install imbalanced-learn

conda:

conda install -c conda-forge imbalanced-learn

in jupyter notebook:

import sys
!{sys.executable} -m pip install <package_name>

If you have scikitlearn>=0.24 (as far as i see there is a dependency for imblearn now,as scikit-learn (>=0.23) https://imbalanced-learn.org/stable/install.html) you may want to try:

try:
    from sklearn.utils import safe_indexing
except ImportError:
    from sklearn.utils import _safe_indexing

Upvotes: 1

Related Questions