ML600 · Machine Learning 600

Richfield Faculty of Information Technology

Machine Learning 600 Study Hub

Open-book CA reference for Topics 1–4, with click-through code explanations and the full module notes below. No searching required.

Definitions Correct patterns Exam traps Model risks Algorithms & structure

Open-book desk · Topics 1–4

CA Quick Reference

Choose a topic, a task or an API name. Every reference links to its explanation in General Module Content. Coverage is based on your stated CA scope, not a prediction of individual questions.

Exam Focus Areas

Confirmed exam focus areas will be added here once the assessment coverage is available.

Coming soon

Exam focus areas are coming soon

The current exam-focus content has been cleared and will be updated when the confirmed focus areas are provided.

General Module Content

Chapters 1–5 follow the study guide, with worked examples and the Chapter 5 practice tasks. Chapters 1–4 were the stated CA scope; Chapter 5 supports wider module revision.

Chapter 1: Introduction to Machine Learning

ML and AI Modeling Learning types Overfitting Correctness Python libraries

1.1 Overview of Machine Learning

Machine learning is a subfield of artificial intelligence focused on models that learn from data to make predictions without being explicitly programmed for every case. It is used in healthcare, finance, marketing, autonomous systems, cybersecurity, education, agriculture, and entertainment.

Core idea: ML is one part of a broader data workflow that includes collecting, cleaning, transforming, modelling, and evaluating data.

1.2 Modeling

A model represents relationships between variables. In ML, the model learns those relationships from data and can improve as more data becomes available.

  • Business model: profit from revenue and expenses.
  • Recipe model: servings linked to ingredient quantities.
  • Poker model: probability of winning based on revealed cards.

1.3 Types of Machine Learning

The guide separates machine learning by the nature of the available data and output.

SupervisedLabeled data: classification or regression
UnsupervisedNo labels: clusters or anomalies
ReinforcementRewards and penalties from an environment

1.4 Overfitting and Underfitting

Underfitting happens when a model is too simple to capture the real pattern. Overfitting happens when a model is so complex that it learns noise instead of the underlying pattern.

Problem Training performance Unseen-data performance Typical fix
Underfitting Poor Poor Use richer features or a more flexible model.
Overfitting Very strong Poor Simplify, regularize, prune, or add more data.
Good generalization Strong enough Strong enough Balance complexity and error.

1.5 Correctness

Correctness is not just accuracy. The guide uses the confusion matrix to separate prediction outcomes into true positives, false positives, false negatives, and true negatives.

  • Precision: of the predicted positives, how many were correct?
  • Recall: of the actual positives, how many were found?
  • F1 score: harmonic mean that balances precision and recall.
Scenario logic: In medical diagnosis, high recall may matter most because false negatives are dangerous. In spam detection, high precision may matter because false positives can hide important mail.

1.6 The Bias-Variance Tradeoff

Bias is error from a model being too simple. Variance is error from a model being too sensitive to training-data fluctuations. A good model balances both so it generalizes to new data.

Reduce variance: simplify the model, increase training data, or use regularization such as L1/L2 penalties.

1.7 Feature Engineering

Feature extraction transforms raw data into usable numerical representations. Feature selection identifies the most relevant features so the model avoids unnecessary complexity.

  • Extraction: text to vectors, image pixels or edges to numeric features.
  • Selection: statistical filter methods, wrapper methods, recursive feature elimination, forward selection.

1.8 Real-World Applications

The guide lists ML uses in healthcare, finance, retail, transportation, manufacturing, cybersecurity, NLP, education, agriculture, and entertainment.

Memory hook: ML is valuable when large volumes of data can reveal patterns that improve prediction, automation, personalization, or anomaly detection.

1.9 Introduction to Python ML Libraries

The guide introduces NumPy for arrays and numerical computing, Pandas for DataFrame-based dataset work, Scikit-learn for ML models, and Matplotlib for visualizations.

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression

df = pd.read_csv("iris.csv")
X = df.drop(columns=["species"])
y = df["species"]

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)

model = LogisticRegression()
model.fit(X_train, y_train)
print(model.score(X_test, y_test))

Chapter 1 Study Workflow: From Problem to Evaluation

The chapter's foundation is that machine learning is not a single algorithm. It is a workflow: collect and understand data, clean and transform it, train a model to minimize error, then evaluate whether the model generalizes to unseen cases.

ProblemWhat prediction or pattern is needed?
DataInputs, outputs, labels, or no labels
ModelMathematical relationship learned from data
TrainingMinimize error and optimize performance
EvaluationCheck correctness and generalization
Exam trap: Do not describe ML as "the computer magically learns". Say what it learns: a mathematical or probabilistic relationship between variables from training data.

1.8 Application Map: What the Guide Wants You to Recognize

The application section is useful for scenario questions because it links the same ML idea to different industries. When revising, identify the data, the pattern being learned, and the decision being supported.

Area Guide application What the model is learning
Healthcare Medical images, genomics, wearable health monitoring. Patterns that support early diagnosis, personalized treatment, or abnormality detection.
Finance Fraud detection, credit scoring, trading, customer assistants. Risk, anomaly, trend, and default-probability patterns in transaction or market data.
Retail Recommendations, dynamic pricing, inventory and demand forecasting. Customer preference and seasonal demand patterns.
Cybersecurity Threat detection, phishing flags, intrusion detection, spam filtering. Unusual network or message patterns that indicate attacks or misuse.
Agriculture Crop monitoring, plant disease detection, smart irrigation. Soil, weather, image, and sensor patterns linked to crop health and yield.

Chapter 1 Extended Code Example: Iris Classification Starter Pipeline

This commented example follows the guide's Python-library exercise: load the bundled Iris data into a Pandas table (no internet needed), split it with Scikit-learn, train Logistic Regression, and evaluate the result.

from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report

# Step 1: Load the guide's sample Iris dataset.
# Each row is one flower observation; target is the known species code.
iris = load_iris(as_frame=True)
df = iris.frame
print(dict(enumerate(iris.target_names)))  # code-to-species key

# Step 2: Explore before modelling.
# describe() gives count, mean, standard deviation, and range for numeric features.
print(df.head())
print(df.describe())

# Step 3: Separate input features X from output label y.
# Supervised learning needs both known inputs and known outputs during training.
X = df.drop(columns=["target"])
y = df["target"]

# Step 4: Split the data so the model is tested on unseen observations.
# random_state makes the split repeatable when revising or debugging.
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)

# Step 5: Train a classification model.
# LogisticRegression is used here as a simple, interpretable baseline.
model = LogisticRegression(max_iter=200)
model.fit(X_train, y_train)

