Course map
Stage 1: Foundations
Stage 2: Machine Learning
Stage 3: Deep Learning
Stage 4: LLMs & Generative AI
Stage 5: Production & Specialization

Part 04 / Stage 1

Your first models

Goal: Understand what "learning" means by building linear and logistic regression from scratch with gradient descent. Time: ~3 hours · Needs: Parts 1–3

What you will learn

  • What learning means: model, parameters, loss, optimisation
  • Linear regression and its exact solution
  • Gradient descent, checked against the exact answer
  • Logistic regression: sigmoid, log loss, decision threshold
  • Feature scaling — why gradient descent needs it
  • Supervised vs unsupervised learning

Topics in this part

Practice

Run from the repo root with PYTHONPATH=tools.

Exercise 1: Learning rate sweep

Take the linear-regression example and run it with learning rates 0.0001, 0.01 and 0.5 for 2000 steps. Print final w, b and the MSE for each. Which rates reach the exact answer (w≈2.986, b≈4.981)?

Show the solution to Exercise 1
# Exercise 1: Learning rate sweep
import numpy as np

rng = np.random.default_rng(1)
X = rng.uniform(0, 10, size=(200, 1))
y = 3.0 * X[:, 0] + 5.0 + rng.normal(0, 1, size=200)


def fit(lr, steps=2000):
    w, b = 0.0, 0.0
    with np.errstate(all="ignore"):       # lr=0.5 diverges to nan; that IS the lesson
        for _ in range(steps):
            err = w * X[:, 0] + b - y
            w -= lr * 2 * (err * X[:, 0]).mean()
            b -= lr * 2 * err.mean()
        mse = ((w * X[:, 0] + b - y) ** 2).mean()
    return w, b, mse


for lr in [0.0001, 0.01, 0.5]:
    w, b, mse = fit(lr)
    print(f"lr={lr:<7} w={w:9.3f} b={b:9.3f} mse={mse:.4g}")
# 0.0001 is still far from b=4.981 after 2000 steps; 0.01 converges; 0.5 diverges.

Exercise 2: Loss curve

Modify the gradient-descent loop to record the MSE every 100 steps and print the series. Does it fall smoothly, and where does it flatten?

Show the solution to Exercise 2
# Exercise 2: Loss curve
import numpy as np

rng = np.random.default_rng(1)
X = rng.uniform(0, 10, size=(200, 1))
y = 3.0 * X[:, 0] + 5.0 + rng.normal(0, 1, size=200)

w, b, lr = 0.0, 0.0, 0.01
for step in range(1, 2001):
    err = w * X[:, 0] + b - y
    w -= lr * 2 * (err * X[:, 0]).mean()
    b -= lr * 2 * err.mean()
    if step % 100 == 0:
        mse = ((w * X[:, 0] + b - y) ** 2).mean()
        print(f"step {step:4d}  mse {mse:8.4f}")
# It drops fast early, then flattens once only the intercept is still adjusting.

Exercise 3: Threshold play

Using the from-scratch logistic model, print accuracy at thresholds 0.3, 0.5 and 0.7, plus how many customers each threshold flags as churners.

Show the solution to Exercise 3
# Exercise 3: Threshold play
import numpy as np
from ailab import make_churn

df = make_churn().dropna()
X = df[["tenure_months", "monthly_charges", "support_calls"]].to_numpy()
X = (X - X.mean(axis=0)) / X.std(axis=0)
X = np.c_[X, (df["contract"] == "month-to-month").to_numpy()]
y = df["churned"].to_numpy()

w = np.zeros(X.shape[1]); b = 0.0
for _ in range(3000):
    p = 1 / (1 + np.exp(-(X @ w + b)))
    w -= 0.1 * X.T @ (p - y) / len(y)
    b -= 0.1 * (p - y).mean()

for t in [0.3, 0.5, 0.7]:
    pred = (p > t).astype(int)
    acc = (pred == y).mean()
    print(f"threshold {t}: accuracy {acc:.3f}, flagged {int(pred.sum())} of {len(y)}")

Exercise 4: Supervised or not?

For each task, print S or U with one reason: predicting delivery time; grouping news articles by topic; flagging fraudulent card payments; compressing images to 32 dimensions for search.


Show the solution to Exercise 4
# Exercise 4: Supervised or not?
tasks = {
    "predicting delivery time": "S — labelled history: order features paired with actual delivery times.",
    "grouping news articles by topic": "U — no labels; clustering finds the topics.",
    "flagging fraudulent card payments": "S — past payments are labelled fraud / not fraud.",
    "compressing images to 32 dimensions for search": "U — dimensionality reduction needs no labels.",
}
for task, verdict in tasks.items():
    print(f"{task:48s} {verdict}")

Mini-project: From-scratch classifier

Train logistic regression with gradient descent on the churn data, record the log loss every 200 steps (a loss curve as numbers), and compare final training accuracy against the majority baseline.

A complete version is in solutions/mini_from_scratch_classifier.py.

Stretch: add L2 regularization and mini-batches, and show their effect on the loss curve.

Common mistakes

Mistake Why it is wrong Fix
Learning rate by vibes Loss crawls or explodes Try powers of 10; watch the loss every run
Unscaled features into gradient descent One lr cannot fit all gradients Standardize columns first
Reporting accuracy without the baseline 0.77 sounds good; the baseline is 0.70 Always print both
Treating 0.5 as the "correct" threshold It is a default, not a decision Choose it for the use case (Part 6)
Training accuracy as the result It flatters the model Hold out a test set (Part 3); this part's number is training-only and labelled as such

Quick recap

  • Learning means choosing a model, its parameters, a loss, and a way to optimise it.
  • Gradient descent matched the closed-form line fit: w=2.986 and b=4.981 both ways.
  • Logistic regression turns a linear score into a probability with the sigmoid; a threshold turns that probability into a decision.
  • The from-scratch churn model reached 0.77 training accuracy against the 0.702 baseline.
  • Scale the features for anything trained by gradients.
  • Supervised learning needs labels; unsupervised learning finds structure without them.

Checklist

  • I can name the four pieces of any learning setup.
  • I ran gradient descent and matched the exact solution.
  • I can read logistic weights as risk factors.
  • I can explain the sigmoid's job in one sentence.
  • I know which models need scaled inputs and which do not.
  • I can classify a problem as supervised or unsupervised.

Read more: scikit-learn: common pitfalls

Search the guide