'import error for -cannot import name 'train_test_split' from 'sklearn.preprocessing'

I wanted to import train_test_split to split my dataset into a test dataset and a training dataset but an import error has occurred.

I tried all of these but none of them worked:

conda upgrade scikit-learn
pip uninstall scipy
pip3 install scipy

pip uninstall sklearn
pip uninstall scikit-learn
pip install sklearn

Here is the code which yields the error:

from sklearn.preprocessing import train_test_split
X_train, X_test, y_train, y_test = 
train_test_split(X,y,test_size=0.2,random_state=0)

And here is the error:

from sklearn.preprocessing import train_test_split
Traceback (most recent call last):

  File "<ipython-input-3-e25c97b1e6d9>", line 1, in <module>
    from sklearn.preprocessing import train_test_split

ImportError: cannot import name 'train_test_split' from 'sklearn.preprocessing' (C:\ProgramData\Anaconda3\lib\site-packages\sklearn\preprocessing\__init__.py)


Solution 1:[1]

train_test_split isn't in preprocessing, it is in model_selection and cross_validation, so you meant:

from sklearn.model_selection import train_test_split

Or:

from sklearn.cross_validation import train_test_split

Solution 2:[2]

test_train_split is not present in preprocessing. It is present in model_selection module so try.

from sklearn.model_selection import train_test_split

it will work.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 U12-Forward
Solution 2 Dev