# Step 6: Evaluate correctness.
# Accuracy is useful here because Iris classes are fairly balanced, but the confusion
# matrix still shows which classes were mixed up.
y_pred = model.predict(X_test)
print("Accuracy:", accuracy_score(y_test, y_pred))
print("Confusion matrix:\n", confusion_matrix(y_test, y_pred))
print(classification_report(y_test, y_pred))
Common error: Scikit-learn expects a two-dimensional feature table for X. A single new flower must still be shaped like one row with four feature columns.
Chapter 1 Glossary: Foundations, Metrics, and Python Terms
machine learning
A subfield of AI where models learn patterns from data to make predictions without explicit rule-by-rule programming.
model
A mathematical or probabilistic representation of relationships between variables.
training dataset
The data used by a supervised algorithm to learn the mapping from inputs to outputs.
supervised learning
Learning from labelled input-output pairs; includes classification and regression.
classification
Supervised prediction of a discrete class, such as spam or not spam.
regression
Supervised prediction of a continuous numeric value, such as income or house price.
unsupervised learning
Learning hidden patterns from data without predefined labels; common tasks include clustering and anomaly detection.
reinforcement learning
Learning through actions, rewards, and penalties while interacting with an environment.
overfitting
When a model learns noise and performs well on training data but poorly on new data.
underfitting
When a model is too simple to capture the underlying pattern and performs poorly even on training data.
bias
Error from a model being too simplistic; high bias usually links to underfitting.
variance
Error from sensitivity to small training-data changes; high variance usually links to overfitting.
TP, FP, FN, TN
The four confusion-matrix outcomes: true positive, false positive, false negative, and true negative.
accuracy
The proportion of all predictions that are correct; weak on imbalanced data when used alone.
precision
Of the predicted positives, the fraction that were actually positive: TP / (TP + FP).
recall
Of the actual positives, the fraction the model found: TP / (TP + FN).
F1 score
The harmonic mean of precision and recall.
feature extraction
Transforming raw data such as text or images into numerical features.
feature selection
Choosing relevant features and removing irrelevant or redundant ones.
NumPy
Python library for arrays, numerical computing, linear algebra, and random-number generation.
Pandas
Python library for dataset handling through structures such as the DataFrame.
Scikit-learn
Python ML library that provides estimators, preprocessing tools, training/test splitting, and metrics.
Matplotlib
Python library used to visualize data, model lines, clusters, and evaluation output.

Chapter 2: Data Preprocessing and Feature Engineering

Structured data Unstructured data Missing values Outliers Scaling PCA

2.1 Understanding Datasets

Before applying ML algorithms, understand the data type, structure, and quality. Structured data is organised in rows and columns. Unstructured data includes text, images, audio, and video.

Data type Format Typical tools or techniques
Structured Tables, spreadsheets and CSV. JSON/XML are commonly semi-structured rather than inherently tabular. SQL, Pandas, standard ML algorithms.
Unstructured Text, image, audio, video. NLP, image analysis, deep learning approaches.

2.2 Data Cleaning

Data cleaning handles missing values, inconsistencies, errors, outliers, and duplicates so the dataset becomes reliable enough for model training.

  • Missing Completely at Random: missingness is independent of observed and missing data.
  • Missing at Random: missingness depends on observed data.
  • Missing Not at Random: missingness depends on the missing value itself.

Fit imputation on training features only; reuse the learned values on test features. Mean imputation is for numeric columns. Treat categorical columns separately (for example, with a most-frequent imputer), and keep the target out of the feature imputer.

import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.impute import SimpleImputer

X = pd.DataFrame({"Age": [21, np.nan, 35, 42, 29],
                  "Income": [30000, 42000, np.nan, 61000, 38000]})
X_train, X_test = train_test_split(X, test_size=0.2, random_state=42)
imputer = SimpleImputer(strategy="mean")
X_train_clean = pd.DataFrame(imputer.fit_transform(X_train),
                             columns=X.columns, index=X_train.index)
X_test_clean = pd.DataFrame(imputer.transform(X_test),
                            columns=X.columns, index=X_test.index)

2.2.2-2.2.3 Outliers and Duplicates

Outliers are unusually distant values. They can be errors or genuine extreme cases. Duplicates repeat observations but may also be legitimate. The percentile rule below flags values for investigation; it does not justify deleting them. Check context before removing outliers or duplicate rows.

import numpy as np

data = np.array([10, 12, 13, 15, 1000])
threshold = np.percentile(data, 95)
candidate_outliers = data[data > threshold]
print(candidate_outliers)

# For an existing DataFrame df, inspect repeated rows before removal:
print(df[df.duplicated(keep=False)])

2.3 Feature Scaling and Normalization

Scaling puts features on comparable ranges. It is important when a model uses distances, gradients, or margins, as with k-NN and SVM.

from sklearn.preprocessing import MinMaxScaler, StandardScaler

data = [[100, 200], [300, 400], [500, 600]]

scaled = MinMaxScaler().fit_transform(data)
standardized = StandardScaler().fit_transform(data)
Exam trap: Scaling should be fitted on the training data, then applied to test data. Do not let test data influence preprocessing choices.

2.4 Principal Component Analysis

PCA is a dimensionality reduction technique that creates principal components, which are new axes capturing maximum variance. It reduces high-dimensional data while retaining as much variance as possible for the chosen number of components; high explained variance does not guarantee high predictive accuracy.

  • Reduces computational cost.
  • Can reduce overfitting risk by removing noisy dimensions.
  • Supports low-dimensional visualization, but component mixtures can be harder to interpret than original features.

2.4.3 Choosing Principal Components

The explained variance ratio tells how much variance each principal component captures. The cumulative explained variance helps decide how many components to keep.

Method How it is used
Scree plot Look for the elbow point where extra components add little value.
Variance threshold Keep enough components to explain about 90-95% of variance.
Cross-validation Try different component counts and compare model performance.

2.5 Applications of PCA

The guide applies PCA to visualizing high-dimensional data such as the breast cancer dataset and to image feature extraction through eigenfaces. PCA can produce a better representation than raw pixel distances for some analysis tasks.

Important interpretation: PCA components are not original columns. They are weighted combinations of original features, so meaning must be explained carefully.

2.2.1 Missing Values: Choose the Method That Fits the Cause

The guide separates missing data by why the gap exists. This matters because a missing value caused by random sensor failure is not the same as a missing value caused by the missing value itself.

Missing-data type Meaning Revision decision
MCAR Missing Completely at Random: the missingness is independent of observed and missing data. Dropping rows may be acceptable if the dataset is still large enough and bias is not introduced.
MAR Missing at Random: the missingness depends on observed data, not the hidden missing value itself. Imputation using related observed variables can be reasonable.
MNAR Missing Not at Random: the missingness depends on the missing value itself. Be careful: simple imputation may hide a meaningful pattern in the missingness.
Exam trap: Never write "just delete missing rows" as a universal answer. The guide says removal is suitable when only a small percentage is missing and removal does not introduce bias.

Preprocessing Selector: What to Do Before Modelling

This chapter is very practical. Most questions ask you to choose the right preprocessing step before an algorithm sees the data.

Problem in the data Guide technique Why it helps
Small number of random missing rows dropna() Prevents contaminated records from entering the model.
Numerical missing values Mean, median, or SimpleImputer Prevents data loss while keeping numeric columns usable.
Categorical missing values Mode imputation Fills with the most frequent category where appropriate.
Complex missing patterns KNNImputer or regression-based prediction Uses other features to estimate missing values.
Extreme values Remove, transform, cap, or robust-scale Reduces distortion from errors or very unusual observations.
Different feature ranges MinMaxScaler or StandardScaler Prevents large-scale features from dominating distance-based models.
Too many correlated features PCA Creates fewer principal components while preserving variance.

2.4 PCA: What Actually Happens to the Features?

PCA is not simple column deletion. Scikit-learn PCA centres the input but does not automatically scale features to unit variance. Use a separately fitted StandardScaler when comparable feature scales are appropriate; PCA then finds directions of maximum variance and projects data onto the retained directions. High variance does not necessarily mean high predictive value.

  • Why reduce dimensions: high-dimensional data increases computation, raises overfitting risk, and makes relationships harder to interpret.
  • What components are: principal components are new axes and are linear combinations of the original features.
  • Why scaling matters: PCA is variance-based, so unscaled features with large ranges can dominate the components.
  • How to choose components: use the scree plot elbow, a 90-95% cumulative explained-variance threshold, or cross-validation.
Worked interpretation: In the guide's correlated-feature example, PC1 captured almost all the variance while PC2 contributed very little. That means one new axis represented most of the useful variation.

PCA applications: variance, whitening and reconstruction

The guide's cancer example reduces 30 features for visualisation. Its eigenfaces example learns directions in pixel space and represents each face by component scores. These representations can help downstream models, but improved prediction is not guaranteed.

