Supervised and Unsupervised Learning
Machine Learning (ML) is the branch of AI in which systems learn patterns from data rather than being explicitly programmed with rules. In data analytics, ML is what powers predictive analytics (supervised) and descriptive analytics (unsupervised).
Supervised Learning
The algorithm learns from labelled training data — every input example carries the correct output. The goal is a function f(X) → Y that generalises to unseen data.
Training data:
X (features/inputs) Y (label/target)
──────────────────── ────────────────
hours=5, attendance=80% -> Pass
hours=2, attendance=45% -> Fail
hours=8, attendance=92% -> Pass
Learn f -> then predict for a NEW student with hours=6, attendance=75%
| Type | Target variable | Question | Examples |
|---|---|---|---|
| Classification | Categorical (discrete classes) | "Which class?" | Spam/not-spam, pass/fail, disease/no-disease, digit 0–9 |
| Regression | Continuous (numeric) | "How much?" | House price, temperature, sales forecast, marks |
Unsupervised Learning
The algorithm receives only inputs, no labels, and must discover structure on its own.
| Type | Goal | Examples |
|---|---|---|
| Clustering | Group similar records | Customer segmentation, document grouping, image compression |
| Association rule mining | Find items that co-occur | Market basket analysis ("bread → butter") |
| Dimensionality reduction | Compress features while retaining information | PCA before modelling, visualization in 2-D |
| Anomaly detection | Identify unusual records | Fraud detection, machine-fault detection |
Reinforcement Learning (Brief)
An agent interacts with an environment, taking actions and receiving rewards or penalties, learning a policy that maximises cumulative reward. Used in game playing (AlphaGo), robotics, dynamic pricing, and recommendation sequencing. It needs neither labels nor a fixed dataset — it needs an environment to experiment in.
Comparison — The Standard Exam Table
| Basis | Supervised Learning | Unsupervised Learning |
|---|---|---|
| Input data | Labelled (X and Y both given) | Unlabelled (only X) |
| Goal | Predict the output for new inputs | Discover hidden structure |
| Feedback | Direct — the correct answer is known | None |
| Analytics type | Predictive | Descriptive |
| Main tasks | Classification, regression | Clustering, association, dimensionality reduction |
| Algorithms | Naïve Bayes, KNN, linear regression, decision tree, SVM, random forest | K-Means, hierarchical clustering, DBSCAN, Apriori, PCA |
| Evaluation | Objective — accuracy, RMSE, F1 vs known truth | Subjective — silhouette score, domain interpretation |
| Data preparation cost | High (labelling is expensive/manual) | Low (no labelling needed) |
| Computational complexity | Generally simpler | Often harder |
| Number of classes | Known in advance | Unknown; must be discovered/chosen |
| Example | Predict whether a loan will default | Segment customers into behavioural groups |
Semi-Supervised and Self-Supervised Learning
- Semi-supervised — a small labelled set plus a large unlabelled set. Common in practice, because labelling is the bottleneck (e.g. 1,000 labelled medical images plus 100,000 unlabelled ones).
- Self-supervised — labels generated automatically from the data's own structure (e.g. predicting a masked word). This is how modern language models are pre-trained.
The Supervised Learning Workflow
The cardinal rule: never evaluate a model on data it was trained on. Training accuracy is always optimistic; only performance on held-out data predicts real-world behaviour.
Overfitting and Underfitting
| Underfitting | Good Fit | Overfitting | |
|---|---|---|---|
| Model complexity | Too simple | Balanced | Too complex |
| Training error | High | Low | Very low |
| Test error | High | Low | High |
| Bias | High | Balanced | Low |
| Variance | Low | Balanced | High |
| Cause | Too few features, over-regularised | — | Too many parameters, too little data, noise memorised |
| Fix | Add features, use a more complex model | — | More data, regularisation, simpler model, cross-validation, early stopping |
The bias-variance trade-off:
Total Error = Bias² + Variance + Irreducible Error
Bias = error from wrong assumptions (model too simple)
Variance = error from sensitivity to the particular training sample
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline
from sklearn.metrics import mean_squared_error
np.random.seed(42)
X = np.sort(np.random.uniform(0, 10, 30)).reshape(-1, 1)
y = 2 * X.ravel() + 5 + np.random.normal(0, 3, 30)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
for degree in [1, 3, 15]:
model = make_pipeline(PolynomialFeatures(degree), LinearRegression())
model.fit(X_train, y_train)
train_rmse = np.sqrt(mean_squared_error(y_train, model.predict(X_train)))
test_rmse = np.sqrt(mean_squared_error(y_test, model.predict(X_test)))
print(f"Degree {degree:2d}: train RMSE = {train_rmse:6.3f}, test RMSE = {test_rmse:8.3f}")
# Degree 1: train RMSE = 2.708, test RMSE = 2.906 <- good fit
# Degree 3: train RMSE = 2.605, test RMSE = 3.297
# Degree 15: train RMSE = 1.183, test RMSE = 108.402 <- OVERFITTING: memorised the noise
Train-Test Split and Cross-Validation
from sklearn.model_selection import KFold, cross_val_score
# Simple split
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
print(f"Train: {len(X_train)}, Test: {len(X_test)}")
# k-fold cross-validation — every observation is used for testing exactly once
model = LinearRegression()
scores = cross_val_score(model, X, y, cv=5, scoring="r2")
print("Fold R² scores:", scores.round(3))
print(f"Mean R² = {scores.mean():.3f} (+/- {scores.std():.3f})")
Why cross-validation beats a single split: one random split can be lucky or unlucky. Averaging over k folds gives a far more stable estimate, and uses every record for both training and testing.
| Variant | Description |
|---|---|
| k-fold | Standard; k = 5 or 10 |
| Stratified k-fold | Preserves class proportions in each fold — essential for imbalanced classification |
| Leave-One-Out (LOOCV) | k = n; maximum data use, very expensive |
| Time-series split | Train only on the past, test on the future — never shuffle time-ordered data |
The next lessons dive into each task type: classification, then regression, then the specific algorithms named in the syllabus.