part I · chapter 1 of 17

Python and ML fundamentals

The language of the AI ecosystem, and what it means for a model to learn something.

why it matters

Almost every AI library, example and model tool is Python first, and the basic maths makes every later chapter easier.

in this chapter · 8 sections
  1. 1.1Why Python, when you already have TypeScript
  2. 1.2The Python you actually need
  3. 1.3The data tools
  4. 1.4What machine learning actually is
  5. 1.5Neural networks in one page
  6. 1.6The maths for this chapter
  7. 1.7Build it: a classifier in a notebook
  8. 1.8Where people go wrong

If you already write TypeScript for a living, this chapter is not about learning to program again. It is about two smaller things: picking up the language the AI world happens to speak, and getting a working picture of what "a model learned something" actually means. Both pay off in every chapter after this one.

We keep it short on purpose. The goal is to stop feeling like a tourist in Python and to read a machine learning paper's first page without bouncing off it. The deeper maths comes in small notes alongside the chapters, so nothing here has to be learned all at once.

Why Python, when you already have TypeScript

The product you build in this guide will probably still have a TypeScript backend and a TypeScript front end. That is fine, and it is often the right call. But almost everything around the model is Python first:

  • The model libraries (PyTorch, Hugging Face Transformers, vLLM) are Python.
  • New research code, evaluation harnesses and data tools appear in Python months before anything else.
  • Most examples you will read, and most notebooks people share, are Python.

So the practical split looks like this. Python is your lab: experiments, data preparation, evaluation scripts, fine-tuning, anything that touches a model's weights. TypeScript stays your product: the API, the UI, the business rules. A good AI engineer moves between the two without ceremony, and the boundary between them is usually an HTTP call or a queue.

The Python you actually need

You do not need all of Python. You need the parts that show up in AI code, and most of them map onto something you already know.

Environments and packages

Every project gets its own environment, the way every Node project gets its own node_modules. The modern, fast way is uv:

uv init support-bot && cd support-bot
uv add numpy pandas scikit-learn pydantic
uv run python main.py

The older way (python -m venv .venv, then pip install) still works and you will see it everywhere. The rule is the same either way: never install into the system Python, and commit the lock file.

Type hints and Pydantic

Python is dynamically typed, but modern AI code is written with type hints, and you should write it that way too. Hints alone check nothing at runtime. Pydantic is what does, and it plays the role Zod plays in TypeScript: a schema that parses and validates untrusted data.

from pydantic import BaseModel, Field
 
class Ticket(BaseModel):
    category: str
    priority: int = Field(ge=1, le=5)
    summary: str
 
ticket = Ticket.model_validate_json(model_output)  # raises if the shape is wrong

This matters more in AI work than anywhere else, because the thing producing your data is a model, and a model will eventually return something that is not quite the shape you asked for. Chapter 4 leans on this heavily.

async and asyncio

Calling a model is network I/O, and you will often make many calls at once: embedding a hundred chunks, running an evaluation over two hundred questions. Python's asyncio is the same idea as JavaScript's event loop, with one difference that catches people: nothing runs concurrently unless you ask for it.

import asyncio
 
async def embed_all(chunks: list[str]) -> list[list[float]]:
    # asyncio.gather is Promise.all
    return await asyncio.gather(*(embed(c) for c in chunks))

In JavaScript every promise starts the moment it is created. In Python a coroutine does nothing until it is awaited or scheduled, so a plain loop of await calls runs one at a time. When something is mysteriously slow, look for that first.

Generators

A generator produces values one at a time with yield, instead of building a whole list. You will meet them as soon as you stream a model's answer token by token, which is how every chat interface works:

for event in client.stream(prompt):
    print(event.text, end="", flush=True)

Decorators and comprehensions