components_ contains axes, while transform(X) contains observation scores. An eigenvalue measures variance; its fraction of total variance is the eigenvalue divided by the sum of all eigenvalues. Add explained_variance_ratio_ values to find the retained fraction. A scree plot shows individual variances; a cumulative plot helps choose a retention threshold.

whiten=True rescales retained component scores to unit variance. It removes their relative variance scales and may help a distance-based downstream model. inverse_transform reconstructs inputs using the retained directions; discarded information is lost. More components usually retain more detail. PCA can aid visualisation while making individual feature interpretation harder.

from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
import numpy as np

# X_train / X_test must already be separated and missing values handled.
scaler = StandardScaler()
X_train_s = scaler.fit_transform(X_train)
X_test_s = scaler.transform(X_test)
pca = PCA(n_components=0.95, svd_solver="full", whiten=True)
Z_train = pca.fit_transform(X_train_s)
Z_test = pca.transform(X_test_s)
print(pca.components_.shape)
print(np.cumsum(pca.explained_variance_ratio_))
reconstructed_s = pca.inverse_transform(Z_test)
reconstructed_original_units = scaler.inverse_transform(reconstructed_s)

Study guide §2.5, PDF pp. 35–44. API clarification: official PCA documentation.

Chapter 2 Extended Code Example: Cleaning, Scaling, and PCA

This example joins the guide's missing-value, scaling, and PCA sections into one practical preprocessing workflow.

import numpy as np
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.impute import SimpleImputer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

# Step 1: Create a small structured dataset.
# Each row is an observation and each column is a feature.
data = {
    "Age": [25, 30, np.nan, 45, 50, 38],
    "Salary": [50000, np.nan, 60000, 80000, 90000, 72000],
    "SpendingScore": [62, 70, 65, 40, 35, 50],
    "OnlineVisits": [12, 15, 13, 4, 3, 8],
}
df = pd.DataFrame(data)

# Step 2: Split before fitting preprocessing objects.
# This avoids test-data leakage: the test set must not influence imputation or scaling.
X_train, X_test = train_test_split(df, test_size=0.33, random_state=42)

# Step 3: Build a preprocessing pipeline.
# SimpleImputer fills missing values with training-column means.
# StandardScaler gives each feature comparable mean and variance.
# PCA then rotates the scaled features into principal components.
preprocess = make_pipeline(
    SimpleImputer(strategy="mean"),
    StandardScaler(),
    PCA(n_components=2)
)

# Step 4: Fit only on training data, then transform both sets in the same way.
X_train_pca = preprocess.fit_transform(X_train)
X_test_pca = preprocess.transform(X_test)

# Step 5: Inspect explained variance to decide whether enough information remains.
pca = preprocess.named_steps["pca"]
print("Training data after PCA:\n", X_train_pca)
print("Test data after PCA:\n", X_test_pca)
print("Explained variance ratio:", pca.explained_variance_ratio_)
print("Total retained variance:", pca.explained_variance_ratio_.sum())
Common error: Do not call fit_transform() separately on training and test sets. Fit preprocessing on training data, then call transform() on test data using the same fitted rules.
Chapter 2 Glossary: Data Cleaning, Scaling, and PCA
structured data
Data organised under a tabular schema, such as database tables, spreadsheets and CSV. JSON/XML are commonly semi-structured.
unstructured data
Data without a predefined tabular schema, such as text, images, audio, and video.
observation
One row or data instance in a dataset.
attribute / feature
A column describing one measurable property of an observation.
data cleaning
Handling missing values, inconsistencies, errors, outliers, and duplicates before model training.
MCAR
Missing Completely at Random; missingness is independent of observed and missing values.
MAR
Missing at Random; missingness depends on observed data.
MNAR
Missing Not at Random; missingness depends on the missing value itself.
imputation
Filling missing values instead of removing the whole row or column.
mean, median, mode
Common statistical imputation choices for numerical or categorical data.
SimpleImputer
Scikit-learn class for filling missing values using strategies such as mean, median, or most frequent.
KNNImputer
Imputation method that estimates missing values from nearby observations.
outlier
A data point significantly different from the rest; it may be an error or a genuine extreme case.
feature scaling
Putting features on comparable ranges so algorithms do not become biased toward large-scale columns.
MinMaxScaler
Scales features into a chosen range, commonly 0 to 1.
StandardScaler
Standardizes features by centering around mean 0 and scaling to unit variance.
RobustScaler
Scaler based on median and quartiles, making it less sensitive to outliers.
Normalizer
Scales each observation vector to length 1, useful when direction matters more than magnitude.
dimensionality reduction
Reducing the number of input features while retaining important information.
PCA
Principal Component Analysis; transforms data into principal components that capture maximum variance.
principal component
A new axis made from a linear combination of original features.
explained_variance_ratio_
Scikit-learn PCA attribute showing how much variance each component captures.
inverse_transform()
Returns transformed PCA data back toward the original feature space for reconstruction or interpretation.

Chapter 3: Supervised Learning - Regression Algorithms

Labeled data Continuous output Linear regression Polynomial degree Decision trees R2 and MAE

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.
  • Accepts feature values outside the training range, but cannot continue a rising or falling target trend there; a leaf predicts a constant value.
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 continue a target trend beyond the training feature 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: grow a tree, then remove weak branches. The study guide's statement that scikit-learn only supports pre-pruning is outdated: current versions support cost-complexity pruning using ccp_alpha. Larger values generally give smaller trees.
  • 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: a standard mean-leaf regression tree accepts inputs outside the observed feature range, but predicts a constant leaf mean within the training target range; it cannot extend a continuing trend.
Exam trap: A tree that has 100% training accuracy is not automatically excellent. It may simply be deep enough to memorize the training data.

Regression assumptions, residuals and evaluation

A residual is actual − predicted. A curved residual pattern suggests unmodelled structure; a fan-shaped spread suggests nonconstant error variance (heteroscedasticity). The guide names linearity, independence, constant error variance and normally distributed errors. Normal-error assumptions support conventional inference; normality is not required simply to compute least-squares predictions. Coefficients describe conditional associations, not automatically causal effects.

MAE: average absolute error. Actual values [100, 200, 300] and predictions [110, 180, 310] give (10+20+10)/3 = 13.33 target units. R²: 1 − SSE/SST. Here SSE=600 and SST=20,000, so R²=0.97. For nonconstant targets, R²=0 matches predicting the evaluation-set mean; negative scores are possible. Constant targets make the raw denominator zero, and scikit-learn handles that special case through force_finite.

Use the same held-out observations for comparisons. Tune on training/validation data; reserve the test set for the final assessment. Similar train/test scores do not by themselves establish underfitting: also assess absolute performance and suitable baselines.

Show larger worked example with plots
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler, PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import mean_absolute_error, r2_score
import matplotlib.pyplot as plt

# Supporting bundled dataset: no network download required.
X, y = load_diabetes(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42)
models = {
    "Linear": make_pipeline(StandardScaler(), LinearRegression()),
    "Polynomial": make_pipeline(StandardScaler(),
        PolynomialFeatures(degree=2, include_bias=False), LinearRegression()),
    "Tree": DecisionTreeRegressor(max_depth=3, random_state=42),
}
for name, model in models.items():
    model.fit(X_train, y_train)
    predicted = model.predict(X_test)
    print(name, "train R²:", model.score(X_train, y_train),
          "test R²:", r2_score(y_test, predicted),
          "MAE:", mean_absolute_error(y_test, predicted))
predicted = models["Linear"].predict(X_test)
fig, axes = plt.subplots(1, 2)
axes[0].scatter(y_test, predicted)
axes[0].set(xlabel="Actual", ylabel="Predicted")
axes[1].scatter(predicted, y_test - predicted)
axes[1].axhline(0, color="red")
axes[1].set(xlabel="Predicted", ylabel="Residual")
plt.tight_layout()
plt.show()

