Skip to content

REGRESSION: StratifiedShuffleSplit errors on list y #7582

Closed

Description

@bwang482

Just updated sklearn:

$ python -c "import sklearn; print(sklearn, sklearn.__version__)"
(<module 'sklearn' from '/usr/local/lib/python2.7/dist-packages/sklearn/__init__.pyc'>, '0.18')

Now receiving errors for importing model_selection modules:

In [3]: from sklearn.model_selection import train_test_split
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-3-139cc3505715> in <module>()
----> 1 from sklearn.model_selection import train_test_split

/usr/local/lib/python2.7/dist-packages/sklearn/model_selection/__init__.py in <module>()
     15 from ._split import check_cv
     16 
---> 17 from ._validation import cross_val_score
     18 from ._validation import cross_val_predict
     19 from ._validation import learning_curve

/usr/local/lib/python2.7/dist-packages/sklearn/model_selection/_validation.py in <module>()
     25 from ..utils.fixes import astype
     26 from ..utils.validation import _is_arraylike, _num_samples
---> 27 from ..utils.metaestimators import _safe_split
     28 from ..externals.joblib import Parallel, delayed, logger
     29 from ..metrics.scorer import check_scoring

ImportError: cannot import name _safe_split
In [6]: from sklearn.model_selection import KFold
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-6-7748d201c9c6> in <module>()
----> 1 from sklearn.model_selection import KFold

/usr/local/lib/python2.7/dist-packages/sklearn/model_selection/__init__.py in <module>()
     15 from ._split import check_cv
     16 
---> 17 from ._validation import cross_val_score
     18 from ._validation import cross_val_predict
     19 from ._validation import learning_curve

/usr/local/lib/python2.7/dist-packages/sklearn/model_selection/_validation.py in <module>()
     25 from ..utils.fixes import astype
     26 from ..utils.validation import _is_arraylike, _num_samples
---> 27 from ..utils.metaestimators import _safe_split
     28 from ..externals.joblib import Parallel, delayed, logger
     29 from ..metrics.scorer import check_scoring

ImportError: cannot import name _safe_split