Decorators (@retry, @tool, @app.post("/ask")) wrap a function with extra behaviour. Agent frameworks use them to turn an ordinary function into a tool a model can call, which you will see in chapter 7. Comprehensions are Python's compact map and filter: [c.text for c in chunks if c.score > 0.7]. Read them left to right as "give me this, for each of these, when that".

The data tools

NumPy: arrays, shapes and broadcasting

NumPy is the reason Python is fast enough for numeric work. A NumPy array is a block of numbers of one type, and operations on it run in compiled code instead of a Python loop. The habit to build is thinking in shapes:

import numpy as np
 
E = np.random.rand(10_000, 384)   # 10,000 embeddings, 384 numbers each
q = np.random.rand(384)           # one query embedding
scores = E @ q                    # shape (10_000,): one score per document
top5 = np.argsort(-scores)[:5]

That one line, E @ q, is a brute-force vector search over ten thousand documents. Chapter 5 builds on exactly this, and maths note 3 explains why it works.

Pandas: a table in memory

A Pandas DataFrame is a table with named columns, and you can think of it as SQL you run in memory: filter rows, group, join, aggregate. You will use it to clean documents before ingestion, to look at evaluation results, and to answer questions like "which category of question does the assistant get wrong most often".

Jupyter: the lab bench

A notebook lets you run code a cell at a time and keep the results on screen. It is the right tool for exploring data and trying a model, and the wrong tool for anything that has to run twice. Once an experiment works, move it into a plain .py file with a test.

What machine learning actually is

Strip away the vocabulary and machine learning is this: instead of writing a function by hand, you choose a family of functions with adjustable numbers in them, and let data choose the numbers.

The adjustable numbers are called parameters (or weights). A spam filter might have a few thousand. A large language model has billions. The process of choosing them is training, and using the trained function on new input is inference.

Supervised and unsupervised learning

In supervised learning, every example comes with the right answer. You show the model ten thousand emails labelled spam or not spam, and it learns to predict the label. When the answer is a category it is classification; when it is a number (a price, a delivery time) it is regression.

In unsupervised learning there are no labels, and the model finds structure on its own. Clustering groups similar items together, which is useful for spotting the five kinds of question your users actually ask.

Language models are trained in a third way that sits between the two: the label is simply the next word of real text, so the data labels itself. Chapter 2 picks this up.

Loss, and learning by going downhill

To train anything you need a way to score how wrong the model is. That score is the loss. For a regression model a common choice is the mean squared error over nn examples:

L(θ)=1n∑i=1n(yi−y^i)2L(\theta) = \frac{1}{n} \sum_{i=1}^{n} \left( y_i - \hat{y}_i \right)^2

where yiy_i is the right answer, y^i\hat{y}_i is the model's prediction and θ\theta stands for all the parameters. Training is the search for the θ\theta that makes LL small.

The search method behind almost all of modern AI is gradient descent. The gradient ∇θL\nabla_\theta L points in the direction that increases the loss fastest, so you take a small step the other way, and repeat:

θ←θ−η ∇θL(θ)\theta \leftarrow \theta - \eta \, \nabla_\theta L(\theta)

The step size η\eta is the learning rate. Too large and the loss jumps around or explodes; too small and training crawls. When you fine-tune a model in chapter 11, the learning rate is one of the first numbers you will set, and now you know what it does.

gradient descent, step by step

θ = 3, the bottomstartθ (the parameter)loss

the steps

  1. step 0θ = -2.00
  2. step 1θ = 1.00
  3. step 2θ = 2.20
  4. step 3θ = 2.68
  5. step 4θ = 2.87
  6. step 5θ = 2.95
  7. step 6θ = 2.98
  8. step 7θ = 2.99
  9. step 8θ = 3.00
About right: big steps while the slope is steep, small ones near the bottom. It settles at θ = 3.

Overfitting, and why you hold data back

A model with enough parameters can memorise its training data and still be useless on anything new. That is overfitting. The defence is simple and non-negotiable: split your data, train on one part, and judge the model only on the part it never saw. The same discipline returns in chapter 12 as evaluation sets for AI applications, where the temptation to "just tweak the prompt until the test passes" is exactly overfitting by hand.

