Python for AI Engineers · Part C · Lesson 19 of 26

How machine learning works: models, loss, gradient descent and train/test splits

Machine learning for Java and JavaScript developers: a model is a function with learned parameters. Features and labels, loss, gradient descent by hand in NumPy, learning rate, scikit-learn, train/validation/test splits, and how LLMs learn from next-token prediction.

⏱ 40 min3 exercises that check your codeRuns in your browser

By the end you can

  • Explain a model as a function whose numbers (parameters) are learned from data, and name its features and labels
  • Measure how wrong a model is with a loss, and train one with gradient descent in plain NumPy
  • Pick a sensible learning rate, and check your result against scikit-learn's fit and predict
  • Split data into train, validation and test sets, and say what each one is for
  • Tell supervised, unsupervised and self-supervised learning apart, and explain how an LLM learns from raw text
1 / 6

1A model is a function with learned numbers

You already write functions that turn inputs into outputs. In normal programming you decide the rule. In machine learning you choose the shape of the rule and let the computer find the numbers inside it from examples.

Our running example is one every AI engineer cares about: how many seconds does a model reply take? A reasonable shape is a straight line, seconds = w * tokens + b: each extra hundred tokens adds w seconds, and b is a fixed start-up cost. w (the weight) and b (the bias) are the model's parameters. Training means finding good values for them.

An LLM is the same idea at a huge scale: still a function from input to output, but with billions of parameters instead of two.

Try it: edit and run
def predict(tokens, w, b):
    """Seconds a reply takes. tokens = reply length in hundreds of tokens."""
    return w * tokens + b


# The same function with two different sets of parameters:
print(predict(5, w=1.0, b=0.0))   # a guess
print(predict(5, w=0.9, b=0.4))   # better parameters, found by training later
Expected output
5.0
4.9
Java: a rule you wrote
// You picked 0.9 and 0.4 yourself, maybe from a dashboard.
// When traffic changes, you edit the code.
static double predict(double tokens) {
    return 0.9 * tokens + 0.4;
}
Machine learning: a rule you fit
# You pick the shape: w * tokens + b.
# Training reads past requests and finds w and b.
# When traffic changes, you train again on new data.

Two words you will hear all the time: training is finding the parameters from data, and inference is calling the trained function on new input. When your app calls an LLM API, it is doing inference on a model somebody else trained.

2Features and labels

A training example has two parts. The features are the inputs the model sees (the x). The label is the right answer for that input (the y), the thing you want the model to predict.

By convention the features of all examples go in a 2-D NumPy array called X with one row per example and one column per feature, and the labels go in a 1-D array y with one entry per row. Capital X for the table, small y for the column of answers: you will see these names in almost every ML codebase.

Try it: edit and run
import numpy as np

# Features: one row per past request, one column per feature.
#            prompt tokens (thousands), reply tokens (hundreds), cached (1 = yes)
X = np.array([
    [0.5, 1, 0],
    [2.0, 3, 0],
    [1.0, 4, 1],
    [4.0, 2, 0],
    [0.8, 6, 1],
])
# Labels: the answer we want the model to learn, one per row.
y = np.array([1.3, 3.6, 3.7, 3.4, 5.5])   # seconds each request took

print("X shape:", X.shape)       # (rows, features)
print("y shape:", y.shape)       # one label per row
print("row 2:", X[2], "->", y[2])
print("reply tokens column:", X[:, 1])
Expected output
X shape: (5, 3)
y shape: (5,)
row 2: [1. 4. 1.] -> 3.7
reply tokens column: [1. 3. 4. 2. 6.]

NumPy turned every number into a float, so 1 prints as 1.. X[:, 1] means "all rows, column 1", the slicing from the NumPy lesson.

Two kinds of label decide the kind of problem:

  • Regression: the label is a number (seconds, a price, a score). That is our example.
  • Classification: the label is a category ("billing" or "bug", spam or not). It is usually stored as an integer, 0, 1, 2 and so on.

Models only read numbers. A yes/no becomes 0 or 1, as in the cached column. Text becomes numbers too, most often as an embedding: the vector of floats an embedding model returns, which you met in the NumPy lesson. A list of embeddings is an X like this one, just with hundreds of columns.

3Loss: one number for how wrong the model is

To improve the parameters you first need to measure them. A loss function compares the model's predictions with the labels and returns one number: lower is better, 0 is perfect.

