How Do You Build Your First Machine Learning Model?

The last post in a five-part series puts every idea to work. It walks a loan-approval project from data to a saved model, introduces the Python tools people use, runs real code you can paste into Google Colab, and shows how the same ideas scale up to the large language models behind chatbots.

This is the last post in a five-part series on machine learning from zero. The previous post covered how to choose a model and how to know it's any good. You don't have to read it first. The next section sums up the facts from the earlier posts that this one needs.

What you need from the earlier posts

  • Weights, bias, parameters. A model is a rule with blanks. A weight is a learned number multiplied with an input. A bias is a learned number added on its own. Together, they are the model's parameters.

  • The training loop. Training repeats five steps:

    1. Take a batch of examples.
    2. Predict.
    3. Measure how wrong the predictions were, as one number called the loss.
    4. Work out a gradient for every parameter: which way to move it, and how strongly.
    5. Nudge every parameter a little. The learning rate sets how big each nudge is.

    One full pass over the training data is an epoch. Backpropagation is how the gradients are found, by walking backward from the loss.

  • Neurons and layers. A neuron multiplies its inputs by weights, adds a bias, and applies a bend that turns negative numbers into 0. A layer is a group of neurons side by side. A neural network is layers connected one after another.

  • Classification and regression. Classification predicts a category, like approved or rejected. Regression predicts a number.

  • Logistic regression. It multiplies each input by a weight and adds a bias. Then the sigmoid squashes the result into a probability between 0 and 1. For a yes/no question, its loss is log loss.

  • Training, validation and test sets. The model learns from the training set. Candidates are compared on the validation set. The test set is used once, at the end.

  • Data leakage. The numbers used to prepare the data must come from the training set only. That means the averages used to fill gaps, and each column's average and spread (how widely its values vary) used for scaling. Otherwise the test score looks better than the truth.

  • Judging a model. Accuracy is the share of examples a model gets right. Overfitting is memorizing the training data: a high training score and a much lower validation score. Underfitting is low scores even on the training data. When one answer is rare, two other scores say more than accuracy. Precision is the share of "yes" flags that really were yes. Recall is the share of real "yes" cases the model caught.

  • Hyperparameters. Settings people choose before training, such as the number of layers, the learning rate and the batch size.

From ideas to a working model

So far, every model in this series was worked out by hand. Real projects use code. This post shows what that looks like, in four steps:

  1. The project in plain steps. A loan-approval model, from data to a saved file.
  2. The tools. Which Python libraries do which job.
  3. The code. The whole project, short enough to paste into a free online notebook and run.
  4. Scaling up. How the same ideas build the large language models behind chatbots.

A complete project, start to finish

Here is one realistic example: a model that predicts whether a loan should be approved.

Eight numbered steps joined by arrows: 1, understand the problem (10,000 applications); 2, split (train, validation, test); 3, prepare (numbers, fill gaps, scale), with a note that averages and spreads come from the training set only; 4, choose candidates; 5, train each one; 6, compare on validation; 7, test once, highlighted as used once; and 8, save and use.

The data

A bank has 10,000 past applications. Each one is a row like these two, taken from the data the code below makes:

incomedebtcredit_scoreyears_employedemployment_typeapproved
57300154006835salaried1
454002380067813self-employed0
..................

Step 1: Understand the problem

  • The inputs are income, debt, credit score, years employed and employment type.
  • The output is "approved", which is 1 (yes) or 0 (no).
  • The answer is a category, so this is a classification problem. The model should output a probability of approval, such as 0.83.

Step 2: Split the data

Divide the 10,000 applications into three sets: 7,000 for training, 1,500 for validation and 1,500 for testing.

Step 3: Prepare the data

  • Convert the employment type into a number: salaried → 0, self-employed → 1. It has only two values, so 0 and 1 are enough.
  • Fill in any missing values, for example with the average of that column. Work out the average from the training set only.
  • Scale the columns, so that income (in the thousands) doesn't overpower years employed (0 to 20). Again, take each column's average and spread from the training set only.

Step 4: Choose candidate models

Start simple, then try stronger options:

  1. Logistic regression as a baseline: a simple model the others have to beat. The data sets its structure: 5 inputs → 5 weights + 1 bias = 6 parameters. There is nothing to design.
  2. A tree-based model such as XGBoost, which often does very well on table data.
  3. A small neural network. Some parts of it are fixed, and some are your choice:
    • The input size is fixed by the data: 5 inputs.
    • The output size is fixed by the question: 1 probability.
    • The middle layers are a design choice. A reasonable start is 1 or 2 layers of 8 to 64 neurons each. There is no formula for the perfect size. You try a few options and compare them.

Step 5: Train each model

Each model is trained on the training set. Logistic regression and the network use the training loop. A tree-based model uses its own search for good questions instead.

Step 6: Compare on the validation set

Check each model's score on the validation set, and watch for overfitting and underfitting. Adjust the hyperparameters if needed, and pick the best model.

Step 7: Final check on the test set

Run the chosen model on the test set, once. This score is the honest estimate of how the model will do on new applicants.

Step 8: Save and use the model

Save the trained parameters to a file. The bank's app loads this file and uses it to predict approval for each new applicant. The parameters don't change while the model is in use. Once enough new data has been collected, the model can be trained again.

A word on fairness

The first post promised to come back to fairness. Here it is.

A model learns whatever patterns are in its data, including unfair ones. Suppose past loan decisions were unfair to some group of people. A model trained on those decisions can learn to repeat that unfairness.

Leaving the group out of the inputs doesn't fully fix this. Other columns, such as a home address, can quietly stand in for it. That's why real projects also compare the model's results across different groups of people, not just its overall accuracy.

The tools

Nobody writes all of this math by hand. In practice, machine learning is done in the Python programming language, using libraries: collections of ready-made code. You prepare the data, choose a model, and call the library's functions. The library takes care of the predictions, the loss, the gradients and the updates.

Which tool is used at which step

Step in a projectCommon tools
Load the datapandas
Explore the data and draw chartspandas, matplotlib
Prepare and split the datapandas, scikit-learn
Train the modelscikit-learn, XGBoost, or PyTorch
Measure how good the model isscikit-learn

Tools for working with data

  • NumPy does fast math on lists and grids of numbers. The weights of a layer form a grid, such as 5 inputs × 16 neurons. So this kind of math is everywhere in machine learning. Most other ML libraries are built on top of NumPy.
  • pandas is like a spreadsheet inside Python. It loads data into tables. It lets you view columns, work out averages, fill in missing values, filter rows and convert text into numbers. Most data preparation is done with pandas.
  • matplotlib draws charts. It is used to explore data, such as "how does income relate to approval?". It is also used to plot training, such as the loss going down over the epochs.

Tools for building and training models

  • scikit-learn is the standard library for classic machine learning, especially on table data. It includes linear regression, logistic regression, decision trees, random forests and many other models. It also has tools for splitting data and measuring accuracy. Every model has the same simple interface: fit() to train, and predict() to make predictions. The whole training loop is hidden inside fit(). It runs on a normal processor, so no special hardware is needed.
  • XGBoost and LightGBM are libraries for gradient-boosted trees. They are among the strongest options for table data. They work much like scikit-learn, with fit() and predict().
  • PyTorch is a library for neural networks, first created at Meta (then Facebook). You describe the network's layers, and you usually write the training loop yourself, so every step is visible. It is the most popular choice for AI research today.
  • TensorFlow is another library for neural networks, created by Google. It does the same job as PyTorch, in a different style. It was the most popular choice a few years ago and is still used in many existing systems. In research, most new work now uses PyTorch.
  • Keras is a simpler way to build neural networks. It makes them feel like scikit-learn, with a fit() method that hides the training loop. It began as part of TensorFlow. Keras 3 can also run on top of other libraries, including PyTorch.

What is a tensor?

You'll see the word tensor a lot. It's even part of the name "TensorFlow". A tensor is simply a grid of numbers. It can be a single number, a list, a table, or a stack of tables.