Neural networks in one page

A neural network is a stack of simple layers. Each layer multiplies its input by a matrix of weights, adds a bias, and passes the result through a small non-linear function:

h=σ(Wx+b)\mathbf{h} = \sigma(W\mathbf{x} + \mathbf{b})

The non-linearity matters. Without it, a stack of layers collapses into one big matrix multiplication and can only learn straight-line relationships. With it, enough layers can approximate almost any function. A classic choice is the sigmoid, which squashes any number into the range zero to one:

σ(x)=11+e−x\sigma(x) = \frac{1}{1 + e^{-x}}

Deep learning is just this with many layers, trained by gradient descent, where the gradient for every weight is computed by backpropagation (the chain rule from calculus, applied backwards through the layers). A transformer, the architecture behind every model in chapter 2, is a particular way of arranging these layers. Nothing in it is magic; there is just a great deal of it.

The maths for this chapter

Maths note 1 is notation, exponentials and logarithms, and one idea from it is worth seeing in full now because it explains something you will meet in every model API.

A model assigns a probability to each token it writes. The probability of a whole answer is the product of those probabilities, and products of many small numbers quickly become too small for a computer to hold. Multiply fifty probabilities of 0.010.01 and the true answer is 10−10010^{-100}, which a 32-bit float rounds to zero.

Logarithms fix this, because they turn products into sums:

log⁡∏i=1npi=∑i=1nlog⁡pi\log \prod_{i=1}^{n} p_i = \sum_{i=1}^{n} \log p_i

Fifty logs of 0.010.01 add up to about −230-230, a perfectly ordinary number. This is why models work in log-probabilities, why APIs return a logprobs field rather than probabilities, and why the training loss in chapter 11 is written with a log in it. Try the underflow yourself:

import math
p = [0.01] * 50
math.prod(p)               # 1e-100 in float64, 0.0 in float32
sum(math.log(x) for x in p)  # about -230.26

Build it: a classifier in a notebook

The exercise is small on purpose: the goal is to have trained, evaluated and inspected a model yourself, end to end, once.

  1. Pick a small labelled dataset. Scikit-learn ships a few (load_iris, load_breast_cancer), or take a CSV of support tickets with a category column.
  2. Load it into Pandas and look at it: how many rows, how many of each label, any missing values.
  3. Split it into training and test sets, and do not touch the test set again until the end.
  4. Train a simple model (logistic regression, then a random forest).
  5. Measure accuracy on the test set, then print the confusion matrix and look at what it gets wrong.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
 
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
 
model = LogisticRegression(max_iter=5000).fit(X_train, y_train)
print(classification_report(y_test, model.predict(X_test)))

The point is not the accuracy number. It is the shape of the work: data in, split, fit, measure on held-out data, look at the failures. Every AI feature you build later follows the same loop, only with a bigger model and messier data.

Where people go wrong

  • Trying to learn all of Python first. Learn what this chapter lists, then learn the rest when a real task needs it.
  • Treating notebooks as production. Hidden state between cells makes results impossible to reproduce. Move working code into files.
  • Skipping the held-out set. A model judged on its own training data always looks better than it is.
  • Avoiding the maths entirely. You do not need much, but the little you need (logs, vectors, gradients) shows up everywhere. The maths notes exists so it arrives a piece at a time.

you reached the end of the chapter

build this

A small Pandas and scikit-learn classifier in a notebook.

the maths underneath

  • maths note 1

    Notation, functions, exponentials and logs

    log⁡∏ipi=∑ilog⁡pi\log \prod_i p_i = \sum_i \log p_i

    Every later formula is written in this notation, and logs are why a model can multiply a thousand tiny probabilities without them rounding to zero.

check yourself

Tick what you could explain to someone else, out loud, without notes.