For regression the standard loss is the mean squared error (MSE): for every example take prediction minus label, square it, and average. Squaring makes every error positive and punishes big misses much more than small ones.

From here on we use only the reply-tokens feature, so x is a plain 1-D array and the model is our line. Run it and compare three guesses for w and b.

Try it: edit and run
import numpy as np

x = np.array([1, 2, 3, 4, 5, 6, 7, 8], dtype=float)   # reply tokens, in hundreds
y = np.array([1.2, 2.3, 3.1, 4.0, 4.8, 5.9, 6.6, 7.7])   # seconds it took


def mse(w, b):
    pred = w * x + b                    # predictions for all 8 examples at once
    return np.mean((pred - y) ** 2)     # average of the squared errors


for w, b in [(1.0, 0.0), (0.5, 1.0), (0.9, 0.4)]:
    print(f"w={w}  b={b}  loss={mse(w, b):.4f}")
Expected output
w=1.0  b=0.0  loss=0.0550
w=0.5  b=1.0  loss=2.3175
w=0.9  b=0.4  loss=0.0075

w * x + b works on the whole array without a loop (vectorised maths), and :.4f prints 4 decimals. The third guess has by far the lowest loss, so it fits the data best. Training is a search for the w and b with the lowest loss, done automatically.

Tip Classification uses a different loss, cross-entropy, which punishes the model for giving the right answer a low probability. An LLM is trained with exactly that loss on "which token comes next". The metrics lesson covers it.

4Gradient descent, by hand

How do you find the lowest loss without trying every w and b? Picture the loss as a valley: every pair of parameters is a spot on the ground, and the loss is the height there. You start somewhere, look which way is downhill, take a small step that way, and repeat.

The gradient is the "uphill" direction: how much the loss changes when you nudge each parameter a little. For MSE and a line it has a simple formula, which comes from calculus but you only need to read it: grad_w = 2 * mean(err * x) and grad_b = 2 * mean(err), where err is prediction minus label. Step the other way: w = w - lr * grad_w.

lr is the learning rate: how big each step is. Every pass through the data and one update is called a step (with all the data in one go, as here, a step is also an epoch). Run it and watch the loss fall.

Try it: edit and run
import numpy as np

x = np.array([1, 2, 3, 4, 5, 6, 7, 8], dtype=float)
y = np.array([1.2, 2.3, 3.1, 4.0, 4.8, 5.9, 6.6, 7.7])

w, b = 0.0, 0.0          # start anywhere
lr = 0.01                # learning rate: the step size

for step in range(1, 2001):
    pred = w * x + b
    err = pred - y                       # how far off each prediction is
    loss = np.mean(err ** 2)             # MSE before this step
    grad_w = 2 * np.mean(err * x)        # slope of the loss in the w direction
    grad_b = 2 * np.mean(err)            # slope of the loss in the b direction
    w = w - lr * grad_w                  # step downhill
    b = b - lr * grad_b
    if step in (1, 10, 100, 500, 2000):
        print(f"step {step:4}  loss {loss:8.4f}  w {w:.4f}  b {b:.4f}")

print(f"a 600-token reply should take about {w * 6 + b:.2f} s")
Expected output
step    1  loss  24.1300  w 0.4957  b 0.0890
step   10  loss   0.0149  w 0.9408  b 0.1754
step  100  loss   0.0110  w 0.9310  b 0.2337
step  500  loss   0.0074  w 0.9120  b 0.3408
step 2000  loss   0.0072  w 0.9072  b 0.3678
a 600-token reply should take about 5.81 s

How to read the important lines:

  • err = pred - y: one error per example. Positive means the model guessed too high.
  • grad_w = 2 * np.mean(err * x): if the model guesses too high on long replies, this is positive, so w - lr * grad_w makes w smaller. That is "step downhill".
  • w = w - lr * grad_w: the whole of learning. Everything else is bookkeeping.
  • {step:4} and {loss:8.4f} only pad the numbers so the columns line up.

The loss drops fast at first, then slowly: near the bottom of the valley the slope is gentle, so the steps get small. After 2000 steps the model says every hundred tokens adds about 0.91 seconds, plus 0.37 seconds of fixed start-up cost.

A neural network trains with this same loop. The model has millions of parameters instead of two, and a library such as PyTorch works out every gradient for you (autograd), but each step is still "compute the loss, compute the gradient, move every parameter a little downhill". You will write that loop in the PyTorch lessons.

