LearnPy Hub
Machine LearningAdvancedLesson 32 of 32

ML Project: Regression

1Level 1 · BasicsBasics

In the scikit-learn lesson you built a classifier, a model that picks a group. Many real questions want a number instead: what will this flat sell for, how many units will we sell next month, how far will this disease progress? Predicting a number is called regression. In this lesson you'll carry out a complete regression project from raw data to a prediction for a brand-new house, one numbered step at a time, with code you can run at every step.

The first run downloads pandas, scikit-learn and Matplotlib into your browser, so it can take up to a minute. After that each example runs in a few seconds.

Classification or regression?

ClassificationRegression
The target isa category: "pass" / "fail", "spam" / "not spam"a number: price, temperature, marks
Example questionWhich species is this flower?How much is this house worth?
Typical modelsKNeighborsClassifier, LogisticRegressionLinearRegression, RandomForestRegressor
How we score itaccuracy, confusion matrixMAE, RMSE, R² (this lesson)

The good news: the scikit-learn pattern doesn't change. You still create a model, fit it on X and y, and predict. Only the models and the scores are different.

The seven steps of a regression project

StepWhat you doMain tools
1. Load the dataGet it into a DataFrameload_diabetes, pd.read_csv
2. Explore (EDA)Size, types, gaps, the target's shape, which features matterinfo(), describe(), corr(), histogram, scatter
3. Clean and preprocessFill gaps, encode text, handle outliers, scaleSimpleImputer, OneHotEncoder, StandardScaler, Pipeline
4. SplitSeparate features from target; hold back a test settrain_test_split
5. Fit modelsTrain a few different modelsLinearRegression, Ridge, trees, forests
6. EvaluateMeasure errors, compare with a baseline, check overfittingMAE, MSE, RMSE, R², cross_val_score
7. PredictUse the best model on new datamodel.predict(new_rows)

We'll use two datasets. The diabetes dataset ships with scikit-learn: 442 patients, 10 measurements each, and a number showing how far their disease progressed a year later. A small house-price table of flats in Dhaka has the messy parts real data has: missing values, a text column and a typo.

Step 1: load the data

from sklearn.datasets import load_diabetes
data = load_diabetes(as_frame=True)
df = data.frame                 # 10 feature columns + "target"

import io, pandas as pd
houses = pd.read_csv(io.StringIO(csv_text))   # works just like a CSV file

as_frame=True gives you a pandas DataFrame instead of bare arrays, so you get column names and all the pandas tools. io.StringIO makes a piece of text behave like a file, which lets these examples run without any download. On your own computer you'd write pd.read_csv("houses.csv").

Step 2: explore the data (EDA)

Run the EDA checklist from the EDA lesson, then add two questions that matter for regression:

  • What does the target look like? Draw its histogram. Is it spread out or bunched? Very skewed targets (like prices) are often easier to model after a log transform.
  • Which features move with the target? df.corr(numeric_only=True)["target"].sort_values() lists each feature's correlation with the target. A scatter plot of the strongest one shows whether the relationship is roughly a straight line.

Correlation is only a first hint: it misses curved relationships, and a weak feature can still help when combined with others.

Step 3: clean and preprocess

Models only understand complete tables of numbers, so we fix four things:

ProblemFixscikit-learn tool
Missing numbersfill with the medianSimpleImputer(strategy="median")
Missing textfill with the most common valueSimpleImputer(strategy="most_frequent")
Text categoriesone-hot encode: one 0/1 column per categoryOneHotEncoder(handle_unknown="ignore")
Outliers and typosfix, remove, or cap (clip to a sensible range)pandas: IQR rule, .clip()
Very different rangesscale to mean 0, standard deviation 1StandardScaler()

One-hot encoding turns a column like location = "Mirpur" into columns location_Mirpur = 1, location_Gulshan = 0, and so on. We don't just number the areas 1, 2, 3, because the model would think Uttara (3) is "three times" Gulshan (1).

