Artificial Intelligence Fundamentals / Check and Troubleshoot Models

Diagnose common errors

Lesson 15 of 26. Open to read. No account needed.

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:

  1. Read the last line of the message. It names the error type and what happened, as the readiness lesson showed.
  2. 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 ModuleNotFoundError point 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.
  3. Find your own line. Look for the last File line that names your script; lines inside the library show where the problem was detected, not where it was caused.
  4. 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 withKindUsual causeFix
ModuleNotFoundError: No module named 'sklearn'EnvironmentThe course environment is not active in this terminalActivate it; do not reinstall
ValueError: Input X contains NaN.DataMissing values in the featuresFix the values, or remove the rows and record that decision
ValueError: Found input variables with inconsistent numbers of samplesDataFeatures and labels have different lengthsMake both cover the same samples
ValueError: X has 3 features, but ... is expecting 4 featuresDataPredicting with different columns from trainingGive the same columns, in the same order
ConvergenceWarningData or settingsThe training search stopped at its step limitScale 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.

  1. 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-drills
    

    Windows PowerShell:

    mkdir $HOME\ai-practice\error-drills
    cd $HOME\ai-practice\error-drills
    

    Save 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}")
    
  2. Drill 1. Open a new terminal, go to the exercise folder and, without activating the environment, run python3 drill1_environment.py on macOS and Linux or python drill1_environment.py on 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 prints scikit-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.

  3. 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 as NaN. Fix: the best fix is to find the real weights. Here nobody can confirm them, so remove the incomplete orders: add the line orders = orders.dropna() directly above the model = ... line. dropna() returns the table without rows that contain a missing value. The script then prints Trained on 4 orders. Record such a decision: the model now knows nothing about the removed orders.

  4. Drill 3. Run python drill3_samples.py. The last line is:

    ValueError: Number of labels=99 does not match number of samples=100
    

    Kind: data. X[:100] takes 100 flowers but y[:99] only 99 labels, so one flower has no label. With logistic regression the same mistake reads Found input variables with inconsistent numbers of samples: [100, 99]. Fix: change y_part = y[:99] to y_part = y[:100]. It prints Trained on 100 flowers.

  5. 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 prints Predicted species: [0], a setosa.

  6. Drill 5. Run python drill5_convergence.py. It prints Test accuracy: 0.933, but first a ConvergenceWarning beginning lbfgs 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 StandardScaler
    

    and change the model line to model = make_pipeline(StandardScaler(), LogisticRegression()).fit(X_train, y_train). It now prints Test accuracy: 1.000 with 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 seeLikely causeNext step
Drill 1 runs without an error before activationYour computer's own Python has scikit-learnCheck the version it prints; activate the environment anyway
Drill 2 still fails after the fixdropna() was added below the model line, or its result was not assigned back to ordersAdd orders = orders.dropna() above the model line
A message other than the one shownThe drill file was changed while pastingSave the drill again exactly as shown
IndentationError after editingSpaces were added at the start of a lineRemove them; these lines start at the left edge
  1. Clean up. macOS and Linux:

    cd ~/ai-practice
    ls
    rm -rf error-drills
    ls
    

    Windows PowerShell:

    cd $HOME\ai-practice
    ls
    Remove-Item -Recurse error-drills
    ls
    

    Check that the first ls shows error-drills before 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

  1. Name the fix for: ValueError: X has 5 features, but LogisticRegression is expecting 20 features as input.
  2. A learner sees ModuleNotFoundError: No module named 'pandas' and reinstalls pandas into their computer's own Python. The error disappears, but check_setup.py now reports a pandas version other than 3.0.6. What went wrong?
  3. 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

  1. 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.
  2. 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.
  3. In this version of scikit-learn, decision trees can handle missing values themselves, while logistic regression cannot. Whether NaN is accepted depends on the model, so check the data whichever model you use.

References

Study this course with an account

Course access adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 199 plus 18% GST. 90 days of online access. No auto-renewal.

See course access

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy