Nameerror: name ‘train_test_split’ is not defined

How to fix the Python nameerror: name ‘train_test_split’ is not defined error message.

If this error gives you a hard time, then you must continue reading.

It is because this article discusses what this error means and why it occurs.

Aside from that, we will also guide you to fix the nameerror name train_test_split is not a defined error message in Python.

What is train_test_split?

The train_test_split is a function from the scikit-learn library that is used to split data into two subsets:

The subsets are:

✔training

✔ and testing set.

The training set is used to train a machine learning model, while the testing set is used to evaluate its performance.

To use this function, you have to import it from the sklearn.model_selection module.

What is “nameerror name ‘train_test_split’ is not defined”?

The nameerror: name ‘train_test_split’ is not defined is an error message in Python that occurs when you are trying to use a function train_test_split without importing it first.

In addition to that, this error is usually raised because you did not install the required modules or libraries or forgot to define it before using the function.

Therefore, Python doe not know what the train_test_split function is.

Why does this error occur?

The nameerror name train_test_split is not defined can occur due to some factors that include the following:

❌ The Scikit-learn or sklearn library is not imported.

❌ The train_test_split function is not imported.

❌ Misspelled the function name

How to fix “nameerror: name ‘train_test_split’ is not defined”?

To fix the nameerror name ‘train_test_split’ is not defined error message, ensure that the train_test_split function is imported correctly.

Solution 1: Install installed sklearn

If you haven’t installed the sklearn library, or you are not if you have it already, you can check it using the following command:

import sklearn
print(sklearn.__version__)

If you get this error message below:

ModuleNotFoundError: no module named 'sklearn' 

You have to install the module, here’s the command that will install the sklearn.

✅ pip install sklearn
pip install scikit-learn

or

✅ pip3 install sklearn
✅ pip3 install scikit-learn

Solution 2: Import the train_test_split function from sklearn.model_selection

You can import the train_test_split function from the sklearn.model_selection module.

Kindly refer to the example code below:

✅ from sklearn.model_selection import train_test_split

Solution 3: Check for typos

Ensure that you’ve spelled the function name correctly. It should be train_test_split, to avoid encountering this error.

Conclusion

In conclusion, the error message nameerror: name ‘train_test_split’ is not defined occurs when you are trying to use a function train_test_split without importing it first.

This article discusses what this error is all about and already provides solutions to help you fix this error.

You could also check out other “nameerror” articles that may help you in the future if you encounter them.

We are hoping that this article helps you fix the error. Thank you for reading itsourcecoders 😊

Function-related NameError

NameError on a function usually means the function was not defined yet, the wrong name was used, or the function is in a different scope.

Common triggers

  • Function name typo. caclulate() instead of calculate().
  • Called before def. At module level.
  • Function in wrong module. Imported from a different module than expected.
  • Decorated function shadowed. Decorator returned wrong name.

Diagnostic pattern

# BAD — undefined function
def main():
    result = compute_total()   # NameError if compute_total not defined

main()

# GOOD — check spelling and scope
def compute_total():
    return 42

def main():
    result = compute_total()
    print(result)

main()

# For decorated functions, make sure functools.wraps is used
from functools import wraps

def my_decorator(fn):
    @wraps(fn)
    def wrapper(*args, **kwargs):
        return fn(*args, **kwargs)
    return wrapper

Best practices

  • Use editor autocomplete. Prevents most typo NameError.
  • Order definitions before calls at module level.
  • Use type hints. Editor flags undefined names immediately.
  • Use functools.wraps in decorators to preserve the original function name.

Frequently Asked Questions

What is Python NameError and what causes it?

NameError is raised when Python encounters a name (variable, function, class) that hasn’t been defined in the current scope. Most common causes: typo in variable name, using a variable before assigning it, missing import, or referencing a variable that was defined inside a function but accessed outside it.

How do I fix ‘name X is not defined’?

Check three things: (1) Is the name a typo? Compare with the spelling where you defined it. (2) Did you import it? Add ‘from module import X’ or ‘import module’ at the top. (3) Is X defined in a different scope (inside a function, conditional branch, or with-block) that hasn’t executed yet at the point you’re using it? Move the definition before the use.

Why does my variable work in one cell but not another (Jupyter)?

Jupyter kernels keep state between cells. If you defined X in cell 5 and run cell 3 later, X exists. But after Kernel-Restart, only the cells you re-run define their variables. Always run cells top-to-bottom on a fresh kernel before submitting. Use ‘Restart and Run All’ to verify your notebook is reproducible.

What is the difference between NameError and AttributeError?

NameError: the name itself doesn’t exist anywhere in scope (typo, missing import, scope issue). AttributeError: the name exists and points to an object, but that object has no such attribute/method (typo on method name, wrong object type). NameError is about the variable; AttributeError is about what’s inside it.

Where can I find more NameError fixes?

Browse the NameError reference hub for 49+ specific fixes (NumPy, pandas, Jupyter, Python 2 to 3 migration). For Python scope rules see the Python Tutorial hub. For attribute-level errors see AttributeError.

Caren Bautista


Technical Writer at PIES IT Solution

Responsible for crafting clear, well-structured, and beginner-friendly content across the platform. Handles the writing, proofreading, and editorial review of tutorials, guides, and documentation to ensure every article is accurate, readable, and easy to follow.

Expertise: Technical Writing · Content Creation · Documentation · Editorial Writing · JavaScript · TypeScript · Python · Python Errors · HTTP Errors · MS Excel
 · View all posts by Caren Bautista →

Leave a Comment