The error “ImportError: cannot import ‘train_test_split'” usually occurs when trying to import train_test_split
from scikit-learn but there is an issue with the installation or import path.
Step 1: Check If Scikit-Learn Is Installed
To use train_test_split
, you must have scikit-learn installed. Check if it’s installed by running:
import sklearn
print(sklearn.__version__) # Check installed version
If you get an ImportError, scikit-learn is not installed.
Fix: Install or Upgrade Scikit-Learn
Run the following command in your terminal or command prompt:
pip install -U scikit-learn
For Jupyter Notebook:
!pip install -U scikit-learn
Step 2: Correct Import Statement
Make sure you are using the correct import statement:
from sklearn.model_selection import train_test_split
Incorrect:
from sklearn.cross_validation import train_test_split # Deprecated
Correct:
from sklearn.model_selection import train_test_split
Step 3: Restart Your Kernel
If you just installed scikit-learn
, restart your Python environment (Jupyter, VS Code, PyCharm, or terminal) and try importing again.
Step 4: Check for Multiple Python Versions
If you have multiple Python versions installed, train_test_split
might be installed in the wrong version. To check:
python -m pip show scikit-learn
If needed, install scikit-learn for the correct version:
python3 -m pip install -U scikit-learn # Mac/Linux
pip install -U scikit-learn # Windows
Step 5: Verify Scikit-Learn Path
Run the following:
import sklearn
print(sklearn.__file__) # Check the installation path
If it points to an unexpected location, uninstall and reinstall:
pip uninstall scikit-learn
pip install scikit-learn
Step 6: Try a Fresh Virtual Environment (If Needed)
If nothing works, create a new virtual environment and install scikit-learn
inside it:
python -m venv myenv
source myenv/bin/activate # Mac/Linux
myenv\Scripts\activate # Windows
pip install scikit-learn