Your First Predictive Model with scikit-learn
Train and evaluate a linear regression with scikit-learn: features and targets, train-test splits, MAE and R-squared, and the overfitting and leakage traps.
Welcome back!
Step 1 of 13Learn
From patterns to predictions
Back to Maya and the bike stations. Exploration showed that morning demand rises with temperature and falls with rain. A predictive model turns that pattern into numbers: given tomorrow's forecast, how many bikes will Harbor station need at 8 a.m.?
In machine learning vocabulary:
- The target (or label, y) is what you want to predict:
bikes_out. - The features (X) are the inputs used to predict it: temperature, rain, weekday, hour.
- Each row is one example (an observation).
Predicting a number is regression; predicting a category, such as "will run short: yes/no", is classification.
The simplest regression model is linear regression, which fits a straight line (or a flat plane with several features):
predicted bikes = intercept + slope × temperature
The model "learns" by choosing the intercept and slope that make predictions as close as possible to the actual values in the training data, usually by minimizing the sum of squared errors (ordinary least squares).
Linear regression is a great first model: it's fast, and its coefficients are readable. A slope of 0.6 means "about 0.6 more bikes for each extra degree", which you can sanity-check against common sense.
Step 2 of 13Explore
Fit a line by eye
The points follow roughly bikes = 2 + 0.6 × temperature. Adjust the intercept and slope to see how the line changes; the readout predicts demand at 25 degrees.
- Predicted bikes at 25°
- 17
- Extra bikes per +10°
- 6
Step 3 of 13Practice · Work it out
A fitted model is: predicted rentals = 4 + 0.75 × temperature. How many rentals does it predict at 20 degrees?
Step 4 of 13Learn
The scikit-learn pattern
scikit-learn gives nearly every model the same interface, so once you learn one, you can try many:
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, r2_score
X = df[["temp", "rain_mm", "is_weekday"]] # features: 2-D table
y = df["bikes_out"] # target: 1-D
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42)
model = LinearRegression()
model.fit(X_train, y_train) # learn from training data only
pred = model.predict(X_test) # predict data the model hasn't seen
print(mean_absolute_error(y_test, pred))
print(r2_score(y_test, pred))
print(model.intercept_, model.coef_)The steps:
- Choose features and target. X is two-dimensional (rows × features), even with a single feature:
df[["temp"]], notdf["temp"]. - Split the data. The model trains on 80% and is judged on the 20% it never saw.
random_statemakes the split reproducible. - Fit on the training set.
- Predict on the test set.
- Evaluate by comparing predictions with the true test values.
Swapping in a different model, such as RandomForestRegressor, changes one line; the rest of the pattern stays identical.
Step 5 of 13Practice · Put in order
Put the steps of training and evaluating a scikit-learn model in order.
Drag the items, or use the arrow buttons, to put them in order.
- Predict on the test features
- Fit the model on the training data
- Create the model object, for example LinearRegression()
- Select the feature columns X and the target column y
- Compare the predictions with the test targets using a metric
- Split the data into training and test sets
Step 6 of 13Learn
Measuring how good the model is
Mean absolute error (MAE) is the average size of the prediction errors, in the target's own units:
MAE = average of |actual − predicted|
If actual rentals are 10, 14 and 8 and predictions are 12, 13 and 5, the errors are 2, 1 and 3, so MAE = 2 bikes. It's easy to explain: "on average, we're off by 2 bikes."
Root mean squared error (RMSE) squares errors before averaging and then takes the square root. It punishes large misses more heavily than MAE.
R² (R-squared) compares the model to the simplest possible baseline, always predicting the average:
R² = 1 − (sum of squared model errors) ÷ (sum of squared errors of predicting the mean)
R² = 1 is perfect, 0 means no better than predicting the average, and it can even be negative on test data when the model is worse than the average.
Always compare against a baseline. A model with MAE = 2 bikes sounds good, unless simply predicting yesterday's value gives MAE = 1.8. And judge errors in context: 2 bikes is excellent for a 40-bike station and poor for a 5-bike one.
Step 7 of 13Practice · Code challenge · Python
Write mae(actual, predicted) that returns the mean absolute error between two equal-length lists, rounded to 3 decimal places. Then write baseline_mae(actual) that returns the MAE of always predicting the mean of actual, also rounded to 3 decimals.
mae([10, 14, 8], [12, 13, 5])mae([3, 3], [3, 3])mae([1, 2, 3, 4], [2, 2, 2, 2])baseline_mae([10, 14, 8, 12])baseline_mae([1, 2, 3])
Step 8 of 13Practice · Work it out
Actual daily sales are 20, 25 and 30. A model predicts 22, 25 and 27. What is the mean absolute error?
Step 9 of 13Learn
Overfitting and data leakage
Two traps catch almost every beginner.
Overfitting happens when a model learns the noise in the training data instead of the general pattern. A very flexible model can fit training data almost perfectly and then predict new data poorly. The symptom is a big gap: excellent training scores, much worse test scores. Remedies include simpler models, more data, fewer or better features, regularization, and cross-validation: cross_val_score(model, X, y, cv=5) trains and tests on five different splits, so a single lucky split can't fool you. The opposite problem, underfitting, means the model is too simple to capture the real pattern, and it scores poorly on both sets.
Data leakage happens when information that wouldn't be available at prediction time sneaks into training. Examples:
- predicting whether a customer will cancel using a "cancellation_date" column;
- scaling or filling missing values using statistics computed on the whole dataset before splitting, so test information leaks into training;
- randomly splitting time-series data, so the model trains on next week to predict this week.
Leaky models look brilliant in testing and fail in production. Protect yourself: split first, fit every preprocessing step on training data only (scikit-learn Pipelines make this automatic), split time series by date, and be suspicious of results that look too good.
Step 10 of 13Practice · Sort into groups
Classify each situation.
Tap an item, then tap its group (or drag it there).
Step 11 of 13Note
Step 12 of 13Note
Step 13 of 13Practice · Choose one
A model predicting house prices has R² = −0.2 on the test set. What does that mean?
Lesson complete!