3.1 What Is Supervised Learning?
Supervised learning uses labeled input-output pairs. The model learns a function from features to a target and adjusts its parameters to minimize prediction error.
- Labeled data: each example has known features and a known target.
- Learning function: the model approximates the relationship.
- Error minimization: training reduces the gap between predictions and actual values.
3.2 Regression
Regression is supervised learning for continuous numerical outcomes. The guide uses examples such as house prices, stock prices, and sales revenue forecasting.
Fast test: If the answer can vary along a number line, think regression. If the answer is a category, think classification.
3.3 Linear Regression
Linear regression assumes a straight-line relationship between independent variables and the target. The slope shows how much the output changes for a unit change in the input; the intercept is the predicted output when the input is zero.
import numpy as np
from sklearn.linear_model import LinearRegression
X = np.array([1200, 1500, 1800, 2100, 2500]).reshape(-1, 1)
y = np.array([220, 270, 320, 370, 420])
model = LinearRegression()
model.fit(X, y)
print(model.predict([[2000]]))
3.4 Polynomial Regression
Polynomial regression handles non-linear relationships by adding higher-degree terms. It is more flexible than linear regression but can overfit when the degree is too high.
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
poly_model = make_pipeline(
PolynomialFeatures(degree=2),
LinearRegression()
)
poly_model.fit(X, y)
3.5 Decision Tree Regression
Decision tree regression splits the data into branches based on feature values. Each leaf predicts a value, usually the average outcome in that region.
- Easy to visualize for small trees.
- Does not require feature scaling.
- Can overfit if the tree grows too deep.
- Cannot extrapolate beyond the range of the training data.
Control complexity: use pre-pruning parameters such as max_depth, max_leaf_nodes, or min_samples_leaf.
3.6 Hands-On Exercise: House Price Prediction
The practical task is to load a housing dataset, preprocess missing values and scales, train linear, polynomial, and decision tree models, evaluate with R2 score and MAE, and visualize predictions against actual values.
Load dataHousing dataset
PreprocessMissing values and scaling
TrainLinear, polynomial, tree
EvaluateR2 and MAE
VisualizePredicted vs actual
Regression Math and Interpretation
The guide introduces regression as learning a function f: X -> Y where Y is continuous. For simple linear regression, the relationship is written as Y = mX + b.
| Term |
Meaning in an answer |
House-price interpretation |
X |
Input feature or features. |
Square footage, bedrooms, location, or age of property. |
Y |
Continuous target value. |
Selling price of the house. |
m |
Slope or coefficient: how much Y changes for a unit change in X. |
Estimated price increase for extra square footage. |
b |
Intercept: predicted Y when X = 0. |
A baseline model value, not always meaningful in the real-world domain. |
least squares |
Chooses parameters that minimize squared prediction errors. |
Fits the line that keeps predicted prices close to actual prices. |
Exam trap: Interpret coefficients only within the model context. A coefficient explains association in the fitted data; it is not automatically proof of real-world causation.
Regression Model Comparison
The chapter asks you to compare linear regression, polynomial regression, and decision tree regression on the same prediction task. A strong answer says how the model learns, when it helps, and where it fails.
| Model |
How it learns |
Strength |
Weakness |
| Linear Regression |
Fits a straight-line relationship using coefficients and an intercept. |
Fast, interpretable, useful when the relationship is roughly linear. |
Underfits curved or highly complex relationships. |
| Polynomial Regression |
Adds powers of features, then fits a linear model on those expanded features. |
Captures non-linear trends while staying equation-based. |
High-degree models can fit noise and generalize badly. |
| Decision Tree Regression |
Splits the feature space into branches; leaves predict an average target value. |
Handles non-linear rules and is easy to explain for shallow trees. |
Can overfit, is sensitive to small data changes, and cannot extrapolate beyond training range. |
Decision Trees: Pruning, Feature Importance, and Extrapolation
The guide explains trees using if/else questions. In regression, those questions split numeric space into regions, and each leaf predicts a value. If a tree is allowed to grow until every leaf is pure, it can memorize the training set.
- Pre-pruning: stop growth early using limits such as
max_depth, max_leaf_nodes, or min_samples_leaf.
- Post-pruning: build a full tree, then remove weak branches; the guide notes scikit-learn focuses on pre-pruning.
- Feature importance: summarizes which features the tree relied on, but it does not show whether a feature pushes the prediction up or down.
- Extrapolation limit: tree regressors cannot predict beyond the range learned from training data; they usually repeat a known leaf value.
Exam trap: A tree that has 100% training accuracy is not automatically excellent. It may simply be deep enough to memorize the training data.
Chapter 3 Extended Code Example: Compare Regression Models
This example follows the guide's house-price exercise: preprocess a dataset, train linear, polynomial, and decision tree regressors, then compare R2 and MAE.
import numpy as np
import pandas as pd
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, r2_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.tree import DecisionTreeRegressor
# Step 1: Small house-price dataset based on the guide's square-footage example.
# Price is measured in thousands, so 320 means $320 000.
df = pd.DataFrame({
"SquareFootage": [1200, 1500, 1800, 2100, 2500, 2800, 3200, np.nan],
"Bedrooms": [2, 3, 3, 4, 4, 4, 5, 3],
"Age": [18, 12, 10, 8, 5, 4, 2, 15],
"Price": [220, 270, 320, 370, 420, 455, 510, 300],
})
# Step 2: Separate features and continuous target.
X = df.drop(columns=["Price"])
y = df["Price"]
# Step 3: Split before fitting imputers, scalers, or models.
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=42
)
# Step 4: Define three models from the chapter.
# Linear regression: interpretable straight-line baseline.
linear_model = make_pipeline(
SimpleImputer(strategy="mean"),
StandardScaler(),
LinearRegression()
)
# Polynomial regression: adds curved feature terms before fitting LinearRegression.
poly_model = make_pipeline(
SimpleImputer(strategy="mean"),
StandardScaler(),
PolynomialFeatures(degree=2, include_bias=False),
LinearRegression()
)
# Decision tree regression: rule-based non-linear model.
# max_depth is pre-pruning; it limits complexity to reduce overfitting.
tree_model = make_pipeline(
SimpleImputer(strategy="mean"),
DecisionTreeRegressor(max_depth=3, random_state=42)
)
models = {
"Linear": linear_model,
"Polynomial degree 2": poly_model,
"Decision tree": tree_model,
}
# Step 5: Train, predict, and compare the same metrics for each model.
for name, model in models.items():
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
print(name)
print(" R2:", round(r2_score(y_test, y_pred), 3))
print(" MAE:", round(mean_absolute_error(y_test, y_pred), 3))
# Step 6: Predict a new house.
# The same fitted preprocessing steps are applied automatically by each pipeline.
new_house = pd.DataFrame({
"SquareFootage": [2000],
"Bedrooms": [3],
"Age": [9],
})
print("Linear prediction:", linear_model.predict(new_house)[0])
Common error: Polynomial regression is still based on linear regression after feature expansion. The "polynomial" part is the transformed input features, not a totally unrelated algorithm.
Chapter 3 Glossary: Regression Algorithms and Evaluation
supervised learning
- Learning from labelled examples where each input has a known output.
f: X -> Y
- The supervised-learning mapping from input features
X to target output Y.
regression
- Supervised learning for continuous numerical targets.
continuous value
- A numeric output that can vary across a range, such as price, income, or sales revenue.
linear regression
- Regression model that fits a linear relationship between independent variables and the target.
Y = mX + b
- Simple linear-regression equation with slope
m and intercept b.
slope
- How much the predicted output changes for a one-unit change in the input.
intercept
- The predicted output when the input value is zero.
least squares
- Parameter-fitting method that minimizes squared differences between actual and predicted values.
polynomial regression
- Regression that adds higher-degree feature terms to model non-linear relationships.
degree
- The highest power used in polynomial features; higher degree means more flexibility and more overfitting risk.
DecisionTreeRegressor
- Scikit-learn tree model for continuous targets.
leaf
- A terminal tree node that stores the final prediction, often an average of training targets in that region.
pre-pruning
- Stopping a tree early using constraints such as
max_depth or min_samples_leaf.
feature_importances_
- Tree attribute showing how much each feature contributed to splits; values are positive and sum to 1.
extrapolation
- Predicting beyond the observed training range; decision trees generally cannot do this well.
R2 score
- Regression score describing how much target variation the model explains.
MAE
- Mean Absolute Error; the average absolute difference between predicted and actual values.