In PyTorch, tensors are like NumPy grids with two extra abilities:

  1. They can be processed on a GPU, which makes them much faster to work with. A GPU is a chip that does thousands of calculations at once.
  2. They record every calculation made with them. That record is what lets the library work out gradients automatically, through backpropagation.

Comparing the main libraries

scikit-learnPyTorchTensorFlow
Main useClassic ML on table dataNeural networks, modern AINeural networks
Training loopHidden inside fit()Usually written by youHidden (with Keras) or written by you
Needs a GPU?NoFor larger models, yesFor larger models, yes
Ease of getting startedEasiestModerateModerate
Typical usesLoan approval, spam, sales forecastsImages, text, LLMs, researchMany existing production systems

Other useful tools

NameWhat it is
Jupyter NotebookA coding environment where you write code in small blocks called cells, and see each cell's output right below it. It's ideal for exploring data step by step, and most ML work happens in notebooks.
Google ColabA free, online Jupyter notebook run by Google. There is nothing to install. It also offers free GPU access, with usage limits that Google doesn't publish and that can change. It's the easiest place to start.
Hugging FaceA website and library where people share models that are already trained, especially language models. You can download one and use it directly, or adapt it to your own task.
KaggleA website with thousands of free datasets, competitions and example notebooks. A great source of practice projects.

A suggested learning path

  1. Start with pandas and scikit-learn in Google Colab. It's the quickest way to see splitting, training, testing, overfitting and learned weights in action.
  2. Move on to PyTorch. Build a small neural network and write the training loop yourself. This makes gradient descent and backpropagation concrete.
  3. Leave TensorFlow for later, unless a job or project needs it. The ideas carry over directly from PyTorch.

The code

Here is the loan project in real Python. Open a new notebook in Google Colab, paste each block into its own cell, and run them from top to bottom. Colab already has every library used here.

The outputs shown below each block come from a real run. It used Python 3.13, NumPy 2.5, pandas 3.0, scikit-learn 1.9 and PyTorch 2.14. A different version may print slightly different numbers. The ideas don't change.

Step 0: Make some data

A real bank's data is private. So this first block makes up 10,000 loan applications. It doesn't download anything.

Each application gets a random income, debt, credit score, years employed and employment type. A hidden, made-up rule then decides whether it was approved. The rule gives points for income, credit score and years employed. It takes points away for debt, and for being self-employed. Some random noise is added, so the rule isn't perfectly clean, just like real decisions. Finally, about 3% of the incomes are blanked out, so there are gaps to fill.

import numpy as np
import pandas as pd

def make_loans(n=10_000, seed=0):
    rng = np.random.default_rng(seed)   # fixed seed: same "random" data every run
    income = rng.normal(55_000, 18_000, n).clip(12_000, 150_000).round(-2)
    debt = rng.normal(12_000, 7_000, n).clip(0, 60_000).round(-2)
    credit_score = rng.normal(660, 70, n).clip(300, 850).round()
    years_employed = rng.integers(0, 21, n)
    employment_type = rng.choice(["salaried", "self-employed"], n, p=[0.7, 0.3])

    # The made-up rule behind every decision, plus some noise
    points = (income / 10_000 - debt / 5_000 + (credit_score - 650) / 20
              + years_employed / 5 - (employment_type == "self-employed"))
    approved = (points + rng.normal(0, 1.5, n) > 5).astype(int)

    df = pd.DataFrame({
        "income": income, "debt": debt, "credit_score": credit_score,
        "years_employed": years_employed, "employment_type": employment_type,
        "approved": approved,
    })
    df.loc[rng.random(n) < 0.03, "income"] = np.nan   # blank out about 3% of incomes
    return df

The model never sees this rule. It only sees the 10,000 finished rows, just as a bank's model only sees past decisions. Later, we can check whether it found the rule on its own.

Step 1: Look at the data with pandas

df = make_loans()
print(df.head())                      # the first 5 rows
print(round(df["income"].mean()))     # the average income
print(df["income"].isna().sum())      # how many incomes are missing
print(df["approved"].mean())          # the share of applications approved

