Artificial Intelligence Fundamentals / Learn From Labelled Data

Train and evaluate a regression model

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

Predicting a Number

Classification predicts a category. Regression predicts a number: a delivery time, a price, tomorrow's demand. The fit, predict and score pattern stays the same, but judging the result changes. A predicted delivery time is rarely exactly right, so instead of counting right and wrong answers you measure how far predictions are from the truth.

Linear Regression

Linear regression predicts a number as a starting value plus one weight times each feature. For delivery times, that could read: "10 minutes, plus 3 minutes per kilometre, plus 8 minutes per level of traffic". Training, fit, finds the starting value and weights that make the predictions as close as possible to the training labels; scikit-learn's LinearRegression uses the method called ordinary least squares. After training, the weights are stored in coef_, one per feature, in the order of the feature columns.

Because each weight is a number of minutes per unit of a feature, a linear model is easy to read: you can check whether its weights are plausible.

Mean Absolute Error

The mean absolute error (MAE) is the average distance between predictions and true values, ignoring whether a prediction was too high or too low:

MAE = the average of |prediction − true value| over the test samples

It is expressed in the units of the label. An MAE of 4 minutes means predictions are, on average, 4 minutes away from the actual delivery time. That makes it easy to judge against the real need: 4 minutes may be fine for a food delivery and useless for scheduling a train.

As always, compare with a baseline. DummyRegressor() predicts the training average for every case; its MAE shows how far off you would be by ignoring the features altogether.

Exercise: Predict Delivery Times

You will generate delivery data with a known pattern, train a linear model, and compare its error with the baseline's.

Starting state: the course environment, active in your terminal. The script generates its own data.

  1. Create the exercise folder. macOS and Linux:

    mkdir -p ~/ai-practice/predict-delivery-times
    cd ~/ai-practice/predict-delivery-times
    

    Windows PowerShell:

    mkdir $HOME\ai-practice\predict-delivery-times
    cd $HOME\ai-practice\predict-delivery-times
    

    Save this as delivery_times.py in that folder:

    """Predict delivery times in minutes and judge the error against a baseline."""
    import numpy as np
    from sklearn.dummy import DummyRegressor
    from sklearn.linear_model import LinearRegression
    from sklearn.metrics import mean_absolute_error
    from sklearn.model_selection import train_test_split
    
    # Generated deliveries: time grows with distance and with traffic, plus random variation.
    rng = np.random.default_rng(4)
    distance_km = rng.uniform(1, 20, size=500)
    traffic = rng.integers(0, 3, size=500)  # 0 light, 1 normal, 2 heavy
    minutes = 10 + 3 * distance_km + 8 * traffic + rng.normal(0, 5, size=500)
    X = np.column_stack([distance_km, traffic])
    
    X_train, X_test, y_train, y_test = train_test_split(X, minutes, random_state=4)
    baseline = DummyRegressor().fit(X_train, y_train)
    model = LinearRegression().fit(X_train, y_train)
    print(f"Baseline mean absolute error: {mean_absolute_error(y_test, baseline.predict(X_test)):.1f} minutes")
    print(f"Model mean absolute error:    {mean_absolute_error(y_test, model.predict(X_test)):.1f} minutes")
    print("Learned minutes per km:", model.coef_[0].round(2), "| per traffic level:", model.coef_[1].round(2))
    for predicted, actual in zip(model.predict(X_test[:3]), y_test[:3]):
        print(f"Predicted {predicted:5.1f}, actual {actual:5.1f}")
    
  2. Run it:

    python delivery_times.py
    

    Output, which should match exactly:

    Baseline mean absolute error: 16.5 minutes
    Model mean absolute error:    4.2 minutes
    Learned minutes per km: 2.94 | per traffic level: 8.15
    Predicted  19.2, actual  24.0
    Predicted  64.6, actual  69.8
    Predicted  48.6, actual  52.2
    

How the Script Works

Generating the data. np.random.default_rng(4) creates a random-number generator with a fixed seed, so the data is the same on every run. rng.uniform(1, 20, size=500) draws 500 distances between 1 and 20 km, rng.integers(0, 3, size=500) draws traffic levels 0, 1 or 2, and rng.normal(0, 5, size=500) draws random variation centred on 0 with a standard deviation of 5 minutes. The minutes line builds each delivery time from a known rule: 10 minutes, plus 3 per kilometre, plus 8 per traffic level, plus the variation. np.column_stack puts the two features side by side as X.

Because you wrote the rule, you can check what the model learns. With real data, the rule is unknown; that is why you need a model.

Training and comparing. The data is split, then both the baseline and the linear model are fitted on the training deliveries. mean_absolute_error takes the true values first and the predictions second.

What the results show. The baseline is 16.5 minutes off on average; the model, 4.2 minutes. The learned weights, 2.94 minutes per km and 8.15 minutes per traffic level, are close to the 3 and 8 used to generate the data. They are not exact, because the random variation hides the rule slightly. The model's error cannot fall to zero either: the variation, with a standard deviation of 5 minutes, is genuinely unpredictable from the features, so no model could remove it. The three example predictions are each a few minutes off, as an MAE of 4.2 suggests.

If you changed the 5 in rng.normal(0, 5, size=500) to 1, the deliveries would vary less around the rule, and the model's MAE would shrink accordingly; the baseline's would barely change.

Success: the output matches; you can state the model's MAE in minutes and compare it with the baseline's, and you can relate the learned weights to the rule that generated the data.

If something differs:

What you seeLikely causeNext step
Different numbersThe seed 4 or a random_state was changedRestore the values shown
ValueError: Found input variables with inconsistent numbers of samplesThe features and labels have different lengths, for example after editing one size=500Use the same size everywhere
An MAE in the thousandsThe arguments to mean_absolute_error include features instead of labelsPass y_test and the predictions
ModuleNotFoundErrorThe course environment is not activeActivate it and rerun
  1. Clean up. macOS and Linux:

    cd ~/ai-practice
    ls
    rm -rf predict-delivery-times
    ls
    

    Windows PowerShell:

    cd $HOME\ai-practice
    ls
    Remove-Item -Recurse predict-delivery-times
    ls
    

    Check that the first ls shows predict-delivery-times before removing it. Do the independent task first.

Independent task: change the script so that the model uses distance only. Replace the line X = np.column_stack([distance_km, traffic]) with X = distance_km.reshape(-1, 1), which makes a one-column feature table, and change the Learned minutes per km line to print("Learned minutes per km:", model.coef_[0].round(2)), because there is now only one weight. Predict whether the model's error will rise or fall, then run it.

Check Your Understanding

A delivery company's model has an MAE of 12 minutes; the mean baseline's MAE is 15 minutes.

  1. What does an MAE of 12 minutes mean in plain words?
  2. The company promises customers a one-hour delivery window. Is the model good enough for that promise? What about a promise of "within 5 minutes"?
  3. How much has the model improved on simply predicting the average?

Answer and Reasoning

Independent task

The model's MAE rises from 4.2 to 7.1 minutes. Without the traffic feature, the model cannot account for the 0, 8 or 16 extra minutes that traffic adds, so that part of the variation now counts as error. It is still far better than the baseline's 16.5 minutes, because distance explains most of the variation.

Understanding check

  1. On average, its predictions are 12 minutes away from the actual delivery times, sometimes early, sometimes late.
  2. For a one-hour window, an average error of 12 minutes may be acceptable, though some individual predictions will be further off, so the company should also look at the largest errors. For "within 5 minutes", no: the typical error alone is more than twice that.
  3. By 3 minutes on average, from 15 to 12: a modest improvement. Whether the model is worth using depends on what those 3 minutes are worth.

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