Chapter 17

Introduction to AI & Machine Learning

College
At a glance
Core ideaML learns the rule from examples instead of being handed it.
Key termGradient descent — step downhill on the loss to fit parameters.
You can…Train linear regression from scratch and predict unseen inputs.
Watch outOverfitting scores high on training data but fails on new data.
Theory

Traditional programming writes explicit rules: input plus code yields output. Machine learning (ML) inverts this — you supply examples of inputs and desired outputs, and the algorithm learns the rule (a model) itself. ML is a subfield of artificial intelligence. Its main paradigms:

  • Supervised learning — learn from labelled examples (input → known answer). Includes regression (predict a number) and classification (predict a category).
  • Unsupervised learning — find structure in unlabelled data, e.g. clustering similar items.
  • Reinforcement learning — an agent learns by trial and error, guided by rewards.

Learning is an optimisation: define a loss function measuring how wrong the model is, then adjust the model's parameters to minimise it. The workhorse method is gradient descent — compute the slope (gradient) of the loss with respect to each parameter and step in the downhill direction. A neural network stacks many simple weighted-sum-plus-nonlinearity units into layers, and deep learning uses many such layers to learn rich representations.

Input Hidden Output
Signals flow forward through weighted connections; training adjusts every weight by gradient descent until outputs match the desired answers.
Explanation

Picture the loss as a landscape of hills and valleys, where each horizontal coordinate is a parameter setting and height is the error. Learning is walking downhill to the lowest valley. The gradient points uphill fastest, so we step the opposite way; the learning rate sets the step size — too small and training crawls, too large and it overshoots and diverges. Repeat over the data and the model's error falls.

The central peril is generalisation. A model that merely memorises its training data — overfitting — performs perfectly in practice and uselessly on anything new, like a student who memorised the answer key without understanding. We guard against this by holding out a test set the model never trains on, and by regularisation. The whole point of ML is to perform well on unseen data; training accuracy alone is a vanity metric.

Honest framing. Modern "AI" is powerful pattern-matching optimised over enormous data, not understanding or consciousness. It can be spectacularly capable and confidently wrong in the same breath. Knowing how it works — statistics and gradient descent, not magic — is the best defence against both hype and fear.

Practical

We implement linear regression by gradient descent from scratch — the "hello world" of ML. The model learns the line y = w·x + b that best fits data generated from y ≈ 2x + 1, purely by minimising squared error.

# Training data roughly following y = 2x + 1
X = [1, 2, 3, 4, 5]
Y = [3, 5, 7, 9, 11]

w, b = 0.0, 0.0          # parameters, start ignorant
learning_rate = 0.01
n = len(X)

for epoch in range(1000):                 # 1000 passes over the data
    # 1. Predict and measure error (mean squared error)
    preds  = [w * x + b for x in X]
    errors = [preds[i] - Y[i] for i in range(n)]

    # 2. Gradients of the loss w.r.t. w and b (calculus of MSE)
    grad_w = (2 / n) * sum(errors[i] * X[i] for i in range(n))
    grad_b = (2 / n) * sum(errors[i]          for i in range(n))

    # 3. Step downhill: adjust parameters against the gradient
    w -= learning_rate * grad_w
    b -= learning_rate * grad_b

print("learned: y = " + str(round(w, 3)) + "x + " + str(round(b, 3)))
# -> learned: y = 2.0x + 1.0   (recovered the underlying rule!)

# Predict an unseen input -> generalisation
print("predict x=6:", round(w * 6 + b, 2))   # ~13.0

No rule for the line was ever written — only a loss to minimise and the downhill rule of gradient descent. After a thousand tiny steps the parameters converge to w≈2, b≈1, and the model correctly predicts an input it never saw. This exact loop, scaled to billions of parameters, underlies modern deep learning.

Q&A
Q1 How is machine learning different from ordinary programming?

Ordinary programming: a human writes the rules, the computer applies them. Machine learning: a human supplies examples and a goal, and the computer derives the rules. You use ML precisely when the rules are too complex or subtle to write by hand — recognising a face, translating a sentence — but you have plenty of examples to learn from.

Q2 What is overfitting, and how do we detect it?

Overfitting is when a model learns the noise and quirks of its training data instead of the underlying pattern, so it scores highly on training data but poorly on new data. We detect it by evaluating on a held-out test set the model never saw: a large gap between high training accuracy and low test accuracy is the signature of overfitting.

Q3 Why is the learning rate so important?

It controls the step size in gradient descent. Too small, and training takes impractically long to reach the minimum. Too large, and each step overshoots the valley, causing the loss to oscillate or diverge to infinity. Choosing it well (often with schedules that shrink it over time) is one of the most consequential knobs in training.

Q4 Is today's AI actually "intelligent" or conscious?

No, in any human sense. Current systems are statistical function approximators that find patterns in vast data by minimising a loss — extraordinarily useful, but without understanding, intentions, or awareness. They can produce fluent, correct-sounding output that is entirely wrong, because they optimise plausibility, not truth. Treat their outputs as capable suggestions to verify, not oracles.

Concept mind map

How the ideas connect

Every key idea in this chapter, branching from the core concept — use it to see the whole picture at a glance.

learn from datafeaturesmodelloss functiongradient descentpredictionAI and machine learning
Infographic

The process, step by step

Step 1PredictUse current parameters to make predictions on the data.
Step 2Measure lossCompute how far predictions are from the true values.
Step 3GradientFind the direction that most reduces the loss.
Step 4StepNudge parameters downhill; repeat until the loss stops falling.
Solved examples

Worked problems, step by step

Follow each solution line by line, then try to reproduce it on paper before moving on.

Example 1A line y = 2x + 1 predicts for x = 3. What is the prediction?

  1. Substitute x = 3.
  2. 2 * 3 + 1.

Example 2True value is 10, prediction is 7. Give the squared error.

  1. Error = 10 - 7 = 3.
  2. Square it: 3^2.
Practice problem set

Now you try

Work each one out first, then tap to reveal the worked answer.

1How is machine learning different from ordinary programming?
Instead of being handed the rule, the model learns the rule from example data.
2What is a loss function?
A measure of how wrong the model predictions are; training tries to make it small.
3What is gradient descent?
An iterative method that steps parameters downhill on the loss to fit the model.
4What is a feature?
An input variable the model uses to make a prediction, such as size or age.
5What does the learning rate control?
The size of each gradient-descent step; too big overshoots, too small learns slowly.
6What is overfitting?
When a model memorises training data and its noise, so it predicts poorly on new, unseen inputs.