Output:

    income     debt  credit_score  years_employed employment_type  approved
0  57300.0  15400.0         683.0               5        salaried         1
1  52600.0   2600.0         739.0              14        salaried         1
2  66500.0   4200.0         670.0              11        salaried         1
3  56900.0   8800.0         700.0               2   self-employed         1
4  45400.0  23800.0         678.0              13   self-employed         0
55179
316
0.5248

So 316 incomes are missing, and 52.48% of applications were approved. Keep that last number in mind. A useless model that always says "approve" would already score about 52%.

This block only looks at the data. It doesn't fill in the missing incomes yet. That has to wait until after the split.

Step 2: Train a logistic regression with scikit-learn

This block does steps 2 to 6 of the project for the first candidate. It splits, prepares, trains, and scores on the validation set.

from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

X = df[["income", "debt", "credit_score", "years_employed", "employment_type"]].copy()
y = df["approved"]                    # the correct answers (0 or 1)

# Text to numbers. The list of values is fixed, so this learns nothing from the data.
X["employment_type"] = (X["employment_type"] == "self-employed").astype(int)

# 1. Split first: 70% training, 15% validation, 15% test
#    (random_state fixes the shuffle, so every run gives the same split)
X_train, X_rest, y_train, y_rest = train_test_split(X, y, test_size=0.3, random_state=42)
X_val, X_test, y_val, y_test = train_test_split(X_rest, y_rest, test_size=0.5, random_state=42)

# 2. Fill in missing values with averages from the training set only
train_averages = X_train.mean()
X_train = X_train.fillna(train_averages)
X_val = X_val.fillna(train_averages)
X_test = X_test.fillna(train_averages)

# 3. Scale, using averages and spreads from the training set only
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)   # learn them, then scale the training set
X_val = scaler.transform(X_val)           # same numbers for the validation set
X_test = scaler.transform(X_test)         # and for the test set

model = LogisticRegression()
model.fit(X_train, y_train)               # TRAINING: the whole loop runs inside this line

print(model.coef_.round(2))               # the learned weights, one per input
print(model.intercept_.round(2))          # the learned bias
print(round(model.score(X_train, y_train), 3))   # accuracy on the training set
print(round(model.score(X_val, y_val), 3))       # accuracy on the validation set

Output:

[[ 2.   -1.56  4.03  1.41 -0.56]]
[0.31]
0.894
0.89

What to notice:

  • train_test_split is called twice. The first call keeps 70% for training and sets 30% aside. The second call splits that 30% in half, into validation and test. That gives 7,000, 1,500 and 1,500.
  • model.fit() runs the whole training loop. It predicts, measures the loss, and adjusts the parameters, over and over until it's done. Inside, scikit-learn uses a faster relative of gradient descent. The idea is the same: keep adjusting the parameters to make the loss smaller.
  • coef_ holds the five learned weights, in the same order as the columns: income, debt, credit score, years employed, employment type. intercept_ is the learned bias.
  • The model found the hidden rule's directions on its own. Income, credit score and years employed got positive weights. Debt and being self-employed got negative ones. That is exactly how the made-up rule worked, and the model only ever saw finished rows.
  • The weights are a little smaller than a plain best fit would give. By default, LogisticRegression adds a small penalty for large weights. That's the regularization from post 4.
  • The averages and spreads come from X_train only. The validation and test sets are then filled in and scaled with those same numbers. That avoids data leakage.
  • model.score() returns the accuracy: the share of applications the model got right. It's 89.4% on training and 89% on validation. The gap is tiny, so there's no sign of overfitting. And 89% is far above the 52% of always saying "approve".

Step 3: Count the parameters in a layer with PyTorch

Before building a network, let's check one layer's parameter count. A layer where 3 inputs connect to 2 neurons should have 3 × 2 = 6 weights, plus 2 biases.

import torch.nn as nn

layer = nn.Linear(in_features=3, out_features=2)   # 3 inputs connected to 2 neurons

