Your first prediction: linear regression
Fit a straight line to data with scikit-learn, use it to predict numbers, and compare it with a simple baseline so you know if it really helps.
In 60 seconds
Your first prediction: linear regression
Fit a straight line to data with scikit-learn, use it to predict numbers, and compare it with a simple baseline so you know if it really helps.
prediction = slope × feature + interceptThe scikit-learn pattern
- 1
Create
model = LinearRegression() - 2
Fit (train)
model.fit(X_train, y_train)finds the best slopes. - 3
Predict
model.predict(X_new)gives numbers for new rows.
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
# Made-up data: wedding guests and kg of rice cooked. Not real figures.
rng = np.random.default_rng(1)
guests = rng.integers(50, 500, 25)
rice_kg = 0.15 * guests + 5 + rng.normal(0, 4, 25)
X = guests.reshape(-1, 1) # scikit-learn wants a 2-D table
model = LinearRegression().fit(X, rice_kg)
print("Slope (kg per guest):", round(model.coef_[0], 3))
print("Intercept (kg):", round(model.intercept_, 2))
print("Prediction for 250 guests:", round(model.predict([[250]])[0], 1), "kg")
xs = np.array([[50], [500]])
plt.scatter(guests, rice_kg, label="made-up examples")
plt.plot(xs, model.predict(xs), color="red", label="learned line")
plt.xlabel("guests"); plt.ylabel("rice (kg)"); plt.legend()Measuring error
| Measure | What it means | Notes |
|---|---|---|
| MAE (mean absolute error) | Average size of the mistake | Same unit as the label; easy to explain |
| RMSE (root mean squared error) | Like MAE but punishes big mistakes more | Same unit as the label |
| R² (R-squared) | How much of the variation the model explains | 1 is perfect, 0 is no better than predicting the average; can be negative |
Always compare with a baseline
train_test_split to keep some rows aside. The "Doing it honestly" unit goes deeper.When a straight line is the wrong shape
Watch and read more
Lab
A linear regression on the diabetes dataset using one feature, scored on a held-out test set and compared with a baseline.
The problem
The diabetes dataset has 442 patients, 10 measurements each (already scaled, so values are small numbers around 0), and a number measuring how the disease progressed one year later. This is a teaching dataset, not medical advice.
- Run the starter. It uses only the
bmicolumn as the feature and splits the data. - Create a
LinearRegressionnamedmodeland fit it on the training rows only. - Compute
test_mae: the mean absolute error of the model on the test rows. - Compute
baseline_mae: the test error if you predict the training average for every test row. - Print both. Does the model beat the baseline? By how much?
Practice lab
Edit the code and run it. Python runs in your browser — nothing is sent to our server.
No output. Add print(...) to see values.
You are done when
Hard questions
Try to answer before you reveal. If you can answer these, you understood the lesson.
Q1Why must the baseline use the training average and not the test average?Reveal
In real use you do not know the answers for new rows, so you cannot know their average. Using the test average would secretly give the baseline information from the test set. Both the model and the baseline must only use what was known at training time.
Q2Add a second feature, <code>s5</code>, so X has two columns. What do you expect, and how would you check it is not luck?Reveal
Likely the test error drops, since another measurement adds information. To check it is not luck of one split, repeat with several different random_state values, or use cross-validation (in the lesson on train, validation and test sets), and see if the gain holds most of the time.
Questions people ask
Why does scikit-learn want X as a 2-D table even for one feature?
Because the same code must work for one feature or a hundred. X is always rows by columns. reshape(-1, 1) turns a flat list into one column, or you can pass a DataFrame with one column.
Does a big slope mean a feature is important?
Not by itself. The slope depends on the unit. A slope per gram looks tiny next to a slope per kilogram. To compare features fairly, scale them first, and even then be careful: related features can share credit in odd ways.
Does linear regression show cause and effect?
No. It finds a pattern in the data. More ice-cream sales and more drownings rise together in summer, but one does not cause the other. Causes need careful study design, not just a fitted line.
What is random_state?
A number that fixes the random choices, such as which rows go to the test set. The same number gives the same split every time, so your results can be repeated.
Lesson test
5 questions. Get 3 right (60%) to pass and complete this lesson.