Classification trees are also in Topic 3

The guide moves from regression trees to classification trees, including a breast-cancer example (PDF page 56 / printed page 54). DecisionTreeClassifier splits to improve class purity; a leaf predicts its most probable class. In contrast, a standard squared-error DecisionTreeRegressor predicts a leaf's mean target.

Shallow trees can be read as rules. Deep trees may memorise data; use max_depth, min_samples_leaf or pruning. Current scikit-learn supports cost-complexity post-pruning through ccp_alpha, unlike the guide's older statement. Current pruning documentation.

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, plot_tree, export_graphviz
import matplotlib.pyplot as plt

data = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(
    data.data, data.target, stratify=data.target, random_state=42)
tree = DecisionTreeClassifier(max_depth=4, random_state=42)
tree.fit(X_train, y_train)
print("Train / test:", tree.score(X_train, y_train), tree.score(X_test, y_test))
plt.figure(figsize=(16, 8))
plot_tree(tree, feature_names=data.feature_names,
          class_names=data.target_names, filled=True)
plt.show()
dot_text = export_graphviz(tree, out_file=None,
    feature_names=data.feature_names, class_names=data.target_names)

Chapter 3 Extended Code Example: Compare Regression Models

This small example demonstrates the mechanics of preprocessing and comparing R2 and MAE. It is not a reliable benchmark: eight houses leave only two test observations, and polynomial expansion is especially prone to overfitting. Use a larger dataset and validation for meaningful comparison.

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_
Nonnegative, normalised reductions in split impurity. Values normally sum to 1; a tree with no effective splits can have all-zero importance. Importance is neither causal influence nor the direction of an effect.
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.

Chapter 4: Supervised Learning - Classification Algorithms

Categorical labels Decision boundary Logistic regression k-NN distance SVM margin Imbalanced metrics

4.1 Classification

Classification predicts categorical outcomes. A decision boundary separates categories in feature space. Common applications include fraud detection, automated decision-making, and medical diagnostics.

4.2 Logistic Regression

Logistic regression is a linear classification algorithm that predicts the probability of class membership. It is commonly used as an interpretable baseline for binary classification.

For binary classification, z = β₀ + Σβⱼxⱼ and the sigmoid gives P(y=1|X) = 1 / (1 + exp(−z)). A threshold such as 0.5 converts probability to a label; changing the threshold changes the false-positive/false-negative balance.

from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score

model = LogisticRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
print(accuracy_score(y_test, y_pred))

4.3 k-Nearest Neighbors

k-NN stores the training dataset and classifies a new point by looking at the majority class among its k closest neighbors, often using Euclidean distance.

  • Lazy learning: no heavy training phase.
  • Distance based: scaling matters.
  • Curse of dimensionality: performance can weaken with many features.
from sklearn.neighbors import KNeighborsClassifier

knn = KNeighborsClassifier(n_neighbors=5)
knn.fit(X_train, y_train)
print(knn.score(X_test, y_test))

4.4 Support Vector Machines

SVM balances a wide separating margin with permitted violations. Support vectors influence the boundary and may lie on or inside the margin, including misclassified observations. Kernels such as RBF allow non-linear separation.

Parameter trap: In Logistic Regression and LinearSVC, larger C means less regularization and a more flexible model. Smaller C means stronger regularization and a simpler model.

4.4.1 Strengths, Weaknesses, and Parameters

Linear models train and predict quickly, scale well to large and sparse datasets, and are easy to express mathematically. Their coefficient interpretation can become unclear when features are highly correlated.

  • Use L1 regularization when only a few features are expected to matter.
  • Use L2 regularization as the usual default when many features may contribute.
  • Search regularization values on a logarithmic scale.

4.4.2 Evaluation Metrics for Classification

Classification metrics explain different kinds of correctness.

Metric Meaning Use when
Accuracy Overall proportion of correct predictions. Classes are balanced and errors have similar cost.
Precision Correct predicted positives divided by all predicted positives. False positives are costly.
Recall Correct predicted positives divided by all actual positives. False negatives are costly.
F1 score Harmonic mean of precision and recall. You need a balanced precision-recall summary.
ROC curve Plots true-positive rate (sensitivity) against false-positive rate (1 − specificity) across thresholds. You need to compare thresholds.

Classification Map: What Changes from Regression?

The guide defines classification as supervised learning for categorical outcomes. The model learns f: X -> Y, but now Y is a label such as spam/non-spam, fraud/not fraud, disease/no disease, or an iris species.

Idea Classification answer Regression contrast
Target Discrete class label. Continuous numeric value.
Output wording "Classify", "detect", "identify", "diagnose". "Predict price", "estimate sales", "forecast value".
Boundary A decision boundary separates categories in feature space. A fitted line, curve, or tree leaf predicts numeric values.
Evaluation Accuracy, precision, recall, F1, ROC curve. R2, MAE, residuals, prediction-vs-actual plots.
Exam trap: Logistic Regression is a classification algorithm even though its name contains "Regression". It predicts class probability through the logistic/sigmoid function.

Classification Algorithm Selector

The chapter groups several common classifiers. For exam answers, name what the algorithm uses to classify and what problem can weaken it.

Algorithm Main idea from the guide Good fit Watch out for
Logistic Regression Uses a linear model and sigmoid probability for binary classification. Medical or financial tasks where interpretability matters. Linear decision boundaries can underfit complex patterns.
k-NN Stores the training set and uses majority vote among nearest neighbors. Simple, well-distributed datasets such as Iris measurements. Scaling and high dimensionality strongly affect distance.
SVM Finds a margin-maximizing hyperplane using support vectors. High-dimensional spaces such as text classification or image recognition. Kernel and regularization choices affect flexibility and overfitting.
LinearSVC Linear margin-based classifier controlled by C. Large sparse feature spaces. Coefficient interpretation can be unclear when features are correlated.

Regularization, C, and Multiclass Logic

The guide spends extra time on linear classifiers because they are fast, scalable, and interpretable, but their parameters need careful reading.

  • C in LogisticRegression and LinearSVC: larger C means less regularization and a more flexible model; smaller C means stronger regularization and a simpler model.
  • L2 regularization: default-style penalty that shrinks coefficients but usually keeps many features active.
  • L1 regularization: can push some coefficients to zero, which helps when only a few features are expected to matter.
  • One-vs-rest: trains one binary classifier per class; the class with the highest score wins.
  • Coefficient caution: a coefficient sign can change when regularization changes or features are correlated, so interpret it carefully.

Metric Traps: Match the Metric to the Error Cost

The classification metrics section builds directly on the confusion matrix. A strong exam answer names the metric and explains which type of error it controls.

Metric Formula or idea Best exam wording
accuracy (TP + TN) / total Use when classes are balanced and error costs are similar.
precision TP / (TP + FP) Use when false positives are costly.
recall TP / (TP + FN) Use when false negatives are costly.
F1-score Harmonic mean of precision and recall. Use when you need a balanced precision-recall summary.
ROC curve Plots true-positive rate (sensitivity) against false-positive rate (1 − specificity) across thresholds. Use when comparing threshold behavior matters.

k-NN and SVM: parameters, shapes and decisions

k-NN: calculate distances to stored training samples, choose k neighbours and vote. Euclidean distance is √Σ(xⱼ−qⱼ)². Small k gives flexible, high-variance decisions; large k smooths the boundary and can underfit. weights="distance" gives nearer neighbours more influence than uniform voting. Fitting still matters: it stores/indexes the observations. Scale features first so units do not dominate distances.

SVM: a linear boundary has w·x+b=0. Soft-margin optimisation balances a wide margin with violations; support vectors include points on/inside the margin and can include misclassified points. C is inverse regularisation strength: smaller C allows a stronger preference for regularisation. With an RBF kernel, gamma controls locality; large gamma may create intricate boundaries. Neither larger C nor gamma guarantees better test performance.

