ML600 · Machine Learning 600

Richfield Faculty of Information Technology

Machine Learning 600 Study Hub

A dark, readable one-page revision site built from the Machine Learning 600 study guide, covering exam focus areas first and the full chapter flow after that.

Definitions Correct patterns Exam traps Model risks Algorithms & structure

Assignment Helper

A question-by-question reading map for the Credit Risk Prediction System assignment. The brief is organised into Parts A-F, so each card identifies the study-guide concepts to apply and links to fuller explanations in General Module Content.

Assignment scenario: Build a supervised credit-risk classifier that predicts high-risk or low-risk loan applicants from a real Kaggle dataset. The workflow covers data acquisition, EDA, cleaning, feature engineering, scaling, PCA, three classification models, evaluation, hyperparameter tuning, and business interpretation.
Use the assignment brief as the requirement source. This section is a study map, not a replacement for the required Python/notebook, visible outputs, structured code comments, presentation PDF, dataset, Harvard references, or zipped-folder submission.
Part A10 marks

Data Acquisition and Understanding

Load one permitted Kaggle credit dataset with Pandas and make its structure visible before modelling.

Study-guide content to apply

Part B15 marks

Exploratory Data Analysis

Create at least four visualisations and interpret what each reveals about the target, relationships, feature distributions, and possible outliers.

Study-guide content to apply

Part C20 marks

Data Cleaning and Preprocessing

Prepare reliable model inputs by justifying how missing values, duplicates, outliers, categorical variables, feature scales, and the train-test split are handled.

Study-guide content to apply

Part D15 marks

Principal Component Analysis

Apply PCA after scaling, show explained variance, select components retaining about 90-95% of variance, and create a transformed dataset.

Study-guide content to apply

Part E25 marks

Model Development: Before and After PCA

Train Logistic Regression, k-Nearest Neighbours, and Decision Tree Classifier models using original and PCA-transformed features. Report the same evidence for every model and compare the results.

Study-guide content to apply

Part F10 marks

Model Optimisation

Select the best-performing model, tune its hyperparameters with GridSearchCV or RandomizedSearchCV, compare results before and after tuning, and explain the bias-variance effect.

Study-guide content to apply

Across the assignmentPresentation & submission

Business Interpretation, Presentation, and Submission

Use the technical results to make a defensible credit-risk recommendation, then communicate the work in the required presentation and zipped submission.

What to include

Test Focus Areas

A future home for confirmed test coverage and targeted revision guidance.

Coming soon

Test Focus Areas are coming soon

This section will be updated when the relevant guidance is available.

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.

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 Iris data with Pandas, split it with Scikit-learn, train Logistic Regression, and evaluate the result.

import pandas as pd
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; the species column is the known label.
df = pd.read_csv(
    "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv"
)

# 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=["species"])
y = df["species"]

# 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, CSV, JSON, XML. 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.
from sklearn.impute import SimpleImputer

imputer = SimpleImputer(strategy="mean")
df.iloc[:, :] = imputer.fit_transform(df)

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 and can skew the model.

import numpy as np

data = np.array([10, 12, 13, 15, 1000])
filtered_data = data[data < np.percentile(data, 95)]

df.drop_duplicates(inplace=True)

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 preserving as much useful information as possible.

  • Reduces computational cost.
  • Can reduce overfitting risk by removing noisy dimensions.
  • Improves interpretability and visualization for high-dimensional data.

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 dimensionality reduction, but the guide is clear that it is not simple column deletion. PCA standardizes the feature space, finds directions of maximum variance, rotates the data onto those directions, and then keeps the strongest components.

  • 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.

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
Organized data stored in rows and columns, such as databases, spreadsheets, CSV, JSON, or XML.
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.
  • 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.

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.

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 finds a hyperplane that maximizes the margin between classes. Support vectors are the closest points that define this margin. Kernel methods such as RBF help with 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 Tradeoff between sensitivity and specificity. 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 Tradeoff between sensitivity and specificity across thresholds. Use when comparing threshold behavior matters.

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.

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())

    if len(non_noise_labels) >= 2:
        print("Silhouette:", round(silhouette_score(X_scaled, labels), 3))
        print("Davies-Bouldin:", round(davies_bouldin_score(X_scaled, labels), 3))
    else:
        print("Not enough non-noise clusters 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 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.

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