A Method That Works for Any Error
When a script fails, the tempting response is to change things until it works: reinstall a library, copy a fix from somewhere, edit lines at random. That wastes time and can hide the real problem. A short routine works better:
- Read the last line of the message. It names the error type and what happened, as the readiness lesson showed.
- Decide which kind of problem it is. Most failures in this course are
one of three kinds:
- Environment: the right Python or library is not being used. Messages
such as
ModuleNotFoundErrorpoint here. - Data: the values given to a model are not what it needs: missing values, mismatched lengths, the wrong number of columns.
- Code: a typing mistake, a wrong name or a value of the wrong kind.
- Environment: the right Python or library is not being used. Messages
such as
- Find your own line. Look for the last
Fileline that names your script; lines inside the library show where the problem was detected, not where it was caused. - Change one thing, then rerun. If the message changes, you have learned something even if the script still fails.
Not every message stops the script. A warning, such as a
ConvergenceWarning, lets the script finish but says the result may not be
trustworthy. Treat warnings as problems to understand, not noise to ignore.
Five Problems You Will Meet
| Message starts with | Kind | Usual cause | Fix |
|---|---|---|---|
ModuleNotFoundError: No module named 'sklearn' | Environment | The course environment is not active in this terminal | Activate it; do not reinstall |
ValueError: Input X contains NaN. | Data | Missing values in the features | Fix the values, or remove the rows and record that decision |
ValueError: Found input variables with inconsistent numbers of samples | Data | Features and labels have different lengths | Make both cover the same samples |
ValueError: X has 3 features, but ... is expecting 4 features | Data | Predicting with different columns from training | Give the same columns, in the same order |
ConvergenceWarning | Data or settings | The training search stopped at its step limit | Scale the features, or allow more steps |
Two details matter. First, the exact wording varies between models: for the
sample-count problem, a decision tree says Number of labels=99 does not match number of samples=100 instead. Recognise the meaning, not only the words.
Second, some models handle missing values themselves: in this version of
scikit-learn, decision trees can train on data containing NaN, while
logistic regression and many other models cannot. A script can therefore work
with one model and fail with another on the same data.
Exercise: Fix Five Broken Scripts
Each drill below is a short script with one problem. Run it, read the message, decide the kind of problem, and fix it. The fixes are given after each drill, but try first.
Starting state: the course environment from the setup lesson. Drill 1 starts in a new terminal without the environment active.
-
Create the exercise folder and save the five drill files in it. macOS and Linux:
mkdir -p ~/ai-practice/error-drills cd ~/ai-practice/error-drillsWindows PowerShell:
mkdir $HOME\ai-practice\error-drills cd $HOME\ai-practice\error-drillsSave this as
drill1_environment.py:"""Drill 1: run this in a new terminal before activating the course environment.""" import sklearn print("scikit-learn", sklearn.__version__)Save this as
drill2_missing.py:"""Drill 2: train a model on a small table of orders.""" import pandas as pd from sklearn.linear_model import LogisticRegression orders = pd.DataFrame({ "items": [3, 1, 5, 2, 4, 1], "weight_kg": [2.5, None, 7.0, 1.2, None, 0.4], "late": [0, 0, 1, 0, 1, 0], }) model = LogisticRegression().fit(orders[["items", "weight_kg"]], orders["late"]) print("Trained on", len(orders), "orders")Save this as
drill3_samples.py:"""Drill 3: train on the first 100 iris flowers.""" from sklearn.datasets import load_iris from sklearn.tree import DecisionTreeClassifier X, y = load_iris(return_X_y=True) X_part = X[:100] y_part = y[:99] model = DecisionTreeClassifier(random_state=0).fit(X_part, y_part) print("Trained on", len(y_part), "flowers")Save this as
drill4_features.py:"""Drill 4: predict the species of one new flower.""" from sklearn.datasets import load_iris from sklearn.tree import DecisionTreeClassifier X, y = load_iris(return_X_y=True) model = DecisionTreeClassifier(random_state=0).fit(X, y) new_flower = [[5.1, 3.5, 1.4]] # sepal length, sepal width and petal length in cm print("Predicted species:", model.predict(new_flower))Save this as
drill5_convergence.py:"""Drill 5: train logistic regression on the wine data.""" from sklearn.datasets import load_wine from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split X, y = load_wine(return_X_y=True) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0, stratify=y) model = LogisticRegression().fit(X_train, y_train) print(f"Test accuracy: {model.score(X_test, y_test):.3f}") -
Drill 1. Open a new terminal, go to the exercise folder and, without activating the environment, run
python3 drill1_environment.pyon macOS and Linux orpython drill1_environment.pyon Windows. The last line is usually:ModuleNotFoundError: No module named 'sklearn'Kind: environment. The script is fine; this terminal is using your computer's own Python, which does not have scikit-learn. Fix: activate the environment as in the setup lesson and run
python drill1_environment.py. It printsscikit-learn 1.9.1. Reinstalling would not help: the library is installed, just not in the Python you ran. If your computer's own Python happens to have scikit-learn, the script runs but may print a different version, which is the same problem in disguise. -
Drill 2. With the environment active, run
python drill2_missing.py. The message ends with:ValueError: Input X contains NaN. LogisticRegression does not accept missing values encoded as NaN natively. ...The second line is shortened here. Kind: data. Two weights are
None, which pandas stores asNaN. Fix: the best fix is to find the real weights. Here nobody can confirm them, so remove the incomplete orders: add the lineorders = orders.dropna()directly above themodel = ...line.dropna()returns the table without rows that contain a missing value. The script then printsTrained on 4 orders. Record such a decision: the model now knows nothing about the removed orders. -
Drill 3. Run
python drill3_samples.py. The last line is:ValueError: Number of labels=99 does not match number of samples=100Kind: data.
X[:100]takes 100 flowers buty[:99]only 99 labels, so one flower has no label. With logistic regression the same mistake readsFound input variables with inconsistent numbers of samples: [100, 99]. Fix: changey_part = y[:99]toy_part = y[:100]. It printsTrained on 100 flowers. -
Drill 4. Run
python drill4_features.py. The last line is:ValueError: X has 3 features, but DecisionTreeClassifier is expecting 4 features as input.Kind: data. The model was trained on four measurements per flower, but the new flower has only three. Fix: give all four, in training order, adding the petal width: change the line to
new_flower = [[5.1, 3.5, 1.4, 0.2]] # all four measurements in cm. It printsPredicted species: [0], a setosa. -
Drill 5. Run
python drill5_convergence.py. It printsTest accuracy: 0.933, but first aConvergenceWarningbeginninglbfgs failed to converge after 100 iteration(s), as in the classifier lesson. Kind: data scale and settings. Fix: scale inside a pipeline. Add these imports below the existing ones:from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScalerand change the model line to
model = make_pipeline(StandardScaler(), LogisticRegression()).fit(X_train, y_train). It now printsTest accuracy: 1.000with no warning.
Success: every drill runs after its fix, and for each one you can name the kind of problem and explain the cause from its message in one sentence.
If something differs:
| What you see | Likely cause | Next step |
|---|---|---|
| Drill 1 runs without an error before activation | Your computer's own Python has scikit-learn | Check the version it prints; activate the environment anyway |
| Drill 2 still fails after the fix | dropna() was added below the model line, or its result was not assigned back to orders | Add orders = orders.dropna() above the model line |
| A message other than the one shown | The drill file was changed while pasting | Save the drill again exactly as shown |
IndentationError after editing | Spaces were added at the start of a line | Remove them; these lines start at the left edge |
-
Clean up. macOS and Linux:
cd ~/ai-practice ls rm -rf error-drills lsWindows PowerShell:
cd $HOME\ai-practice ls Remove-Item -Recurse error-drills lsCheck that the first
lsshowserror-drillsbefore removing it. Do the independent task first.
Independent task: the script below has two problems. Fix them one at a
time, rerunning after each fix, and name the kind of each problem. Save this
as drill6_two_problems.py in the exercise folder:
"""Drill 6: this script has two problems. Fix them one at a time."""
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
X, y = load_wine(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0, stratify=y)
tree = DecisionTreeClassifier(random_state=0).fit(X_train, y_train)
print(f"Test accuracy: {tree.score(X_test, y_tset):.3f}")
print("First test wine:", tree.predict(X_test[0]))
Check Your Understanding
- Name the fix for:
ValueError: X has 5 features, but LogisticRegression is expecting 20 features as input. - A learner sees
ModuleNotFoundError: No module named 'pandas'and reinstalls pandas into their computer's own Python. The error disappears, butcheck_setup.pynow reports a pandas version other than 3.0.6. What went wrong? - Why can the same data train a decision tree but stop logistic regression
with
Input X contains NaN?
Answer and Reasoning
Independent task
The first run stops with:
NameError: name 'y_tset' is not defined. Did you mean: 'y_test'?
Kind: code, a typing mistake. Change y_tset to y_test. The script then
prints Test accuracy: 0.889 and stops at the next line with a message
beginning:
ValueError: Expected 2D array, got 1D array instead:
Kind: data shape. X_test[0] is a single row as a flat list of 13
numbers, but predict expects a table with one row per sample. Change it to
X_test[:1], a table containing just the first row. The script then prints
First test wine: [2]. The second problem only appeared after the first was
fixed, which is why changing one thing at a time and rerunning works.
Understanding check
- Predict with data that has the same 20 feature columns, in the same order, as the training data. Something removed or reordered columns, or the wrong table was passed.
- The real problem was an inactive environment. Installing into the computer's own Python made the error go away without fixing it, and the scripts now run with an unpinned version. Activate the course environment instead.
- In this version of scikit-learn, decision trees can handle missing values
themselves, while logistic regression cannot. Whether
NaNis accepted depends on the model, so check the data whichever model you use.
References
- S06: scikit-learn installation guide (source)
- S07: Python 3.15 documentation: venv (source)
- S18: scikit-learn: Cross-validation
- S22: scikit-learn: Metrics and scoring
- S23: scikit-learn: Linear models
- S24: scikit-learn: Decision trees
- S27: scikit-learn: Neural network models (supervised)
- S31: pandas: Working with missing data
- S48: Python 3.15 tutorial: Errors and exceptions (source)