SVC supports kernels and trains multiclass one-vs-one internally, even with one-vs-rest-shaped output scores. LinearSVC uses a different linear solver and ordinarily one-vs-rest. Logistic regression can use multinomial fitting with compatible solvers; do not apply a single multiclass rule to every estimator. SVC documentation.

For one new Iris flower, use [[5.0, 2.9, 1.0, 0.2]], shape (1,4), not a bare four-value vector. Predict using the fitted pipeline so scaling remains consistent. Array shape walkthrough.

Classification metrics: labelled worked example

Declare class 1 positive. Scikit-learn's confusion matrix has actual labels as rows and predicted labels as columns. With labels=[0,1]:

Actual / predictedNegative (0)Positive (1)
Negative (0)TN = 50FP = 10
Positive (1)FN = 5TP = 40
  • Accuracy = (40+50)/105 = 85.7%.
  • Precision = 40/(40+10) = 80%: of predicted positives, how many were correct?
  • Recall / sensitivity / TPR = 40/(40+5) = 88.9%: of actual positives, how many were found?
  • F1 = 80/(80+10+5) = 84.2%.
  • Specificity = 50/60 = 83.3%; FPR = 10/60 = 16.7%.

classification_report includes support (actual class count), macro averages (equal weight to each class), and weighted averages (weighted by support). High weighted scores may hide weak minority-class results. Specify zero_division deliberately when metrics have a zero denominator.

ROC: plot FPR on x and TPR on y across thresholds. Supply positive-class probabilities or decision scores, not just predicted labels. ROC AUC measures ranking, not accuracy at one threshold. The basic roc_curve function is binary; multiclass needs an explicit strategy. ROC documentation.

from sklearn.metrics import roc_curve, roc_auc_score
# Binary model; ensure column j represents the positive class 1.
j = list(model.classes_).index(1)
scores = model.predict_proba(X_test)[:, j]
fpr, tpr, thresholds = roc_curve(y_test, scores, pos_label=1)
auc = roc_auc_score(y_test, scores)
# For a binary LinearSVC, use decision_function instead of predict_proba.

Recognition only: Topic 4's outcomes name Random Forest (an ensemble of randomised decision trees) and Naive Bayes (probabilistic classification using conditional-independence assumptions). The body does not develop these comparably to logistic regression, k-NN and SVM; that is a scope ambiguity, not proof they are excluded from the CA.

Chapter 4 Extended Code Example: Logistic Regression, k-NN, and SVM

This example uses a labelled dataset and compares the chapter's main classifiers with shared metrics.

from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC

# Step 1: Load the Iris dataset.
# It has four input measurements and three known species labels.
iris = load_iris()
X = iris.data
y = iris.target

# Step 2: Split into training and testing sets.
# The test set estimates how well each model generalizes.
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)

# Step 3: Build classifiers from the chapter.
# Logistic Regression: interpretable linear baseline.
# k-NN: distance-based majority vote, so scaling is important.
# SVM: margin-based classifier; RBF kernel can handle non-linear boundaries.
models = {
    "Logistic Regression": make_pipeline(
        StandardScaler(),
        LogisticRegression(max_iter=300, C=1.0)
    ),
    "k-NN": make_pipeline(
        StandardScaler(),
        KNeighborsClassifier(n_neighbors=5)
    ),
    "SVM RBF": make_pipeline(
        StandardScaler(),
        SVC(kernel="rbf", C=1.0, gamma="scale")
    ),
}

# Step 4: Train and evaluate using the same test set.
for name, model in models.items():
    model.fit(X_train, y_train)
    y_pred = model.predict(X_test)
    print("\n", name)
    print("Accuracy:", round(accuracy_score(y_test, y_pred), 3))
    print("Confusion matrix:\n", confusion_matrix(y_test, y_pred))
    print(classification_report(y_test, y_pred, target_names=iris.target_names))

# Step 5: Predict one new flower.
# The nested list is one row with four feature values.
new_iris = [[5.0, 2.9, 1.0, 0.2]]
predicted_class = models["k-NN"].predict(new_iris)[0]
print("Predicted iris species:", iris.target_names[predicted_class])
Common error: k-NN and SVM are scale-sensitive. Without scaling, a feature with a larger numeric range can dominate distance or margin calculations.
Chapter 4 Glossary: Classification Algorithms and Metrics
classification
Supervised learning task where the target is a categorical label.
categorical outcome
A discrete class such as spam/non-spam, fraud/not fraud, or setosa/versicolor/virginica.
decision boundary
The line, plane, or surface that separates classes in feature space.
logistic regression
Linear classifier that predicts class probability and is commonly used for binary classification.
sigmoid
The logistic function that maps a model score into a probability-like value between 0 and 1.
binary classification
Classification between two classes.
multiclass classification
Classification among more than two classes.
k-NN
k-Nearest Neighbors; predicts from the majority class among the k nearest training points.
Euclidean distance
Distance measure commonly used by k-NN to find nearby points.
lazy learning
Model style where little training happens upfront; k-NN mainly stores the training set and computes during prediction.
curse of dimensionality
The problem that distance-based methods can weaken when many features make points harder to compare meaningfully.
SVM
Support Vector Machine; classifier that seeks a margin-maximizing hyperplane.
support vectors
Training points closest to the decision boundary that define the SVM margin.
hyperplane
The separating boundary used by a linear SVM, written in the guide as wX + b = 0.
kernel trick
Technique that lets SVM separate non-linear data by working in a transformed feature space.
RBF kernel
Common SVM kernel for non-linear decision boundaries.
C
Regularization parameter in LogisticRegression and LinearSVC; higher means less regularization.
L1
Regularization that can reduce some coefficients to zero, helping with feature selection.
L2
Regularization that shrinks coefficients while usually keeping many features active.
one-vs-rest
Multiclass strategy that trains one binary classifier for each class against all other classes.
accuracy_score
Scikit-learn metric for overall correct predictions.
classification_report
Scikit-learn report showing precision, recall, F1-score, and support per class.

General code walkthroughs · Topics 1–4

Supporting explanations for the clickable API reference. Examples are illustrative unless a complete dataset setup is provided. Imports: import numpy as np, import pandas as pd, import matplotlib.pyplot as plt.

Creating and loading data

A NumPy array is a numerical container; a pandas DataFrame adds row/column labels and allows different column types. A dictionary of equally sized lists creates a table, while a nested list passed to np.array creates a matrix. pd.read_csv parses a CSV into a DataFrame; inspect inferred types and missing-value markers before modelling.

Scikit-learn's built-in dataset loaders return Bunch objects with data, target and descriptive metadata; return_X_y=True returns two arrays instead. Iris has 4 features and 3 classes; breast cancer has 30 features and 2 classes; digits provides both flattened rows and 2D images. These bundled datasets avoid network downloads.

from sklearn.datasets import load_iris
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df["target"] = iris.target
X = df.drop(columns=["target"])
y = df["target"]
Back to create/load reference

Inspect before modelling

head previews records, info prints schema and non-null counts, and describe summarises distributions. shape reports dimension lengths; ndim counts dimensions; size counts elements. NumPy dtype describes an array's element type; pandas dtypes reports each column's type. Attributes do not take parentheses.

print(df.head())
df.info()  # prints a summary, returns None
print(df.describe())
print(df.shape, df.dtypes, df.columns)
print(df.isna().sum())
Back to inspection reference

Array shapes, selection and reshaping

The models here expect X shaped (n_samples, n_features). For ordinary single-target problems y is usually (n_samples,). Three house areas are three observations of one feature, not one observation with three features. reshape keeps the elements and changes their arrangement; one -1 infers a dimension from the element count. Total size must remain compatible.

