AI & ML Quick Path Progress

Part 3: Machine learning Lesson 4 of 20 in this part

Linear models under the hood

What you will learn. Solve a linear regression with the normal equation instead of a library call, see how one change (a log link) turns it into a count model, and choose a decision threshold from the real cost of each kind of mistake.

  • Intermediate
  • Study time about 75 min
  • Maths Some algebra
  • Python: example run
  • C#: compiled and run

Before this lesson: Regression: predicting a number, Classification: picking a category. Already know these? Carry on.

In plain words

In the regression lesson a library found the best line for you. Underneath, that is one piece of algebra called the normal equation: it gives the best slope and intercept directly, with no repeated tries. It is worth seeing once, because it explains why a column of ones carries the intercept, why features on very different scales cause trouble, and why highly similar features make the answer unstable. Two ideas then stretch the same model. A generalised linear model keeps the straight-line part but connects it to the answer through a link, so it can predict counts or probabilities instead of any number. And cost-sensitive learning accepts that mistakes are not equal: when a missed case costs ten times a false alarm, the best cut-off is not 50%.

Diagram The normal equation in four steps
  1. InputPut the features in a table XAdd a column of ones for the intercept
  2. ProcessWork out XtX and XtyTwo small tables built from X and the answers
  3. ModelSolve XtX times w equals XtyThe unknown w holds slope and intercept
  4. OutputUse w to predictPrediction is X times w

One calculation gives the best line. No repeated guessing is needed.

Diagram Normal equation and gradient descent

Normal equation

  • One calculation
  • Fine for a few features
  • Slows down with very many features

Gradient descent

  • Many small steps
  • Works for huge data and any model
  • Needs a learning rate

Both reach the same line. They differ in how they get there and when they stop working well.

Diagram Plain and generalised linear models

Plain linear model

  • Answer is any number
  • Good for prices and times

Generalised linear model

  • A link connects the line to the answer
  • Log link: counts. Logit link: probabilities

The straight-line part is the same. The link changes what the answer means.

Real-world example

A property website predicts a flat's price from its size. A data scientist first uses a library call. A reviewer asks, "How do I know the numbers are right?" The scientist solves the normal equation directly on six flats and shows that the slope and intercept match the library to three decimals. The same company also predicts how many support calls a district will make per day. Calls are counts: never negative, often small, and the spread grows with the average. They use a Poisson model with a log link, which cannot predict a negative count. And for a loan-risk alert, where missing a risky loan costs far more than a needless review, they pick the cut-off from the total cost, not from 50%.

How it works

  1. The line by algebra. For one feature, write the table X with a column of ones and a column of sizes. The best weights satisfy XtX times w = Xty. For two unknowns this is two equations you can solve by hand.
  2. When it breaks. If two features carry nearly the same information, XtX is almost impossible to invert and the weights become unstable. This is called multicollinearity. Drop one feature or use ridge regression.
  3. The link. A Poisson model says the logarithm of the expected count is a straight line in the features. Taking the exponential gives the count, which is always positive.
  4. The cost. To choose a threshold, count how many cases are missed and how many are false alarms at each cut-off, multiply by the cost of each, and pick the cheapest.

Python example

Python: example run The example programme behind this lesson's quoted output ran on 2026-11-19 (Python 3.12.10). 1 code block in the lesson passed a syntax check, 1 also ran on their own.

Six flats, made-up numbers. The program solves the normal equation, checks it against scikit-learn, and then evaluates four thresholds by total cost, where a missed case costs 10 and a false alarm costs 1.

Python — linear_deeper.py
"""Linear regression under the hood: the normal equation, then a cost-sensitive threshold.

Part 1 solves for the best line with the normal equation (w = (XtX)^-1 Xt y) and checks it against scikit-learn.
Part 2 picks a decision threshold by total cost when a missed case costs 10 times a false alarm.
Run:  python linear_deeper.py   (needs numpy and scikit-learn)
"""
import numpy as np
from sklearn.linear_model import LinearRegression

size = np.array([50.0, 60.0, 70.0, 80.0, 90.0, 100.0])             # square metres
price = np.array([150.0, 172.0, 205.0, 226.0, 255.0, 270.0])       # thousands (made-up numbers)
X = np.column_stack([np.ones_like(size), size])                    # a column of ones carries the intercept
w = np.linalg.solve(X.T @ X, X.T @ price)                          # the normal equation
print("normal equation: intercept %.3f  slope %.3f" % (w[0], w[1]))
lib = LinearRegression().fit(size.reshape(-1, 1), price)
print("scikit-learn:    intercept %.3f  slope %.3f" % (lib.intercept_, lib.coef_[0]))
print("prediction for 75 square metres: %.1f" % (w[0] + w[1] * 75))