print(layer.weight.shape)                          # the grid of weights
print(layer.bias.shape)                            # one bias per neuron
print(sum(p.numel() for p in layer.parameters()))  # all the parameters together

Output:

torch.Size([2, 3])
torch.Size([2])
8

The weights are a grid of 2 × 3 = 6, there are 2 biases, and 8 parameters in total.

Step 4: Build a neural network with PyTorch

In code, you don't connect neurons one by one. You describe layers, and the library connects them. The standard layer, nn.Linear, connects every input to every neuron. You only choose how many neurons each layer has.

import torch
import torch.nn as nn

torch.manual_seed(0)   # fixed seed: the same random starting weights every run

net = nn.Sequential(
    nn.Linear(5, 16),   # 5 inputs → 16 neurons (each neuron receives all 5 inputs)
    nn.ReLU(),          # the bend: negative values become 0
    nn.Linear(16, 8),   # 16 → 8 neurons
    nn.ReLU(),
    nn.Linear(8, 1),    # 8 → 1 output
    nn.Sigmoid(),       # the squash: turns the output into a probability
)
print(sum(p.numel() for p in net.parameters()))   # count every parameter

Output:

241

Here's where 241 comes from:

LayerWeightsBiasesTotal
Linear(5, 16)5 × 16 = 801696
Linear(16, 8)16 × 8 = 1288136
Linear(8, 1)8 × 1 = 819
Whole network241

When the network is created, all 241 parameters start as small random numbers. Training then adjusts them.

The small sleep-and-study network from post 3 (2 inputs, 3 neurons, 1 output) would be written like this:

nn.Sequential(nn.Linear(2, 3), nn.ReLU(), nn.Linear(3, 1))   # 9 + 4 = 13 parameters

Can you connect certain neurons only to certain others? It's possible, but it's rarely done by hand. Instead, researchers have designed special layer types with built-in connection patterns. For example, layers designed for images connect each neuron only to a small patch of nearby pixels. You choose which layer types to use, not single connections. And if a connection turns out to be useless, training can simply push its weight close to 0.

Step 5: Write the training loop

In PyTorch, you usually write the training loop yourself, so every step is visible. This loop uses real batches of 32, shuffled before every epoch.

# Convert the data into PyTorch tensors
X_train_t = torch.tensor(X_train, dtype=torch.float32)
y_train_t = torch.tensor(y_train.values, dtype=torch.float32).unsqueeze(1)
X_val_t = torch.tensor(X_val, dtype=torch.float32)
y_val_t = torch.tensor(y_val.values, dtype=torch.float32).unsqueeze(1)

optimizer = torch.optim.SGD(net.parameters(), lr=0.1)   # gradient descent, learning rate 0.1
loss_fn = nn.BCELoss()                                  # log loss, for yes/no questions
batch_size = 32

for epoch in range(1, 51):                              # 50 epochs
    order = torch.randperm(len(X_train_t))              # shuffle the training examples
    for start in range(0, len(order), batch_size):
        batch = order[start:start + batch_size]         # 1. take a batch of 32
        predictions = net(X_train_t[batch])             # 2. predict
        loss = loss_fn(predictions, y_train_t[batch])   # 3. measure the loss (one number)
        optimizer.zero_grad()                           #    clear the old gradients
        loss.backward()                                 # 4. backpropagation: a gradient for every parameter
        optimizer.step()                                # 5. nudge every parameter a little

    if epoch % 10 == 0:
        with torch.no_grad():                           # just measuring, not training
            train_loss = loss_fn(net(X_train_t), y_train_t).item()
            val_loss = loss_fn(net(X_val_t), y_val_t).item()
        print(f"epoch {epoch}: training loss {train_loss:.3f}, validation loss {val_loss:.3f}")

with torch.no_grad():
    val_accuracy = ((net(X_val_t) > 0.5).float() == y_val_t).float().mean().item()
print(round(val_accuracy, 3))

Output:

epoch 10: training loss 0.238, validation loss 0.241
epoch 20: training loss 0.235, validation loss 0.239
epoch 30: training loss 0.238, validation loss 0.248
epoch 40: training loss 0.236, validation loss 0.242
epoch 50: training loss 0.236, validation loss 0.237
0.893