values = np.array([1200, 1500, 1800])
print(values.shape)                   # (3,)
print(values.reshape(-1, 1).shape)    # (3, 1): 3 houses, 1 feature
print(values.reshape(1, -1).shape)    # (1, 3): 1 sample, 3 features
one_new_house = np.array([[2000]])    # (1, 1)
X = np.array([[1, 2], [3, 4], [5, 6]])
print(X[:, 0])                        # [1, 3, 5], shape (3,)
print(X[:, [0]])                      # column table, shape (3, 1)
print(X[0])                           # first row
print(X.T.shape)                      # (2, 3)

ravel flattens, sharing data when possible; flatten always returns a copy. Neither should be used to erase sample boundaries accidentally. A 1D array's .T remains 1D. hstack joins matching 2D feature blocks horizontally. With pandas, df["Age"] returns a Series but df[["Age"]] returns a one-column table. loc selects labels/masks (label slice endpoints included); iloc selects positions (slice stop excluded).

A Boolean mask selects only matching records: df.loc[df["Age"] >= 18, ["Age"]]. Combine masks using parenthesised expressions and &/|. In indexing, -1 means the last position, not inferred length. NumPy reshape reference.

Back to reshape card

Missingness, summaries and clean subsets

isna creates a Boolean mask; summing counts True values. dropna removes incomplete rows/columns, whereas fillna replaces values. drop(columns=[...]) removes named columns regardless of missingness. These ordinarily return new objects: assign the result. Learn imputation values on training data only.

Mean is sensitive to outliers; median is more robust; mode may return multiple values or an empty result. Pandas numeric summaries normally skip missing entries, while ordinary NumPy percentile does not. duplicated flags repeats and drop_duplicates removes them; check whether repetition is legitimate before deleting. A percentile cutoff identifies a distribution tail, not automatically a data error.

print(df.isna().sum())
X = df.drop(columns=["target"])
y = df["target"]
# After splitting X into training and test tables:
replacement = X_train["Age"].median()
train_age = X_train["Age"].fillna(replacement)
test_age = X_test["Age"].fillna(replacement)
a = np.array([[1, 2], [3, 4]])
print(a.sum(axis=0))  # [4, 6]: column totals
print(a.sum(axis=1))  # [3, 7]: row totals
Back to cleaning reference

Splits and pipelines: one consistent workflow

train_test_split(X,y) returns X_train, X_test, y_train, y_test in that order. test_size controls the held-out fraction; random_state makes a random split reproducible; stratify=y preserves approximate class proportions when feasible. Regression targets are not class strata. Random splitting is not suitable for every time-ordered or grouped dataset.

A Pipeline fits its intermediate transformers on training data and passes their outputs to the final estimator. Prediction reuses those transformers. make_pipeline supplies lowercase names automatically; Pipeline accepts explicit (name, estimator) pairs. named_steps accesses a component. During cross-validation, fit the entire pipeline inside each training fold.

from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
X_train, X_test, y_train, y_test = train_test_split(
    X, y, stratify=y, test_size=0.2, random_state=42)
model = make_pipeline(SimpleImputer(strategy="median"),
    StandardScaler(), LogisticRegression(max_iter=1000))
model.fit(X_train, y_train)
predictions = model.predict(X_test)
print(model.named_steps["logisticregression"].coef_)
Back to pipeline reference

Fit, predict and score are different operations

fit(X_train,y_train) learns an estimator and returns that estimator. predict(X_test) returns labels for classifiers or numbers for regressors. predict_proba, where available, gives columns ordered by classes_; decision_function returns scores, not probabilities. SVC needs probability=True before fitting to expose probabilities; LinearSVC has no probability method.

The classifiers in Topics 1–4 use accuracy for score; LinearRegression and DecisionTreeRegressor use R². A Pipeline delegates this to its final estimator. Maintain the same feature order and representation at prediction time. A new sample is still a row of a 2D table.

Back to train/predict reference

Parameters, learned attributes and interpretation

Constructor parameters such as n_neighbors, max_depth and C are choices made before training. Attributes such as coef_, classes_, components_ and feature_importances_ are learned results, typically available after fit. They are read without parentheses. shape is also an attribute but is not a learned estimator parameter.

Linear coefficients depend on units and correlations. A PCA component is a direction, not an observation. Class labels determine probability-column order. Tree importance is not a signed or causal effect. Inspect a pipeline's estimator through named_steps, not by assuming the pipeline exposes every internal attribute.

Back to learned-results reference

Plots and synthetic examples

Use scatter for points; plot connects points in supplied order; hist shows a distribution; imshow displays a pixel array. subplots returns a Figure and Axes (or an array of Axes). Label axes/units, add a title and use labelled series for a legend. show displays the figure.

For a smooth one-feature regression curve, generate a column grid using linspace(...).reshape(-1,1), predict on that grid, and plot in ascending x order. argsort returns sorting indices for existing observations. For a decision tree use plot_tree, or export DOT text with the guide's export_graphviz.

# model must be fitted on one feature for this particular curve example.
grid = np.linspace(X[:, 0].min(), X[:, 0].max(), 100).reshape(-1, 1)
plt.scatter(X[:, 0], y, label="Observed")
plt.plot(grid[:, 0], model.predict(grid), label="Fitted")
plt.xlabel("Feature value")
plt.ylabel("Target value")
plt.title("One-feature regression")
plt.legend()
plt.show()
# Guide-style synthetic data; seed makes the draws reproducible.
np.random.seed(42)
synthetic_X = np.random.rand(100, 2)
noise = np.random.randn(100, 1)

rand draws uniform values on [0,1); randn draws standard-normal values. Modern code can use an independent np.random.default_rng. Synthetic exercises demonstrate mechanics, not evidence of real-world performance.

Back to plotting reference

Chapter 5: Unsupervised Learning - Clustering Algorithms

Unlabeled data Clustering k-Means k Dendrograms DBSCAN noise Silhouette

5.1 Introduction

Unsupervised learning finds patterns in unlabeled data. It is useful when labels are unavailable but hidden structure may still support segmentation, anomaly detection, or exploration.

5.2 Clustering

Clustering groups similar data points so intra-cluster similarity is high and inter-cluster similarity is low. Cluster labels are arbitrary: cluster 0 does not inherently mean anything until you inspect the group.

Exam trap: Clustering produces group assignments, but there is no ground-truth label by default. Do not interpret cluster numbers as meaningful names without analysis.

5.3 k-Means Clustering

k-Means is a centroid-based algorithm. It chooses k centroids, assigns points to the nearest centroid, updates centroids to the mean of assigned points, and repeats until cluster assignments stop changing.

  1. Choose the number of clusters k.
  2. Randomly initialize k centroids.
  3. Assign each point to its nearest centroid.
  4. Update each centroid using the mean of its assigned points.
  5. Repeat until convergence.
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler

df_scaled = StandardScaler().fit_transform(df)
kmeans = KMeans(n_clusters=3, random_state=42)
df["Cluster"] = kmeans.fit_predict(df_scaled)

5.4 Hierarchical Clustering

Hierarchical clustering creates nested clusters shown as a tree-like dendrogram. Agglomerative clustering starts with each point as its own cluster and merges the most similar clusters until the stopping condition is reached.

  • Ward: minimizes variance increase and often creates similar-sized clusters.
  • Average: uses average distance between all points in two clusters.
  • Complete: uses the smallest maximum distance between points in two clusters.

5.5 Density-Based Clustering (DBSCAN)

DBSCAN identifies dense regions and separates noise points. It does not require a predefined k and can find arbitrary-shaped clusters.

  • eps: neighborhood radius.
  • min_samples: minimum points needed to form a dense region.
  • Noise: points not assigned to a dense cluster.
from sklearn.cluster import DBSCAN