Scaling matters because area is in the thousands while bedrooms is 1 to 5. Linear models with regularisation, and distance-based models like KNN, would otherwise treat the big-number column as more important. Tree models don't care about scale.

Pipelines: preprocessing that can't cheat

Every fill value, category list and scaling factor is learned from data. If it's learned from the test rows too, the test score is no longer honest; this is called data leakage. A ColumnTransformer sends each group of columns through its own steps, and a Pipeline chains that with the model, so that fit learns everything from the training set only and predict reuses it.

from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline, make_pipeline

numbers = make_pipeline(SimpleImputer(strategy="median"), StandardScaler())
text = make_pipeline(SimpleImputer(strategy="most_frequent"),
                     OneHotEncoder(handle_unknown="ignore"))
prep = ColumnTransformer([("num", numbers, ["area", "bedrooms", "age"]),
                          ("cat", text, ["location"])])
model = Pipeline([("prep", prep), ("reg", LinearRegression())])
model.fit(X_train, y_train)     # learns fill values, scaling AND the model

Fixing an obvious typo, or dropping rows with no target, is fine to do before the split, because it doesn't learn anything from the data.

Step 4: separate X and y, then split

X = df.drop(columns="price")     # features: everything except the answer
y = df["price"]                  # target: the number to predict
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42)

For regression we don't use stratify, because there are no classes to balance. Twenty to twenty-five percent for testing is common.

Step 5: fit some models

ModelHow it predictsGood to know
LinearRegressiona weighted sum of the features plus a constantfast and easy to explain; only straight-line patterns
Ridge(alpha=1.0)the same, but keeps the weights smallsteadier when features are related; alpha sets how strongly
DecisionTreeRegressora chain of yes/no questions; each leaf predicts the average of its training rowscaptures curves and thresholds; overfits easily, so limit max_depth
RandomForestRegressorthe average of many different treesusually strong with no tuning; slower and harder to explain

After fitting, a linear model shows what it learned. intercept_ is the starting value (the prediction when every feature is 0), and coef_ holds one coefficient (weight) per feature: how much the prediction changes when that feature goes up by 1 and the others stay the same. If the coefficient for area is 0.06, every extra square foot adds 0.06 lakh taka to the predicted price.

price = intercept_ + coef_[0] × area + coef_[1] × bedrooms + ...

Step 6: evaluate

Each prediction misses the true value by some amount, its error (or residual): actual − predicted. The scores summarise all those errors:

ScoreFormula in wordsIn plain wordsBetter is
MAE (mean absolute error)average of |error|"on average we're off by this much", in the target's own unitslower
MSE (mean squared error)average of error²punishes big misses much more; units are squared, so hard to readlower
RMSE (root MSE)√MSEback in the target's units, but still extra-strict on big misseslower
R² (R-squared)1 − (model's squared error ÷ squared error of always guessing the mean)share of the target's variation the model explains: 1 is perfect, 0 is no better than the mean, below 0 is worsehigher
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
mae = mean_absolute_error(y_test, pred)
rmse = np.sqrt(mean_squared_error(y_test, pred))
r2 = r2_score(y_test, pred)      # same as model.score(X_test, y_test)

Four habits make the numbers trustworthy:

  1. Beat a baseline. A "model" that always predicts the training mean has R² of about 0. Your model must clearly beat it, or it has learned nothing. DummyRegressor(strategy="mean") builds this baseline for you.
  2. Compare models in one table, all scored on the same test set.
  3. Compare train and test scores. A big gap (say train R² 1.00, test R² 0.20) is overfitting: the model memorised the training rows instead of learning the pattern.
  4. Use cross-validation for a steadier estimate. cross_val_score(model, X, y, cv=5, scoring="r2") splits the data five ways, trains five times and scores each held-out part. Report the mean and the spread.

Finally, look at the errors. In a predicted vs actual scatter, a perfect model puts every point on the diagonal line. In a residual plot (error against prediction) you want a shapeless cloud around 0; a curve or a funnel shape means the model is missing a pattern.

Step 7: predict for new data

New rows must have the same columns as X. Because the pipeline remembers every cleaning step, you can pass raw values (even a missing one) straight in:

new = pd.DataFrame([{"area": 1500, "bedrooms": 3, "age": 5, "location": "Uttara"}])
model.predict(new)

Always report a prediction with its typical error: "about 131 lakh taka, give or take 7" (the MAE) is more honest than a single exact-looking number.

Key points: regression predicts a number; follow the seven steps (load, explore, clean, split, fit, evaluate, predict); look at the target and its correlations first; one-hot encode text, fill gaps and scale inside a Pipeline so everything is learned from the training set only; read coef_ and intercept_ to explain a linear model; judge models with MAE, RMSE and R² on the test set, against a mean baseline, with train vs test scores and cross-validation; check the predicted-vs-actual and residual plots; give predictions with their typical error.

Try it yourselfExample 1: Step 1a: load the diabetes dataset

as_frame=True gives a DataFrame with named columns. The features are already centred and scaled by scikit-learn, which is why the numbers are small. The target is a measure of disease progression one year later.

example_1.py
Output appears here

Example 2: Step 1b: load a messy house-price CSV

Flats in Dhaka, prices in lakh taka. There are blank cells, a text column (location) and one suspicious area of 15000 square feet. We'll find and fix all of them.

example_2.py
Output appears here

Example 3: Step 2a: first look and the target

info() shows 442 complete rows of numbers, so the diabetes data needs no cleaning. describe() and the histogram show the target runs from about 25 to 346 and leans to the right.

example_3.py
Output appears here

Example 4: Step 2b: which features move with the target?

bmi (body-mass index) and s5 (a blood measurement) have the strongest correlation with the target. The scatter shows a rising but noisy straight-line trend, so a linear model is a sensible first try.

example_4.py
Output appears here

Example 5: Step 3a: clean the house data by hand

The IQR rule flags the area of 15000 (a typo for 1500). We cap it, fill the gaps with the median or the most common value, and one-hot encode location with get_dummies. This shows what each step does; the next example does the same job safely with a pipeline.

example_5.py
Output appears here

Example 6: Step 3b: scaling with StandardScaler

After scaling, every column has mean 0 and standard deviation 1, so area (thousands) and bedrooms (1 to 5) are on the same footing. The scaler learns the mean and spread in fit, and reuses them in transform.

example_6.py
Output appears here

Example 7: Steps 3 + 4: X and y, the split, and a preprocessing pipeline

200 made-up Dhaka flats with gaps and a text column. We split first, then the ColumnTransformer learns fill values, categories and scaling from the training rows only. The output shows the clean numeric table the model will see.

example_7.py
Output appears here

Example 8: Step 5a: what LinearRegression learns

With one feature the model is a straight line: price = intercept + coefficient × area. Here each extra square foot adds about 0.14 lakh taka. The intercept is negative because no flat has an area of 0, so on its own it has no real meaning; it just positions the line. Change the areas in new and see the predictions follow the formula.

example_8.py
Output appears here

Example 9: Step 5b: fit four models

Same split, four models. For linear models, coef_ shows each feature's weight; bmi and s5 get large positive weights, matching the EDA. Notice s1 and s2 jump around between Linear and Ridge: they are strongly related to each other, and Ridge keeps such weights calmer. The tree and the forest learn rules instead of weights, so they have no coef_.

example_9.py
Output appears here

Example 10: Step 6a: MAE, MSE, RMSE and R² (and a baseline)

Each score is worked out by hand and with scikit-learn, so you can see they match. The baseline always predicts the training mean: its R² is about 0, and our model has to beat it.

example_10.py
Output appears here

Example 11: Step 6b: compare models, spot overfitting, cross-validate

The full tree scores a perfect 1.0 on training rows but much worse on the test set: classic overfitting. Limiting its depth helps. Cross-validation (5 splits) gives a steadier R² with its spread.

example_11.py
Output appears here

Example 12: Step 6c: predicted vs actual, and residuals

Left: points near the diagonal are good predictions; the model squeezes its guesses towards the middle, under-predicting the highest values. Right: residuals scattered around 0 with no clear shape mean no big pattern is being missed.

example_12.py
Output appears here

Example 13: Step 7: predict the price of a new house

The whole pipeline (cleaning + model) is fitted once, then used on brand-new flats. The second flat has no area given: the pipeline fills it with the training median. We report each price with the test MAE as its typical error.

example_13.py
Output appears here

Example 14: The whole project in one cell

All seven steps together on the house data: load, a quick look, fix an obvious typo, split, a preprocessing pipeline, three models compared against a baseline with cross-validation, and a prediction from the winner. The typo (14000 sq ft) is why area looks weakly correlated with price in step 2. Here Ridge wins: the prices were made with a straight-line formula, which suits a linear model best. Use it as a template for your own projects.

example_14.py
Output appears here

2Level 2 · IntermediateCurves and regularisation: polynomial features, Ridge and Lasso

When the pattern is a curve

A linear model can only draw a straight line (or a flat plane). If the true relationship bends, for example a flat's price rising faster for bigger flats, the line will always miss. Polynomial features fix this without changing the model: PolynomialFeatures(degree=2) adds new columns such as x² and, with several features, products like area × age. A linear model fitted on those columns can then draw a curve.

from sklearn.preprocessing import PolynomialFeatures
model = make_pipeline(PolynomialFeatures(degree=2), LinearRegression())

The degree controls how bendy the curve can be. Too low and the model underfits (misses the pattern on both train and test). Too high and it overfits: the curve wiggles through every training point and goes wild in between. Always choose the degree by the test or cross-validation score, never the training score.

Regularisation: keeping the weights small

With many features (polynomial features quickly make dozens), a plain linear model can give some features huge weights that cancel each other out. That fits the training data well but generalises badly. Regularisation adds a penalty for large weights, so the model prefers simpler explanations.

ModelPenaltyEffect
Ridge(alpha=...)sum of squared weightsshrinks every weight towards 0, but rarely to exactly 0
Lasso(alpha=...)sum of absolute weightssets weak features' weights to exactly 0: built-in feature selection

alpha is the regularisation strength. alpha near 0 behaves like plain LinearRegression; a very large alpha squashes all weights and the model underfits, predicting little more than the mean. The best value lies in between, and you find it by trying several. Always scale features before Ridge or Lasso, because the penalty treats every weight the same and a feature measured in large units would be unfairly punished less.

Example 15: Polynomial features for a curved pattern

The data follows a curve. Degree 1 (a straight line) underfits, degree 2 matches the true shape, and degree 15 overfits: its training R² is the highest, but its test R² collapses far below 0 as the curve shoots off between the points.

example_15.py
Output appears here

Example 16: Regularisation strength: Ridge alpha

Degree-2 polynomial features turn the 10 diabetes features into 65. With a tiny alpha the weights are huge and the cross-validated R² suffers; a medium alpha gives the best score; a huge alpha shrinks everything and underfits.

example_16.py
Output appears here

Example 17: Lasso picks features for you

As alpha grows, Lasso sets more weights to exactly 0. At alpha 5 half the features are gone while the test R² stays the same; at alpha 20 only bmi, bp and s5 are left, close to the features the EDA pointed to, but the score starts to drop.

example_17.py
Output appears here

3Level 3 · AdvancedTuning and explaining: GridSearchCV and feature importance

Hyperparameters and GridSearchCV

Settings you choose before training, like the polynomial degree, Ridge's alpha or a tree's max_depth, are called hyperparameters. Trying them by hand in a loop gets tedious. GridSearchCV tries every combination in a grid, scores each with cross-validation on the training set, and keeps the best:

from sklearn.model_selection import GridSearchCV
pipe = Pipeline([("poly", PolynomialFeatures()), ("scale", StandardScaler()), ("ridge", Ridge())])
grid = {"poly__degree": [1, 2, 3], "ridge__alpha": [0.1, 1, 10, 100]}
search = GridSearchCV(pipe, grid, cv=5, scoring="r2")
search.fit(X_train, y_train)
search.best_params_, search.best_score_, search.score(X_test, y_test)

To reach a step inside a pipeline, write the step name, two underscores, then the setting: ridge__alpha. The grid above has 3 × 4 = 12 combinations, and with cv=5 that's 60 fits, so keep grids small. The test set stays untouched until the very end; it is scored once, on the winner, so the final number is still honest.

Which features matter? Three ways to ask

MethodWorks forRead it as
Coefficients coef_ (on scaled features)linear modelschange in prediction for a one-standard-deviation rise; the sign gives the direction
feature_importances_trees and forestshow much each feature reduced the error inside the trees; sums to 1
permutation_importanceany model, even a whole pipelinehow much the test score drops when that column is randomly shuffled

Permutation importance is the most honest of the three: if shuffling a column barely hurts the test score, the model wasn't really using it. Tree importances can favour features with many different values, and coefficients only make sense when features are on the same scale. Two warnings for all of them: importance shows what the model relies on, not what causes the target, and two strongly related features can split the importance between them so that each looks weaker than it is.

Example 18: GridSearchCV over a whole pipeline

12 combinations of degree and alpha, each scored by 5-fold cross-validation on the training set. The table shows the top five. Here degree 1 with alpha 10 wins: the curved features did not help on this data, and the search tells us so. The winner is then scored once on the untouched test set.

example_18.py
Output appears here

Example 19: Feature importance three ways

Ridge coefficients (on scaled features), the forest's built-in importances and permutation importance on the test set mostly agree: bmi and s5 lead. Permutation importance also shows several features that barely matter. Look at s1: Ridge gives it a big negative weight, yet shuffling it changes nothing, because s1 and s2 are closely related and cancel each other out.

example_19.py
Output appears here

Example 20: Importance for a full house-price pipeline

permutation_importance works on the whole pipeline, so it reports the original columns (area, location...) rather than the one-hot pieces. Location and area matter most, which matches how these prices were made.

example_20.py
Output appears here
Common mistakeDon't fit the scaler, the imputer or the encoder on the whole dataset before you split. The test rows then help choose the fill values and scaling, so your test score comes out a little too good, and it won't match what happens on truly new data. Split first, put every learned step in a Pipeline, and fit it on the training set only. And never judge a regression model by its training R²: a deep decision tree scores 1.0 there while being poor on new data.
Exercise · predict the output

Three predictions miss by 1, 0 and 2. What does the program print?

from sklearn.metrics import mean_absolute_error
y_true = [3, 5, 8]
y_pred = [4, 5, 6]
print(mean_absolute_error(y_true, y_pred))
Quick quiz · 9 questions
1. Which of these is a regression problem?
2. In y = df["price"] and X = df.drop(columns="price"), what are X and y?
3. Why do we one-hot encode a location column instead of numbering the areas 1, 2, 3?
4. A LinearRegression model has intercept_ 10 and a coefficient of 0.05 for area. What does it predict for an area of 1000 (with no other features)?
5. What does an MAE of 8 lakh taka mean?
6. A model's R² on the test set is 0. What does that tell you?
7. A decision tree has a train R² of 1.00 but a test R² of 0.15. What is happening?
8. Why should the StandardScaler be fitted inside a Pipeline on the training set only?
9. Which code gives the RMSE?
Ready to practice ml project: regression?

Graded problems for this topic are coming soon.

Practice this topic →
Python ML Project: Regression · LearnPy Hub