The first four lines convert the data into tensors:

  • torch.tensor(X_train, dtype=torch.float32) turns the scaled inputs into a tensor of decimal numbers, the kind PyTorch works with.
  • torch.tensor(y_train.values, dtype=torch.float32).unsqueeze(1) does the same for the answers. They must be decimals, because the loss compares them with probabilities. .unsqueeze(1) turns the flat list of 7,000 answers into one column, so it has the same shape as the network's output.

The rest of the loop is the one from post 2:

  • torch.randperm shuffles the order of the training examples before each epoch. Slicing that order into groups of 32 gives the batches. 7,000 examples make 219 batches per epoch, the last one smaller.
  • SGD stands for stochastic gradient descent. "Stochastic" means random. The name comes from training on randomly shuffled batches.
  • lr=0.1 is the learning rate. It's a hyperparameter, so we picked it. You could try others and compare them on the validation set.
  • optimizer.zero_grad() clears the gradients from the previous batch, so they don't pile up.
  • net(X_val_t) > 0.5 applies the cut-off: a probability above 0.5 means "approve".

Many tutorials use torch.optim.Adam instead of SGD. Adam is a smarter version of gradient descent. It adjusts the step size for each parameter on its own, which often makes training faster. The loop stays exactly the same.

Reading the output. By epoch 10, the training loss had already levelled off at about 0.24. It barely moves after that. The validation loss never pulls away from the training loss, so the network isn't overfitting.

How the code connects to the ideas in this series:

CodeIdea
order[start:start + batch_size]A batch
net(X_train_t[batch])Prediction
loss_fn(predictions, ...)The loss (log loss)
loss.backward()Backpropagation: working out the gradients
optimizer.step()The gradient descent update
lr=0.1The learning rate
for epoch in range(1, 51)Epochs

Step 6: Pick a winner, then test it once

On the validation set, the network scores 0.893 and logistic regression scores 0.89. That's 1,339 against 1,335 correct out of 1,500, a difference of 4 applications.

Why are they so close? The hidden rule that made the data is a multiply-and-add rule. A multiply-and-add model can already capture it, so the network has nothing extra to find. That's common with table data.

When two models score about the same, the simpler one usually wins. It's faster, and its weights can be explained to an applicant. So we pick logistic regression, and run it on the test set, once:

print(round(model.score(X_test, y_test), 3))   # the test set, used once, on the chosen model

Output:

0.9

90% on applications the model never saw while training or choosing. That's close to its validation score, so the estimate holds up.

Scaling up: from 13 parameters to 8 billion

Everything in this series also applies to the largest AI systems. They are just much, much bigger.

Counting the parameters

A layer has (number of inputs × number of neurons) weights, plus one bias per neuron. Step 3 above checked that: 3 inputs and 2 neurons give 6 weights and 2 biases, so 8 parameters.

Large models are counted the same way. Their layers just have thousands of inputs and thousands of neurons, and there are many layers.

Large language models

Large language models, or LLMs, are the kind of model behind AI chatbots. Their size is usually given as a number of parameters. For example, Meta's Llama 3 8B has about 8 billion parameters. Counted from its published settings, it is 8.03 billion.

Language models split text into small pieces called tokens: whole words or parts of words. Where do all those parameters live?

  • Most are weights inside the model's many layers. In LLMs, these are mainly two kinds of layers:
    • Feed-forward layers are the kind this series has built: every input connects to every neuron.
    • Attention layers let each token look at the other tokens in the text, and pick out the ones that matter to it. How they work is a topic of its own.
  • A noticeable share is in the embedding table. Each token has its own learned list of numbers, called an embedding, which stands for that token inside the model. Llama 3 8B knows 128,256 tokens, each with a list of 4,096 numbers. That's 128,256 × 4,096 ≈ 525 million parameters, about 6.5% of the model.

Parameters take up memory

Every parameter is a number that has to be stored. So a model's size directly sets how much computer memory it needs:

How each number is storedBytes per parameterMemory for an 8-billion-parameter model
16-bit numbers2 bytesAbout 16 GB
4-bit numbers0.5 bytesAbout 4 GB

These numbers cover only the parameters. Actually running the model needs some extra memory on top.

Storing parameters with fewer bits is called quantization. It makes the model a little less accurate, but it greatly cuts the memory needed. That's why it is popular for running large models on ordinary computers.

How LLMs are trained

LLMs are trained with the same loop as everything in this series: predict, measure the loss, work out the gradients, nudge the parameters, and repeat. Their training task is surprisingly simple. Given some text, predict the next token. Doing this over enormous amounts of text, with billions of parameters, is what lets them learn grammar, facts and patterns of reasoning.

Notice where the correct answers come from. Nobody labels the text by hand. The next token is already in the text, so the text provides its own answers. This is called self-supervised learning. Supervised learning means learning from examples that come with correct answers, called labels. Self-supervised learning is the same, except the labels come for free.

New words in this post

WordMeaning
LibraryA collection of ready-made code
TensorA grid of numbers, as used in PyTorch and TensorFlow
GPUA chip that does thousands of calculations at once; it makes training neural networks much faster
Notebook (cell)A coding environment of small code blocks, each showing its output below it
SGD (stochastic gradient descent)Gradient descent on randomly shuffled batches
AdamA smarter version of gradient descent that sets each parameter's step size on its own
LLM (large language model)A very large neural network trained on text to predict the next token
TokenA small piece of text, a word or part of a word, as a language model sees it
EmbeddingA learned list of numbers that stands for one token inside a model
QuantizationStoring parameters with fewer bits, to save memory
Self-supervised learningSupervised learning where the data provides its own answers

The whole series in 10 points

  1. Machine learning means learning rules from examples, instead of writing the rules by hand.
  2. A model is a rule with blanks. The blanks are its parameters: weights (multiplied with inputs) and biases (added on).
  3. Training finds good values for the parameters. Prediction uses them on new inputs.
  4. Training is a loop. Take a batch, predict, and measure the loss. Work out a gradient for every parameter, and nudge every parameter a little. Repeat for many epochs. This is gradient descent.
  5. A multiply-and-add rule can only learn straight lines. Neurons with a bend, arranged in layers, can learn curves. That is a neural network.
  6. Gradients come from multiplying simple rates along the chain from each parameter to the loss. Backpropagation does it for every parameter in one backward sweep.
  7. People choose the structure and the hyperparameters. Training finds the parameters.
  8. Problems are classification (a category) or regression (a number). Not every model is a neural network. For table data, simple and tree-based models are often best.
  9. Split the data into training, validation and test sets first. Then prepare it using numbers from the training set only.
  10. Always judge a model on hidden data. High training but low validation scores mean overfitting. Low scores on both mean underfitting. When one answer is rare, check precision and recall, not just accuracy.

Where to go next

  1. Build your first model on real data. Use pandas and scikit-learn in Google Colab on a real dataset, such as a loan approval dataset from Kaggle. Its column names will differ, so change the names in the code to match. Compare training and validation accuracy, and print the learned weights.
  2. Train a neural network yourself. Use PyTorch to build a small network and write the loop by hand. Watch the loss go down. Then try making the network much bigger, with very little data, to see overfitting happen.
  3. Learn how text becomes numbers. Study tokens and embeddings, which are how language models represent text. What Fills Your Context Window is a good start on tokens.
  4. Learn how LLMs are trained. It's the same training loop from this series, applied to predicting the next token over huge amounts of text.
  5. Learn the difference between pre-training, fine-tuning and RAG.
    • Pre-training: training a model from scratch on a huge amount of general data.
    • Fine-tuning: continuing to train an existing model on a smaller, specific dataset, which changes its weights.
    • RAG (retrieval-augmented generation): leaving the model's weights alone, and instead finding relevant information and giving it to the model along with each question. What Is RAG, and Why Does Your LLM Need It? explains how it works.