dbscan = DBSCAN(eps=0.5, min_samples=5)
df["DBSCAN_Cluster"] = dbscan.fit_predict(df_scaled)

5.6 Clustering Evaluation Metrics

Because clustering is unsupervised, ordinary accuracy is not the main evaluation method. The guide lists internal evaluation methods.

Metric Meaning
Silhouette Score Measures how well-separated and cohesive clusters are.
Davies-Bouldin Index Lower values indicate better cluster separation.
Elbow Method Helps choose k for k-means by looking for diminishing improvement.

5.6.1 Failure Cases of k-Means

k-Means can fail even when the correct number of clusters is known because it assumes clusters are represented well by centers, have simple convex shapes, and have similar diameter.

Weakness: k-Means struggles with stretched, uneven-density, or complex-shaped clusters because it only considers distance to the nearest center.

Clustering Labels Are Assignments, Not Meanings

The guide compares clustering to classification because both assign a number or label to each data point. The crucial difference is that clustering has no ground-truth label by default. A cluster number only means "these points were grouped together". It does not automatically mean "premium customers", "fraud", or "disease group".

Clustering output What you can say safely What needs manual analysis
Cluster = 0 All points with label 0 are similar according to the algorithm and feature representation. Whether those points represent high-value customers, anomalies, or a business segment.
Cluster = 1 The number is arbitrary and may change if initialization changes. The semantic name and business meaning of the group.
-1 in DBSCAN The point was treated as noise or an outlier. Whether the point is an error, a rare but valid case, or a valuable anomaly.
Exam trap: Do not use ordinary classification accuracy for clustering labels unless the task specifically gives ground truth and you use a clustering-aware metric such as ARI or NMI.

k-Means: Centroids, Failure Cases, and Vector Quantization

k-Means represents each cluster by a center. It alternates between assigning points to the closest center and recomputing each center as the mean of assigned points until assignments stop changing.

  • Needs k: the number of clusters must be chosen before fitting.
  • Random initialization: results can vary; scikit-learn runs multiple initializations and keeps the best outcome.
  • Simple cluster shapes: k-means assumes clusters are well described by centers, roughly convex, and not wildly different in diameter.
  • Vector quantization: the guide notes that k-means can be viewed as representing each point by a single component: its cluster center.
  • Expressive representation: using many cluster centers can create new features, such as one-hot cluster assignments or distances to each center.
Weakness: k-Means struggles on stretched, uneven-density, or two-moons-style clusters because nearest-center distance does not capture complex shape.

Hierarchical Clustering and DBSCAN: Two Different Ways to Control Granularity

Agglomerative clustering starts with every point as its own cluster and repeatedly merges the two most similar clusters. DBSCAN starts from density: enough nearby points create a core region, sparse points become boundaries or noise.

Method Control parameter What it changes
k-Means n_clusters Directly chooses how many centroid-based clusters to form.
Agglomerative n_clusters and linkage Chooses the final number of clusters and how similarity between clusters is measured.
DBSCAN eps and min_samples Controls how dense a region must be; the number of clusters emerges from the data.
  • Ward linkage: minimizes the increase in within-cluster variance and often gives similar-sized clusters.
  • Average linkage: merges clusters with the smallest average distance between their points.
  • Complete linkage: merges based on the smallest maximum distance between any two points in the clusters.
  • Dendrogram: shows the merge history and helps inspect possible cut points.
  • DBSCAN eps: too small can mark everything as noise; too large can merge everything into one cluster.

Evaluating Clusters: Quantitative Scores Plus Human Interpretation

The guide warns that clustering is often qualitative and exploratory. Internal metrics help, but a high score does not prove that clusters match the real-world concept you care about.

Evaluation idea Use when Limitation
silhouette score No ground truth; you want compact, separated clusters. Can prefer compact shapes even when DBSCAN captures complex structure better.
Davies-Bouldin Index No ground truth; you want a lower-is-better separation score. Still does not prove semantic meaning.
elbow method Choosing k for k-means. The elbow may be unclear.
ARI or NMI You have ground-truth grouping for comparison. Rare in real unsupervised applications.
Manual cluster analysis You need business or domain meaning. Requires inspection of examples, summaries, or visualizations.

Chapter 5 Extended Code Example: Customer Segmentation With Three Clustering Methods

This example follows the guide's customer-segmentation scenario: scale customer features, apply k-means, agglomerative clustering, and DBSCAN, then compare internal metrics.

import numpy as np
import pandas as pd
from sklearn.cluster import AgglomerativeClustering, DBSCAN, KMeans
from sklearn.metrics import davies_bouldin_score, silhouette_score
from sklearn.preprocessing import StandardScaler

# Step 1: Generate guide-style customer data.
# Features: age, annual income, and spending score.
np.random.seed(42)
data = np.random.rand(200, 3) * [50, 100000, 100]
df = pd.DataFrame(data, columns=["Age", "Annual_Income", "Spending_Score"])

# Step 2: Scale features before distance-based clustering.
# Without scaling, Annual_Income would dominate Age and Spending_Score.
scaler = StandardScaler()
X_scaled = scaler.fit_transform(df)

# Step 3: Fit the three clustering algorithms from the chapter.
kmeans = KMeans(n_clusters=3, random_state=42, n_init=10)
hierarchical = AgglomerativeClustering(n_clusters=3, linkage="ward")
dbscan = DBSCAN(eps=0.5, min_samples=5)

df["KMeans_Cluster"] = kmeans.fit_predict(X_scaled)
df["Hierarchical_Cluster"] = hierarchical.fit_predict(X_scaled)
df["DBSCAN_Cluster"] = dbscan.fit_predict(X_scaled)

# Step 4: Evaluate when possible.
# Silhouette and Davies-Bouldin require at least two non-noise clusters.
def evaluate_clusters(name, labels):
    unique_labels = set(labels)
    non_noise_labels = unique_labels - {-1}

    print("\n", name)
    print("Cluster labels:", sorted(unique_labels))
    print("Cluster sizes:", pd.Series(labels).value_counts().sort_index().to_dict())

    keep = np.asarray(labels) != -1
    clean_labels = np.asarray(labels)[keep]
    if 2 <= len(non_noise_labels) < keep.sum():
        print("Silhouette (non-noise):", round(silhouette_score(X_scaled[keep], clean_labels), 3))
        print("Davies-Bouldin (non-noise):", round(davies_bouldin_score(X_scaled[keep], clean_labels), 3))
    else:
        print("Need 2 clusters and at least 1 extra non-noise sample for internal scores.")

evaluate_clusters("k-Means", df["KMeans_Cluster"])
evaluate_clusters("Hierarchical", df["Hierarchical_Cluster"])
evaluate_clusters("DBSCAN", df["DBSCAN_Cluster"])

# Step 5: Inspect cluster profiles instead of trusting numeric labels.
# This is where the arbitrary labels become meaningful business descriptions.
profile = df.groupby("KMeans_Cluster")[["Age", "Annual_Income", "Spending_Score"]].mean()
print("\nk-Means customer profiles:\n", profile)

# Step 6: Remember that DBSCAN label -1 means noise/outlier.
noise_customers = df[df["DBSCAN_Cluster"] == -1]
print("DBSCAN noise count:", len(noise_customers))
Common error: Cluster labels are arbitrary. Interpret clusters by inspecting profiles, examples, centers, dendrograms, or visualizations.

Chapter 5 guide practice: all ten tasks