Activity

  1. bwang482 commented on Oct 5, 2016

    @bwang482
    Author

    from sklearn.cross_validation import train_test_split works but shouldn't 0.18 version be updated now?

  2. amueller commented on Oct 5, 2016

    @amueller
    Member

    How did you install and update scikit-learn?
    If you install with conda and update with pip, there will be left-over files. I recommend uninstalling, removing the folder entirely, and reinstalling.

  3. bwang482 commented on Oct 5, 2016

    @bwang482
    Author

    Yes, forgot I installed with conda. Thanks, issue closed.

  4. bwang482 commented on Oct 5, 2016

    @bwang482
    Author

    With from sklearn.model_selection import train_test_split I am getting IndexError for splitting Pandas DataFrame:

    In [9]: train_df, test_df = train_test_split(df, test_size=0.3, random_state=42, stratify=meds)
       ...: 
    ---------------------------------------------------------------------------
    IndexError                                Traceback (most recent call last)
    <ipython-input-9-38a80ac8eeee> in <module>()
    ----> 1 train_df, test_df = train_test_split(df, test_size=0.3, random_state=42, stratify=meds)
    
    /usr/local/lib/python2.7/dist-packages/sklearn/model_selection/_split.pyc in train_test_split(*arrays, **options)
       1671                  random_state=random_state)
       1672 
    -> 1673     train, test = next(cv.split(X=arrays[0], y=stratify))
       1674     return list(chain.from_iterable((safe_indexing(a, train),
       1675                                      safe_indexing(a, test)) for a in arrays))
    
    /usr/local/lib/python2.7/dist-packages/sklearn/model_selection/_split.pyc in split(self, X, y, groups)
        931         """
        932         X, y, groups = indexable(X, y, groups)
    --> 933         for train, test in self._iter_indices(X, y, groups):
        934             yield train, test
        935 
    
    /usr/local/lib/python2.7/dist-packages/sklearn/model_selection/_split.pyc in _iter_indices(self, X, y, groups)
       1263             for i, class_i in enumerate(classes):
       1264                 permutation = rng.permutation(class_counts[i])
    -> 1265                 perm_indices_class_i = np.where((y == class_i))[0][permutation]
       1266 
       1267                 train.extend(perm_indices_class_i[:n_i[i]])
    
    IndexError: index 8 is out of bounds for axis 1 with size 0
    
    In [8]: df.dtypes
    Out[8]: 
    A        object
    B       object
    C     int64
    dtype: object
    In [10]: df.shape
    Out[10]: (6884, 3)
    

    With the old version train_test_split, I get no error and resulting splits are correct. Is there any differences between the old and the new that caused the IndexError? Thanks.

  5. amueller commented on Oct 5, 2016

    @amueller
    Member

    No, there shouldn't have been a change there.
    I'm not sure that stratify is tested with a dataframe. What's the shape of meds?

  6. bwang482 commented on Oct 5, 2016

    @bwang482
    Author

    Ah ok meds is a list. After converting to numpy array, it now works. Thanks!

    Interestingly the 0.17 version stratify works with list.

    Issue closed.

  7. amueller commented on Oct 5, 2016

    @amueller
    Member

    That is strange and shouldn't happen. Can you confirm that exactly the same code worked on 0.17? Then that is a regression :(

  8. added this to the 0.18.1 milestone on Oct 5, 2016
  9. amueller commented on Oct 5, 2016

    @amueller
    Member

    @raghavrv there's a check on y missing, maybe check_Xy? Would you mind seeing if that is also the case for other stratified models or other grouped models? We should accept lists everywhere.

  10. changed the title [-]model_selecion importing "ImportError: cannot import name _safe_split"[/-] [+]REGRESSION: StratifiedShuffleSplit errors on list y[/+] on Oct 5, 2016
  11. 2 remaining items

  12. raghavrv commented on Oct 5, 2016

    @raghavrv
    Member

    Could you give me a reproducible sample code? The following seems to work for me

    from sklearn.model_selection import train_test_split
    
    X = [[1,], [2,], [3,], [4,], [5,], [6,], [7,]]
    y = [0, 0, 0, 1, 1, 0, 0]
    
    train_test_split(X, y, stratify=y, random_state=42)
  13. bwang482 commented on Oct 5, 2016

    @bwang482
    Author

    @raghavrv Ah I think the error is caused by the stratify list having strings. So

    import pandas as pd
    import numpy as np
    from sklearn.model_selection import train_test_split
    df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
    st = [1]*33+[-1]*33+[0]*34
    train, test = train_test_split(df, test_size=0.3, random_state=42, stratify=st)
    # **Works!**
    
    st = ['A']*33+['C']*33+['B']*34
    train, test = train_test_split(df, test_size=0.3, random_state=42, stratify=st)
    # **IndexError: index 31 is out of bounds for axis 1 with size 0**
    
    train, test = train_test_split(df, test_size=0.3, random_state=42, stratify=np.array(st))
    # **Works!**
  14. lesteve commented on Oct 6, 2016

    @lesteve
    Member

    Confirmed. Here is an updated snippet that can be run under both 0.17 and 0.18:

    import pandas as pd
    import numpy as np
    try:
        from sklearn.model_selection import train_test_split
    except ImportError:
        from sklearn.cross_validation import train_test_split
    
    df = pd.DataFrame(np.random.randint(0, 100, size=(100, 4)),
                      columns=list('ABCD'))
    
    st = ['A']*33+['C']*33+['B']*34
    train, test = train_test_split(df, test_size=0.3, random_state=42, stratify=st)
  15. raghavrv commented on Oct 6, 2016

    @raghavrv
    Member

    @bluemonk482 @lesteve Thanks for confirming... I've made a PR at #7593 that fixes this.

  16. tangfucius commented on Nov 3, 2016

    @tangfucius

    @bluemonk482 I am having the error ImportError: cannot import name _safe_split in your first post above. I tried removing scikit-learn from conda, removing all directories named sklearn, then did a conda install again, but it still didn't work. How did you get it working? Thanks!

  17. bwang482 commented on Nov 3, 2016

    @bwang482
    Author

    @tangfucius Make sure which python points to the python directory you expect, OR try from sklearn.cross_validation import train_test_split instead, which is the older version

  18. shamrockiris commented on Nov 3, 2016

    @shamrockiris

    Get error ImportError: cannot import name _safe_split while trying from sklearn.model_selection import cross_val_score. Removed package and folder and reinstalled. Any thoughts how to solve this? Thank you.

  19. jnothman commented on Nov 4, 2016

    @jnothman
    Member

    If you removed the folder, I don't know why this should happen unless
    you're actually loading a different version to the one you think you are.
    Check sklearn.path, for instance..

    On 4 November 2016 at 08:19, Xiaowen Wang [email protected] wrote:

    Get error ImportError: cannot import name _safe_split while trying from
    sklearn.model_selection import cross_val_score. Removed package and
    folder and reinstalled. Any thoughts how to solve this? Thank you.

    —
    You are receiving this because you are subscribed to this thread.
    Reply to this email directly, view it on GitHub
    #7582 (comment),
    or mute the thread
    https://github.com/notifications/unsubscribe-auth/AAEz6zc6u2JK1GKcWGmLzqYDtKdR_7sLks5q6k_1gaJpZM4KO6eM
    .

  20. traethethird commented on Nov 16, 2016

    @traethethird

    @tangfucius @shamrockiris Hopefully you're not still having the problem, but if anyone else stumbles across this, I had to uninstall/reinstall both scikit-learn and scipy to stop this error.

  21. amueller commented on Nov 16, 2016

    @amueller
    Member

    @traethethird no, this is unrelated to scipy. This was not what removed the error.
    Locking the issue. Please open a new issue if you have installation problems or import errors.

  22. locked and limited conversation to collaborators on Nov 16, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions