# Building ML Algorithms from Scratch in Python

**Key takeaways**

- In *Programming for Machine Learning*, a course in my master's in Applied AI, I worked through labs on regression, clustering and image processing, writing core algorithms myself before using libraries.
- The key lessons: understand the data before modelling it, keep test data separate when choosing a model, and scale features for distance-based methods.
- Writing k-means, the silhouette score and template matching from scratch, then checking them against scikit-learn, is the habit I take with me: **implement, then verify against a trusted reference.**

## Context: why "programming for ML" is its own skill

Most ML tutorials start with `model.fit(X, y)`. This course went the other way. It started with Python basics (program state, loops, recursion, string processing), then asked us to load and clean real data by hand, implement algorithms ourselves, and only then compare our results with scikit-learn.

That order matters in industry. Data rarely arrives clean, and you can only trust, explain or improve a model if you know what it computes.

The labs I write about here:

| Topic | What I built |
| --- | --- |
| Regression | Linear regression with the normal equation, then polynomial regression with scikit-learn |
| Clustering | A k-means class and the silhouette score, written from scratch |
| Image processing | Image loading, scaling and thresholding with scikit-image, plus my own template matching |

---

## Regression: from the normal equation to overfitting

### Linear regression by hand

For income versus age, I solved linear regression with the **normal equation** instead of calling a library:

**θ = (XᵀX)⁻¹ Xᵀy**

where the first column of X is all ones, which gives the intercept. In NumPy, on a small synthetic example:

```python
import numpy as np
rng = np.random.default_rng(0)
age = rng.uniform(20, 50, 40).reshape(-1, 1)
income = 240 + 3.9 * age.ravel() + rng.normal(0, 10, 40)

X = np.c_[np.ones(age.shape), age]                 # design matrix [1, x]
theta = np.linalg.inv(X.T @ X) @ X.T @ income      # normal equation
print("intercept, slope:", theta.round(2))
```

```text
intercept, slope: [237.4    4.06]
```

The fitted values are close to the true 240 and 3.9 used to generate the data. One small but real lesson: you cannot "divide" by a matrix. You multiply by its inverse (and in production you would use `np.linalg.lstsq` or a library, which is numerically safer).

### Underfitting and overfitting, made visible

Next came polynomial regression. Income rises with age and then falls, so a straight line underfits. Here is the same experiment on synthetic data with that shape:

```python
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import LinearRegression

for degree in [1, 2, 5, 12]:
    model = make_pipeline(StandardScaler(), PolynomialFeatures(degree), LinearRegression())
    model.fit(X_tr, y_tr)
    # ... compute train and test MSE
```

```text
degree  1: train MSE   4798.7   test MSE   5936.1
degree  2: train MSE    344.3   test MSE    411.9
degree  5: train MSE    319.9   test MSE    415.0
degree 12: train MSE    225.1   test MSE    454.3
```

Degree 1 underfits. Degree 2 captures the curve. Degree 12 has the lowest training error but a higher test error: it starts fitting noise. Two practices I now follow:

- **Learn preprocessing settings from the training split only**, then apply them unchanged to the test split. A pipeline makes this automatic.
- **Choose hyperparameters on a validation set**, and keep a separate test set for the final, honest estimate.

---

## Clustering: k-means and the silhouette score from scratch

I implemented k-means as a class with the two alternating steps of Lloyd's algorithm (Lloyd, 1982): label every point with its closest centroid, recompute every centroid as the average of the points it owns, and repeat until the centroids settle. The core idea, in a compact vectorised form:

```python
def kmeans_step(data, centroids):
    # assign: index of the nearest centroid for every point
    dists = np.linalg.norm(data[:, None, :] - centroids[None, :, :], axis=2)
    labels = dists.argmin(axis=1)
    # update: each centroid moves to the mean of its points (kept if empty)
    new = np.array([data[labels == j].mean(axis=0) if np.any(labels == j) else centroids[j]
                    for j in range(len(centroids))])
    return labels, new
```

On three synthetic blobs this converged after 3 iterations, with centroids close to the true centres (0, 0), (4, 4) and (0, 4).

To choose *k*, I implemented the **silhouette score** (Rousseeuw, 1987). For a point i, a(i) measures how far it sits, on average, from its cluster-mates, b(i) measures its average distance to the closest neighbouring cluster, and

**s(i) = (b(i) − a(i)) / max(a(i), b(i))**

The average over all points is between −1 and 1; higher means tighter, better-separated clusters.

### Checking against scikit-learn

I compared my implementation with `sklearn.metrics.silhouette_score`, including a cluster with only one point, which by the standard definition contributes s(i) = 0:

```python
data = np.array([[0, 0], [0, 1], [1, 0], [8, 8], [8, 9], [20, 0]], dtype=float)
labels = np.array([0, 0, 0, 1, 1, 2])             # [20, 0] is a one-point cluster
print("mine:", round(silhouette(data, labels), 4),
      " scikit-learn:", round(silhouette_score(data, labels), 4))
```

```text
mine: 0.7527  scikit-learn: 0.7527
```

This is the habit I value most from the course: **a from-scratch implementation is only finished when it agrees with a trusted reference**, and testing edge cases is part of that.

Another lesson from this lab: features on very different scales (here, yearly income and annual rent per square metre) let the larger one dominate every Euclidean distance. Distance-based methods need **feature scaling** (for example `StandardScaler`) just as much as regression does.

---

## Image processing: images are just arrays

The image-processing lab used scikit-image's sample images. The useful mindset shift: an image is a NumPy array with a shape and a dtype, so most image operations are array operations.

- A colour image is `(rows, cols, 3)` of `uint8` (0–255); `rgb2gray` turns it into `(rows, cols)` floats in 0–1, which means any threshold also has to live on the 0–1 scale. scikit-image weights the channels 0.2125, 0.7154 and 0.0721 (red, green, blue), which I checked directly.
- `rescale` multiplies the size by a factor; `resize` targets a fixed output shape.
- `uint8` **arithmetic wraps around:** `np.uint8(200) + np.uint8(100)` gives `44`. Converting to float before doing sums is not optional.

I wrote my own **template matching** with normalised cross-correlation (NCC): slide the template over the image, subtract the mean of the template and of each window (so brightness differences don't matter), and score the match between −1 and 1:

```python
image = data.coins().astype(float)            # uint8 -> float, avoids wrap-around
template = image[170:220, 75:130]             # one coin cut from the image
t = template - template.mean()
# for each window: wc = win - win.mean()
# score = (wc * t).sum() / np.sqrt((wc ** 2).sum() * (t ** 2).sum())
```

```text
best match (x, y): (75, 170) NCC: 1.0
```

The highest score lands exactly where I cut the template from. A sum-of-squared-differences matcher works the other way round (lowest value wins), and it finds the same location. Writing the loop myself made it clear why library versions use FFT-based tricks: the naive version is slow.

---

## What I learned

- **Evaluation discipline.** Separate training, validation and test data, fit preprocessing on training data only, and compare models on data they have not seen.
- **Implement, then verify.** Writing k-means, the silhouette score, the normal equation and NCC myself gave me a real understanding of what library calls do, and comparing with scikit-learn and scikit-image turned that understanding into tested code.
- **Data comes before models.** Cleaning text fields, handling file encodings (a hidden BOM character in a CSV header) and choosing feature scales mattered as much as the choice of algorithm.

**What I would explore next:** k-means++ initialisation with several random starts (keeping the lowest-inertia result), automated tests for each from-scratch function, and an FFT-based version of template matching for speed.

## Why this matters in industry

The same skills show up in every production ML project: cleaning and validating data before training, choosing models on validation data rather than training data, scaling features for distance-based methods, and verifying numerical code before its results reach a dashboard or a decision. Computer-vision basics like template matching are still used in quality inspection and document processing, and knowing that an image is "just an array" makes deep-learning pipelines much less mysterious.

On **The Hybrid Mind**, this course is my foundation on the *neural and statistical* side: the learning-from-data half of hybrid AI.

---

**Skills demonstrated:** Python · NumPy · pandas · Matplotlib · scikit-learn · scikit-image · linear regression (normal equation) · polynomial regression · train/validation/test splits · overfitting and underfitting · feature scaling · k-means · silhouette analysis · template matching (NCC) · testing numerical code against reference implementations

---

## References

Lloyd, S. (1982). Least squares quantization in PCM. *IEEE Transactions on Information Theory, 28*(2), 129–137. <https://doi.org/10.1109/TIT.1982.1056489>

Pedregosa, F., Varoquaux, G., Gramfort, A., Michel, V., Thirion, B., Grisel, O., … Duchesnay, É. (2011). Scikit-learn: Machine learning in Python. *Journal of Machine Learning Research, 12*, 2825–2830.

Rousseeuw, P. J. (1987). Silhouettes: A graphical aid to the interpretation and validation of cluster analysis. *Journal of Computational and Applied Mathematics, 20*, 53–65. <https://doi.org/10.1016/0377-0427(87)90125-7>

van der Walt, S., Schönberger, J. L., Nunez-Iglesias, J., Boulogne, F., Warner, J. D., Yager, N., Gouillart, E., Yu, T., & the scikit-image contributors. (2014). scikit-image: Image processing in Python. *PeerJ, 2*, e453. <https://doi.org/10.7717/peerj.453>

---

*The Hybrid Mind: where symbolic AI meets neural networks.*