Watch out Scale your features. Here x is in hundreds of tokens (1 to 8). With raw token counts (100 to 800) the gradient for w is about 100 times bigger, so the same learning rate overshoots and the loss explodes. Real projects rescale each feature to a similar range first, for example with scikit-learn's StandardScaler.

5The learning rate: too small, too big, just right

The learning rate is a hyperparameter: a setting you choose before training, as opposed to a parameter the training finds. Too small and training crawls. Too big and every step jumps over the bottom of the valley to a higher spot on the other side, so the loss grows instead of shrinking.

This box trains the same model five times for 100 steps each, with a different learning rate every time.

Try it: edit and run
import numpy as np

x = np.array([1, 2, 3, 4, 5, 6, 7, 8], dtype=float)
y = np.array([1.2, 2.3, 3.1, 4.0, 4.8, 5.9, 6.6, 7.7])


def train(lr, steps=100):
    w, b = 0.0, 0.0
    for _ in range(steps):              # _ = a loop variable we do not use
        err = w * x + b - y
        w = w - lr * 2 * np.mean(err * x)
        b = b - lr * 2 * np.mean(err)
    return np.mean((w * x + b - y) ** 2)    # final loss


for lr in [0.0001, 0.001, 0.01, 0.03, 0.05]:
    print(f"lr {lr:<7} loss after 100 steps: {train(lr):.4g}")
Expected output
lr 0.0001  loss after 100 steps: 8.414
lr 0.001   loss after 100 steps: 0.01534
lr 0.01    loss after 100 steps: 0.01094
lr 0.03    loss after 100 steps: 0.007973
lr 0.05    loss after 100 steps: 6.635e+43

{lr:<7} pads the number on the right to 7 characters and :.4g prints 4 significant digits, switching to scientific notation for huge numbers. With 0.0001 the model has barely moved after 100 steps. 0.03 gets closest. 0.05 diverges: the loss reaches 6.6 times ten to the 43rd power, and after about 700 steps in total it would overflow to inf, then turn into nan ("not a number"). If you ever see a training loss shoot up or turn into nan, the learning rate is the first thing to lower.

Tip You will meet the same word when fine-tuning: LoRA fine-tuning of an LLM usually runs with a learning rate around 1e-4 (0.0001), and a run whose loss jumps or turns nan is fixed the same way, with a smaller learning rate.

6The same model with scikit-learn

Nobody writes gradient descent by hand for a straight line at work. scikit-learn (imported as sklearn) is the standard Python library for classic machine learning. Every model in it has the same two methods: fit(X, y) trains, predict(X) runs inference. Install it with uv add scikit-learn; the box below already has it, but the first run takes a few seconds while the browser downloads it.

LinearRegression finds the exact best line with a direct formula instead of many small steps. Run it and compare with the numbers gradient descent reached.

Try it: edit and run
import numpy as np
from sklearn.linear_model import LinearRegression

x = np.array([1, 2, 3, 4, 5, 6, 7, 8], dtype=float)
y = np.array([1.2, 2.3, 3.1, 4.0, 4.8, 5.9, 6.6, 7.7])

X = x.reshape(-1, 1)          # scikit-learn wants a 2-D X: 8 rows, 1 feature
model = LinearRegression()
model.fit(X, y)               # training
print(f"w {model.coef_[0]:.4f}  b {model.intercept_:.4f}")

new = np.array([[6.0], [12.0]])        # two new requests: 600 and 1200 tokens
for tokens, secs in zip(new[:, 0], model.predict(new)):   # inference
    print(f"{tokens * 100:.0f} tokens -> {secs:.2f} s")
Expected output
w 0.9071  b 0.3679
600 tokens -> 5.81 s
1200 tokens -> 11.25 s
  • x.reshape(-1, 1) turns the 8 numbers into 8 rows of 1 column. -1 means "work this number out for me". Passing a 1-D array to fit raises a ValueError asking for exactly this.
  • coef_ holds one weight per feature and intercept_ is the bias. A trailing underscore is scikit-learn's convention for "learned during fit".
  • zip pairs each input row with its prediction, so the loop prints them side by side.

Gradient descent after 2000 steps had w 0.9072, b 0.3678: almost exactly the answer. 1200 tokens is outside the data we trained on (1 to 8 hundred). The line happily extends, but nothing guarantees the real world does: models are only reliable on inputs that look like their training data.

Tip Same fit/predict shape for every scikit-learn model (trees, k-nearest neighbours, logistic regression). The next lesson swaps the model and keeps the rest of the code.

7Train, validation and test sets

A model that has seen an example can simply remember its answer. So the loss on the training data tells you how well it memorised, not how well it will do on new requests, which is the only thing that matters. The fix is to hold data back:

  • Training set (often about 60 to 80%): the only data fit sees.
  • Validation set (often 10 to 20%): used to choose between models and hyperparameters (learning rate, model type). You look at it many times.
  • Test set (often 10 to 20%): used once, at the very end, to report how good the chosen model is. If you keep choosing based on it, it quietly becomes a second validation set and its score stops being honest.

The box makes 40 fake requests, shuffles them with a seeded random generator (so you get the same numbers every run), splits them 24 / 8 / 8, and compares our line with a "memoriser" that answers every question with the label of the closest training example.

Try it: edit and run
import numpy as np

rng = np.random.default_rng(42)                  # seeded: same "random" data every run
x = rng.uniform(0, 10, size=40)                  # 40 reply lengths (hundreds of tokens)
y = 0.9 * x + 0.4 + rng.normal(0, 0.6, size=40)  # the true line plus noise

idx = rng.permutation(40)                        # the row numbers 0..39, shuffled
train, val, test = idx[:24], idx[24:32], idx[32:]
print("sizes:", len(train), len(val), len(test))


def fit_line(xs, ys):
    """The exact best line: the same answer LinearRegression gives."""
    w = np.mean((xs - xs.mean()) * (ys - ys.mean())) / np.mean((xs - xs.mean()) ** 2)
    b = ys.mean() - w * xs.mean()
    return lambda q: w * q + b


def fit_memorizer(xs, ys):
    """Remembers every training example and answers with the closest one's label."""
    def predict(q):
        nearest = np.abs(xs[:, None] - q[None, :]).argmin(axis=0)
        return ys[nearest]
    return predict


def mse(model, rows):
    return np.mean((model(x[rows]) - y[rows]) ** 2)


models = {"line": fit_line(x[train], y[train]),
          "memorizer": fit_memorizer(x[train], y[train])}
for name, m in models.items():
    print(f"{name:10} train {mse(m, train):.3f}   validation {mse(m, val):.3f}")

best = min(models, key=lambda name: mse(models[name], val))
print(f"picked {best}; test loss {mse(models[best], test):.3f}")
Expected output
sizes: 24 8 8
line       train 0.166   validation 0.267
memorizer  train 0.000   validation 0.433
picked line; test loss 0.131

The lines that matter:

  • rng.permutation(40) shuffles the row numbers, then slicing cuts them into three groups that never overlap. Shuffle first: data often arrives sorted (by date, by user), and an unshuffled split would test on a different kind of data.
  • lambda q: w * q + b is a one-line anonymous function, like q -> w * q + b in Java or (q) => w * q + b in JavaScript. Each fit_ function returns the trained model as a function.
  • xs[:, None] - q[None, :] uses broadcasting to get the distance from every training point to every query, and argmin(axis=0) picks the closest training point for each query.
  • min(models, key=...) picks the model name with the lowest validation loss.

The memoriser has a perfect training score of 0.000 and the worse validation score. That gap between training and validation is overfitting, and spotting it is the whole reason for the split. With only 8 rows the test number is noisy (here it happens to be better than validation); real test sets have hundreds or thousands of rows.

In a real project you split with scikit-learn: from sklearn.model_selection import train_test_split, then X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42), and call it again on the training part to cut off a validation set.

Watch out Never let test rows leak into training: no duplicates across the split, and no "fitting" anything (a scaler, a vocabulary) on the full data before splitting. The overfitting lesson shows how a leak makes a useless model look excellent.

8Supervised, unsupervised and self-supervised

The three big families differ in where the labels come from:

  • Supervised: people (or logs) provide the label for every example. Our latency data, spam filters, "is this ticket billing or a bug". Labels are expensive, so data sets are often small.
  • Unsupervised: no labels at all. The model finds structure by itself, for example clustering similar support tickets by their embeddings (k-means), or squashing hundreds of columns down to two to plot them.
  • Self-supervised: the labels are cut out of the data itself, so any amount of raw text becomes training data for free. This is how an LLM is pretrained.

For an LLM the task is next-token prediction: given the tokens so far, predict the next one. Every position in every document is one free training example: the tokens before it are the features, the token itself is the label. The box builds those examples from one sentence and "trains" the simplest possible language model by counting which word follows which.

Try it: edit and run
from collections import Counter, defaultdict

text = "the cat sat on the mat . the cat ate . the dog sat on the rug ."
tokens = text.split()                       # real LLMs use subword tokens, not words

pairs = list(zip(tokens, tokens[1:]))       # (this token, the next token)
print(len(tokens), "tokens ->", len(pairs), "training examples")
print(pairs[:3])

counts = defaultdict(Counter)               # counts[prev][next] = how often
for prev, nxt in pairs:
    counts[prev][nxt] += 1

after_the = counts["the"]
total = sum(after_the.values())
for word, n in after_the.most_common():     # most frequent first
    print(f"P({word!r} | 'the') = {n}/{total} = {n / total:.2f}")
print("sat ->", counts["sat"].most_common(1)[0][0])
Expected output
18 tokens -> 17 training examples
[('the', 'cat'), ('cat', 'sat'), ('sat', 'on')]
P('cat' | 'the') = 2/5 = 0.40
P('mat' | 'the') = 1/5 = 0.20
P('dog' | 'the') = 1/5 = 0.20
P('rug' | 'the') = 1/5 = 0.20
sat -> on
  • zip(tokens, tokens[1:]) pairs each token with the one after it, so 18 tokens give 17 examples with no human labelling.
  • defaultdict(Counter) is a dict that creates an empty Counter (a dict of counts) the first time you use a new key, so counts[prev][nxt] += 1 never raises a KeyError.
  • P('cat' | 'the') reads "the probability of cat, given the". !r prints the word with quotes.

This counting model only looks one word back. An LLM looks at thousands of previous tokens and learns its probabilities with gradient descent and cross-entropy loss instead of counting, but the output is the same kind of thing: a probability for every possible next token. Generating text is picking one token from that distribution, adding it to the input, and asking again. Temperature controls how adventurous that pick is.

After pretraining, chat models get two more rounds of training: supervised fine-tuning on example conversations written by people (supervised: prompt in, ideal answer as the label), then preference tuning (RLHF or DPO), where people rank answers and the model learns to prefer the better ones.

9Where an AI engineer meets this

You will rarely train an LLM, but these ideas are everywhere in AI engineering work:

  • Embeddings, rerankers and classifiers are trained models you call. Knowing what they were trained on tells you where they fail.
  • Fine-tuning (for example LoRA) is supervised training: you supply prompts with ideal answers as labels, pick a learning rate, and watch training and validation loss.
  • Small classic models still win for routing, spam, intent and guardrail checks: a logistic regression on embeddings answers in a millisecond and costs nothing per call.
  • Evals are test sets. When you tune a prompt, your examples play the role of training and validation data. Keep a held-out set you never tune on, or you will overfit your prompt.

The box shows that last point. classify stands in for an LLM with a prompt; each "prompt version" adds a keyword after looking at the mistakes on the dev set.

Try it: edit and run
tickets = [   # (text, correct label): your labelled eval set
    ("I was charged twice", "billing"), ("refund my order", "billing"),
    ("app crashes on login", "bug"), ("button does nothing", "bug"),
    ("invoice is wrong", "billing"), ("page shows error 500", "bug"),
    ("cancel my subscription", "billing"), ("screen goes blank", "bug"),
    ("why did my card fail", "billing"), ("upload keeps failing", "bug"),
]
dev, test = tickets[:6], tickets[6:]    # tune on dev, report on test


def classify(text, words):
    """Stands in for an LLM call with a prompt: 'billing' if any word matches."""
    return "billing" if any(w in text for w in words) else "bug"


def accuracy(data, words):
    return sum(classify(t, words) == label for t, label in data) / len(data)


versions = {"v1": ["charged"], "v2": ["charged", "refund"],
            "v3": ["charged", "refund", "invoice"]}
for name, words in versions.items():
    print(f"{name}  dev {accuracy(dev, words):.0%}")
print(f"v3  test {accuracy(test, versions['v3']):.0%}   <- the honest number")
Expected output
v1  dev 67%
v2  dev 83%
v3  dev 100%
v3  test 50%   <- the honest number
  • sum(classify(t, words) == label for ...) counts the right answers: in Python True adds as 1 and False as 0.
  • :.0% formats 0.5 as 50%.

Version 3 is perfect on the examples it was tuned on and gets half of the unseen tickets wrong, because "cancel" and "card" never appeared in dev. With a real LLM and a real prompt the gap is smaller but just as real. You will build a proper eval pipeline in the evals lab.

Tip Freeze your test set early, store it in version control, and only add to it, never pick and choose. Then a better score really means a better prompt or model.

Common mistakes

  • Judging a model by its score on the training data. A model can memorise its training set; only held-out data tells you how it does on new input.
  • Tuning on the test set, by trying settings or prompts until the test score looks good. Then it is just another validation set and the reported number is too optimistic.
  • A learning rate that is too high, so the loss grows or turns into nan. Lower it by 10 times and try again.
  • Feeding features on very different scales (token counts in the thousands next to 0/1 flags) to gradient descent without rescaling them.
  • Splitting without shuffling, or letting duplicates and preprocessing leak across the split, so test rows are not really unseen.
  • Passing a 1-D array as X to scikit-learn. It needs one row per example: use x.reshape(-1, 1) for a single feature.

Practice

Write the code, then press Check. Your work is saved in this browser.

1Write the loss

Write mse(pred, y) that returns the mean squared error between the predictions and the labels as a float: the average of (pred - y) ** 2. It must also accept plain Python lists (turn them into arrays with np.asarray).

Exercise
import numpy as np


def mse(pred, y):
    # your code here
    return 0.0


print(mse([2, 4], [1, 1]))
Hint

`pred, y = np.asarray(pred, dtype=float), np.asarray(y, dtype=float)`, then `return float(np.mean((pred - y) ** 2))`.

2One step downhill

Write gd_step(w, b, x, y, lr) that does one step of gradient descent for the line w * x + b with MSE loss and returns the new (w, b) as a tuple. Use the formulas from the lesson: err = w * x + b - y, grad_w = 2 * mean(err * x), grad_b = 2 * mean(err), then move each parameter by lr times its gradient, downhill.

Exercise
import numpy as np


def gd_step(w, b, x, y, lr):
    # your code here
    return w, b


x = np.array([1.0, 2.0, 3.0])
y = np.array([2.0, 4.0, 6.0])
print(gd_step(0.0, 0.0, x, y, 0.1))
Hint

Compute `err` first, then both gradients from the **same** `err`, and only then update: `return w - lr * grad_w, b - lr * grad_b`.

3Free labels from text

Self-supervised training makes its own labels. Write make_examples(tokens, context) that returns a list of (previous, next) pairs, where previous is a tuple of the context tokens just before position i and next is tokens[i], for every position that has context tokens before it. With ["a", "b", "c", "d"] and context 2 the answer is [(("a", "b"), "c"), (("b", "c"), "d")].

Exercise
def make_examples(tokens, context):
    # your code here
    return []


print(make_examples(["a", "b", "c", "d"], 2))
Hint

Loop `for i in range(context, len(tokens)):` and append `(tuple(tokens[i - context:i]), tokens[i])`.

Interview questions

Q1What is the difference between a parameter and a hyperparameter?

Parameters are the numbers training learns, such as the weights and bias of a model. Hyperparameters are the settings you choose before training, such as the learning rate, the number of steps, or the model type, and you choose them by comparing scores on the validation set.

Q2Explain gradient descent.

Start with any parameters, compute the loss on the training data, compute the gradient (how the loss changes with each parameter), move every parameter a small step in the opposite direction, scaled by the learning rate, and repeat until the loss stops falling. Neural networks train the same way, with the gradients computed by backpropagation.

Q3Why do you need separate validation and test sets?

The validation set is used again and again to choose models and hyperparameters, so the final choice is tuned to it and its score is slightly optimistic. The test set is touched once at the end, so it gives an honest estimate of performance on new data.

Q4What happens if the learning rate is too high or too low?

Too low and training converges very slowly or stalls. Too high and each step overshoots the minimum, so the loss oscillates or diverges, often ending in inf or nan. A common fix is to lower it by a factor of 10, or use a schedule that starts higher and decays.

Q5How is an LLM trained?

Pretraining is self-supervised next-token prediction on huge amounts of text: each position in a document is an example whose label is the next token, trained with cross-entropy loss and gradient descent. Then supervised fine-tuning on example conversations, and preference tuning such as RLHF or DPO, turn it into a helpful chat model.

Q6What is the difference between supervised, unsupervised and self-supervised learning?

Supervised learning trains on examples with labels given by people or logs. Unsupervised learning has no labels and finds structure such as clusters. Self-supervised learning creates labels from the data itself, for example by hiding the next word, which lets it use unlimited unlabelled data.