The guide's closing exercises ask you to compare clustering on Iris or Digits, inspect a dendrogram, test DBSCAN on noisy shapes, compare PCA and scaling choices, visualise with t-SNE, engineer features, detect anomalies, choose k with an elbow plot, and compare a Gaussian mixture with k-means. These are wider-module practice tasks, not additions to the earlier CA scope. Source: Machine Learning 600 Study Guide, §5.6, PDF pp. 161–166 (printed pp. 159–164).

  1. k-means: vary n_clusters; compare silhouette and, when true labels exist, ARI. Cluster numbers need not match class numbers.
  2. Hierarchical: inspect merge distances in a dendrogram; choose a cut and compare assignments with k-means.
  3. DBSCAN: vary eps and min_samples; count label -1 as noise and inspect irregular shapes.
  4. PCA: plot two components, report explained_variance_ratio_, then compare clustering on original and reduced features.
  5. Preprocessing: compare original, scaled and row-normalised features. Normalizer scales each sample; RobustScaler scales columns robustly, so they answer different questions.
  6. t-SNE: use a 2D embedding for visual exploration; local neighbours matter more than global axis distances, and the embedding is not a fitted predictor.
  7. Feature engineering: add justified interactions, then compare clusters using the same evaluation method; extra features can also make distances less useful.
  8. Isolation Forest: inspect predictions (-1 = anomaly) and compare the flagged points with DBSCAN noise or known synthetic outliers.
  9. Elbow: plot k-means inertia_ over a range of k; an elbow is a judgement aid, not a guaranteed optimum.
  10. Gaussian mixture: compare hard labels and predict_proba membership probabilities with k-means; a mixture assumes Gaussian components.
from sklearn.datasets import load_iris, make_moons
from sklearn.cluster import KMeans, DBSCAN, AgglomerativeClustering
from sklearn.decomposition import PCA
from sklearn.ensemble import IsolationForest
from sklearn.manifold import TSNE
from sklearn.metrics import adjusted_rand_score, silhouette_score
from sklearn.mixture import GaussianMixture
from sklearn.preprocessing import Normalizer, PolynomialFeatures, StandardScaler
from scipy.cluster.hierarchy import dendrogram, linkage
import matplotlib.pyplot as plt
import numpy as np

X, true_species = load_iris(return_X_y=True)
X = StandardScaler().fit_transform(X)
km = KMeans(n_clusters=3, random_state=42, n_init=10).fit(X)
print("ARI:", adjusted_rand_score(true_species, km.labels_))
print("Silhouette:", silhouette_score(X, km.labels_))
print("K-means centers:", km.cluster_centers_.shape)

# A dendrogram is drawn from a linkage matrix, not from model labels.
tree = linkage(X, method="ward")
dendrogram(tree, truncate_mode="lastp", p=12)
plt.title("Last 12 merges")
plt.show()
hierarchical = AgglomerativeClustering(n_clusters=3).fit_predict(X)

pca = PCA(n_components=2).fit(X)
Z = pca.transform(X)
print("PCA retained variance:", pca.explained_variance_ratio_.sum())
print("PCA-space silhouette:", silhouette_score(Z, KMeans(n_clusters=3, random_state=42, n_init=10).fit_predict(Z)))
unit_rows = Normalizer().fit_transform(X)
print("Row-normalised silhouette:", silhouette_score(unit_rows, KMeans(n_clusters=3, random_state=42, n_init=10).fit_predict(unit_rows)))
X_interactions = PolynomialFeatures(degree=2, include_bias=False).fit_transform(X)
print("Engineered-feature silhouette:", silhouette_score(X_interactions, KMeans(n_clusters=3, random_state=42, n_init=10).fit_predict(X_interactions)))
embedding = TSNE(n_components=2, random_state=42, perplexity=30).fit_transform(X)
plt.scatter(embedding[:, 0], embedding[:, 1], c=true_species)
plt.title("t-SNE view (colours shown only for interpretation)")
plt.show()

moons, _ = make_moons(n_samples=200, noise=0.07, random_state=42)
db_labels = DBSCAN(eps=0.2, min_samples=5).fit_predict(moons)
print("DBSCAN noise:", np.sum(db_labels == -1))
keep = db_labels != -1
if 2 <= np.unique(db_labels[keep]).size < keep.sum():
    print("DBSCAN silhouette without noise:", silhouette_score(moons[keep], db_labels[keep]))
anomaly_labels = IsolationForest(random_state=42, contamination=0.05).fit_predict(moons)
print("Isolation Forest flags:", np.sum(anomaly_labels == -1))

ks = range(1, 9)
inertias = [KMeans(n_clusters=k, random_state=42, n_init=10).fit(X).inertia_ for k in ks]
plt.plot(list(ks), inertias, marker="o")
plt.xlabel("k")
plt.ylabel("Within-cluster sum of squares")
plt.show()
gmm = GaussianMixture(n_components=3, random_state=42).fit(X)
print("GMM agreement with species:", adjusted_rand_score(true_species, gmm.predict(X)))
print("GMM memberships for first row:", gmm.predict_proba(X[:1]))

The snippet demonstrates the APIs on bundled or generated data. For the guide's full comparison task, also inspect cluster profiles and repeat evaluation after PCA or justified feature engineering. Compare silhouette only when the evaluated labels contain at least two clusters and fewer clusters than samples.

Chapter 5 Glossary: Clustering Algorithms and Evaluation
unsupervised learning
Learning hidden patterns from input data without predefined output labels.
clustering
Grouping similar data points so intra-cluster similarity is high and inter-cluster similarity is low.
cluster
A group of observations considered similar by the algorithm.
intra-cluster similarity
Similarity among points within the same cluster.
inter-cluster similarity
Similarity between points from different clusters; good clustering aims to keep this low.
k-Means
Centroid-based algorithm that assigns points to the nearest cluster center and updates centers repeatedly.
k
The number of clusters chosen before running k-means.
centroid
The center of a cluster, usually the mean of assigned points.
cluster_centers_
Scikit-learn k-means attribute storing the learned centroids.
labels_
Attribute storing the cluster assignment for each training point.
vector quantization
Viewing k-means as representing each point with a single component: its nearest cluster center.
MiniBatchKMeans
More scalable version of k-means for very large datasets.
hierarchical clustering
Clustering that builds nested groups, often visualized with a dendrogram.
agglomerative clustering
Bottom-up hierarchical clustering that starts with each point alone and merges clusters.
divisive clustering
Top-down hierarchical clustering that starts with one cluster and splits it.
dendrogram
Tree-like plot showing the order and distance of hierarchical cluster merges.
ward
Linkage method that merges clusters while minimizing increased within-cluster variance.
average linkage
Linkage method based on average distance between all points in two clusters.
complete linkage
Linkage method based on the maximum distance between points in two clusters.
DBSCAN
Density-Based Spatial Clustering of Applications with Noise; finds dense regions and marks noise points.
eps
DBSCAN neighborhood radius used to decide which points are close enough.
min_samples
Minimum number of nearby points required for a DBSCAN core sample.
core point
A point with at least min_samples points within distance eps.
boundary point
A point near a core point but not itself dense enough to be a core point.
noise / -1
DBSCAN label for points not assigned to a dense cluster.
silhouette score
Internal metric measuring compactness and separation; higher is better.
Davies-Bouldin Index
Internal clustering metric where lower values indicate better separation.
elbow method
Method for selecting k by finding where extra clusters give diminishing improvement.
ARI
Adjusted Rand Index; compares clustering to ground truth while ignoring arbitrary label names.
NMI
Normalized Mutual Information; another clustering-aware comparison metric when ground truth exists.

Classes, Functions, Methods & Attributes

Choose a task below, or click a letter and then an API name. Course/page identifies APIs used in the study material or existing examples; Supporting identifies useful additions, not extra confirmed test scope. Examples assume the imports shown in the general-content walkthroughs.

Learning Lab

Use these interactive tools to practise Machine Learning 600 concepts. Your quiz attempts are saved only in this browser.

Quiz Builder

Choose how many questions to draw from each topic, then answer and submit when ready.

Flashcards

Recall the definition before flipping the card.

Concept Challenge

Explain It

Methods indexCA homeGeneral notes