score = np.array([0.05, 0.10, 0.20, 0.30, 0.35, 0.45, 0.55, 0.60, 0.70, 0.80, 0.90, 0.95])
label = np.array([0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1])             # 1 means a real case
print("threshold  missed  false alarms  total cost (miss = 10, false alarm = 1)")
for t in (0.1, 0.3, 0.5, 0.7):
    flagged = score >= t
    missed = int(np.sum((label == 1) & ~flagged))
    false_alarms = int(np.sum((label == 0) & flagged))
    print("%9.1f  %6d  %12d  %10d" % (t, missed, false_alarms, 10 * missed + false_alarms))
Output — Output of linear_deeper.py (executed)
normal equation: intercept 26.571  slope 2.486
scikit-learn:    intercept 26.571  slope 2.486
prediction for 75 square metres: 213.0
threshold  missed  false alarms  total cost (miss = 10, false alarm = 1)
      0.1       0             5           5
      0.3       0             3           3
      0.5       1             1          11
      0.7       2             0          20

Both ways give the same line (intercept 26.571, slope 2.486), which predicts 213.0 for 75 square metres. In the cost table, the cut-off of 0.5 that looks natural costs 11. The lower cut-off of 0.3 flags more cases but costs only 3, because it misses nobody.

.NET (C#) example

C#: compiled and run The C# sample compiled on 2026-11-19 with .NET SDK 10.0.400 (no extra packages). It also ran to the end without error.

The normal equation for two unknowns is solved by hand here, so no packages are needed. It prints the same numbers as the Python version. In ML.NET the Sdca and Ols regression trainers solve the same problem for you.

C# — Program.cs
// Same numbers as linear_deeper.py. The normal equation is solved by hand for two unknowns, so no packages are needed.
double[] size = { 50, 60, 70, 80, 90, 100 };
double[] price = { 150, 172, 205, 226, 255, 270 };
int n = size.Length;

// X has a column of ones and a column of sizes. XtX is a 2x2 table and Xty is a list of 2 numbers.
double a = n, b = size.Sum(), d = size.Sum(s => s * s);          // XtX = [[a, b], [b, d]]
double e = price.Sum(), f = size.Zip(price, (s, p) => s * p).Sum();   // Xty = [e, f]
double det = a * d - b * b;                                       // determinant of XtX
double intercept = (d * e - b * f) / det;                         // solve the 2x2 system
double slope = (a * f - b * e) / det;
Console.WriteLine($"normal equation: intercept {intercept:F3}  slope {slope:F3}");
Console.WriteLine($"prediction for 75 square metres: {intercept + slope * 75:F1}");

double[] score = { 0.05, 0.10, 0.20, 0.30, 0.35, 0.45, 0.55, 0.60, 0.70, 0.80, 0.90, 0.95 };
int[] label = { 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1 };             // 1 means a real case
Console.WriteLine("threshold  missed  false alarms  total cost (miss = 10, false alarm = 1)");
foreach (double t in new[] { 0.1, 0.3, 0.5, 0.7 })
{
    int missed = 0, falseAlarms = 0;
    for (int i = 0; i < score.Length; i++)
    {
        bool flagged = score[i] >= t;
        if (label[i] == 1 && !flagged) missed++;
        if (label[i] == 0 && flagged) falseAlarms++;
    }
    Console.WriteLine($"{t,9:F1}  {missed,6}  {falseAlarms,12}  {10 * missed + falseAlarms,10}");
}

Maths behind it

  • The normal equation and matrix algebra (linear algebra)
  • Determinant of a 2 by 2 table (linear algebra)
  • The logarithm and exponential as inverses (algebra)
  • Expected cost of decisions (decision theory)

Common mistakes

  • Forgetting the column of ones, which forces the line through the origin.
  • Feeding two features that say nearly the same thing (multicollinearity) and trusting the weights.
  • Using a plain linear model for counts and getting negative predictions.
  • Choosing a 50% threshold because it is the default, without looking at the cost of each mistake.
  • Tuning the cut-off on the test set. Use validation data.

Quick check

  1. Why do we add a column of ones to the features?

    Show answer

    It lets the model learn the intercept as one more weight. Without it the line must pass through zero.

  2. Why use a log link for a model of counts?

    Show answer

    The exponential of any number is positive, so predicted counts can never be negative, and each unit of a feature multiplies the expected count.

  3. A missed fraud costs 50 and a false alarm costs 1. Should the cut-off be above or below 50%?

    Show answer

    Below. Misses are far more expensive, so flag more cases and accept extra false alarms.

  4. Two features are almost copies of each other. What goes wrong in the normal equation?

    Show answer

    XtX becomes nearly impossible to invert, so the weights are unstable and can change a lot with tiny changes in the data. Remove one feature or use ridge regression.

Completion

Evidence of completion. The same line fitted by the normal equation and by a library, with both sets of numbers shown, plus a cost table that justifies one threshold.

Saved in this browser only. Reading and exercise are ticked separately because they are different achievements. A tick records your own work; it is not a test result. See all progress.