---
title: A complete example
date: 2026-10-29
authors: [you]
category: Tutorials
tags: [guide, writing]
summary: Every feature of the Markdown renderer in one post, each used where a paper would use it.
# Sections numbered 1, 1.1, …, here and in the contents list.
numbered: true
# Equations, figures and the rest counted within each section: (2.1), Figure 4.1.
numberWithin: section
# Shorthands for this post's maths, on top of the site's \R, \E, \argmin and the rest.
macros:
  # Quoted: in YAML a space before # starts a comment.
  \KL: 'D_{\mathrm{KL}}\left(#1 \,\Vert\, #2\right)'
  \loss: \mathcal{L}
---

> All models are wrong, but some are useful.
>
> — George E. P. Box, *Robustness in Statistics*

This post fits a logistic regression and reports on it, using every feature
the renderer has along the way. The numbers are made up for the example. Rest
the pointer on any reference below, "Figure 4.1" or "(2.1)" or a citation, and it
shows what it points at.

## Introduction

Quotes and dashes are shown as typed on this site. With `smartQuotes: true` in
a post's frontmatter, or `typography.smartQuotes` in the site config, "the
model," she said, "isn't done" -- see pages 10--12 --- would be set with curly
quotes, an en dash and an em dash, while code such as `print("isn't")` kept what
was typed.

An empty link to another post writes its title: [Writing like a paper](https://blog.kiarashs.ir/blog/writing-like-a-paper)
covers the basics, and [Math and citations](https://blog.kiarashs.ir/blog/math-and-citations) the maths. One to a section
here writes its number: the method is in [Section 3](https://blog.kiarashs.ir/blog/a-complete-example/#method), the results in
[Section 4](https://blog.kiarashs.ir/blog/a-complete-example/#results). A citation works as before [@knuth1984literate], and so does a
footnote, which on a wide screen stands in the margin.[^margin]

[^margin]: Numbered sections are asked for with `numbered: true` in the
    frontmatter; most posts do not need them.

## Theory

The symbols used throughout:

$X$
: The $n \times d$ matrix of inputs, one example to a row.

$y$
: The labels, each $0$ or $1$.

$w$
: The weights, the model's only parameters.

$\sigma$
: The logistic function, which maps a score to a probability.

### The loss

> [!DEFINITION] Cross-entropy
> For labels $y_i \in \{0, 1\}$ and predictions $p_i = \sigma(x_i^\top w)$, the
> loss of weights $w \in \R^d$ is
>
> $$
> \loss(w) = -\frac{1}{n} \sum_{i=1}^{n} \Big[ y_i \log p_i + (1 - y_i) \log (1 - p_i) \Big].
> \label{loss}
> $$

`\loss` and `\KL` are this post's own macros, defined in its frontmatter; `\R`
and `\E` come with the site. Minimising [(2.1)](https://blog.kiarashs.ir/blog/a-complete-example/#eq-loss) is the same as minimising
$\E_{x}\big[\KL{p_{\text{true}}}{p_w}\big]$, up to a constant.

Its derivatives share a number, (2.2a) and (2.2b), as related equations do in
a paper:

$$
\label{derivatives}
\begin{subequations}
\nabla \loss(w) &= X^\top (p - y) / n \label{gradient} \\
\nabla^2 \loss(w) &= X^\top S X / n \label{hessian}
\end{subequations}
$$

> [!THEOREM] Convexity
> $\loss$ is convex in $w$, so gradient descent with a small enough step
> reaches its minimum $\hat w = \argmin_w \loss(w)$.

> [!PROOF] of [Theorem 2.2](https://blog.kiarashs.ir/blog/a-complete-example/#thm-convex)
> The Hessian is [(2.2b)](https://blog.kiarashs.ir/blog/a-complete-example/#eq-hessian), with $S = \operatorname{diag}\big(p_i (1 - p_i)\big)$,
> and $v^\top X^\top S X v = \lVert S^{1/2} X v \rVert^2 \ge 0$ for every $v$.

### Exercises

> [!EXERCISE]
> Show that the gradient of [(2.1)](https://blog.kiarashs.ir/blog/a-complete-example/#eq-loss) is $X^\top (p - y) / n$.

> [!SOLUTION] to [Exercise 2.3](https://blog.kiarashs.ir/blog/a-complete-example/#ex-gradient)
> Write $\ell_i = -y_i \log p_i - (1 - y_i) \log (1 - p_i)$. Since
> $\sigma'(z) = \sigma(z)\big(1 - \sigma(z)\big)$, the chain rule gives
> $\partial \ell_i / \partial w = (p_i - y_i)\, x_i$. Averaging over $i$ gives
> $X^\top (p - y) / n$.

## Method

### The algorithm

![A step from w down the slope of a bowl towards its minimum](https://blog.kiarashs.ir/posts/complete-example/step.svg)

Caption: One step: down the slope, by $\eta$ times it.

[Algorithm 3.1](https://blog.kiarashs.ir/blog/a-complete-example/#alg-gd) is [Theorem 2.2](https://blog.kiarashs.ir/blog/a-complete-example/#thm-convex) put to work, one step at a time as in
[Figure 3.1](https://blog.kiarashs.ir/blog/a-complete-example/#fig-step). It uses all the data for every step; drawing a few rows at a
time instead is SGD, which scales to data that does not fit in memory. SGD is
left out here for clarity.

```algorithm
\begin{algorithm}
\caption{Gradient descent for logistic regression}
\label{gd}
\begin{algorithmic}
\REQUIRE data $X, y$, step size $\eta$, number of steps $T$
\STATE $w \gets 0$
\FOR{$t = 1$ \TO $T$}
  \STATE $p \gets \sigma(X w)$
  \STATE $w \gets w - \eta\, X^\top (p - y) / n$
\ENDFOR
\RETURN $w$
\end{algorithmic}
\end{algorithm}
```

### The code

[Listing 3.1](https://blog.kiarashs.ir/blog/a-complete-example/#lst-fit) is read from the file the post links to, lines 16 to 23, so it is
the code that ran. Lines 19 to 21 are the loop.

```python
def fit(self, X, y):
    n, d = X.shape
    self.w = np.zeros(d)
    for _ in range(self.steps):
        p = sigmoid(X @ self.w)
        gradient = X.T @ (p - y) / n
        self.w -= self.step * gradient
    return self
```

Caption: The `fit` method of `fit.py`.

A file can also be read from elsewhere. [Listing 3.2](https://blog.kiarashs.ir/blog/a-complete-example/#lst-predict) is the same file in
this site's repository on GitHub, at the commit that added it, so it cannot
change under the post; the build keeps a copy in
`src/content/remote-code.lock.json` and needs no network to show it again.

```python
def predict(self, X):
    return (sigmoid(X @ self.w) >= 0.5).astype(int)
```

Caption: The `predict` method, read from GitHub at a fixed commit.

Callouts explain a listing line by line:

```python
model = LogisticRegression(step=0.5)  # <1>
model.fit(X_train, y_train)  # <2>
accuracy = (model.predict(X_test) == y_test).mean()  # <3>
```

1. A larger step than the default, which [Figure 4.1](https://blog.kiarashs.ir/blog/a-complete-example/#fig-lr) shows is still safe.
2. Five hundred steps of [Algorithm 3.1](https://blog.kiarashs.ir/blog/a-complete-example/#alg-gd).
3. The share of test points classified correctly; see [Table 4.1](https://blog.kiarashs.ir/blog/a-complete-example/#tbl-accuracy).

The same model in two languages:

```python tab="Python"
model = LogisticRegression().fit(X, y)
```

```r tab="R"
model <- glm(y ~ ., data = d, family = binomial)
```

And what changed when the loop learnt to stop early:

```diff-python
     for _ in range(self.steps):
         p = sigmoid(X @ self.w)
         gradient = X.T @ (p - y) / n
+        if np.linalg.norm(gradient) < 1e-6:
+            break
         self.w -= self.step * gradient
```

## Results

### Step sizes

![Loss falling slowly](https://blog.kiarashs.ir/posts/complete-example/lr-small.svg "Too small")
![Loss falling quickly to a floor](https://blog.kiarashs.ir/posts/complete-example/lr-good.svg "About right")
![Loss oscillating and climbing](https://blog.kiarashs.ir/posts/complete-example/lr-large.svg "Too large")

Caption: Training loss for three step sizes.

The step in [Figure 4.1b](https://blog.kiarashs.ir/blog/a-complete-example/#fig-lr-b) is the one used for the rest of the post;
[Figure 4.1c](https://blog.kiarashs.ir/blog/a-complete-example/#fig-lr-c) diverges. The row is set wider than the text, `#wide` on its
first picture, so the three plots are not squeezed into the column.

### Before and after

Two images flagged `#compare` are laid one over the other with a divider to
drag, or to move with the arrow keys once it has focus. Printed, or with no
script, they are two pictures side by side.

![A noisy photograph of hills at sunset](https://blog.kiarashs.ir/posts/complete-example/scan-noisy.jpg "Noisy")
![The same photograph without the noise](https://blog.kiarashs.ir/posts/complete-example/scan-clean.jpg "Denoised")

Caption: A photograph before and after denoising.

### Accuracy

[Table 4.1](https://blog.kiarashs.ir/blog/a-complete-example/#tbl-accuracy) is read from `accuracy.csv` beside the post, so it shows the
numbers the results came out in; the numeric columns line up on the right.
Accuracy depends on where the threshold is set; AUC, which does not, would be
the other number to report.

```csv
Model,Test accuracy,Training time (s),Note
Logistic regression,0.86,1.2,"linear, fast"
Decision tree,0.81,0.4,depth 6
Random forest,0.89,7.9,"200 trees, depth 8"
```

Caption: Test accuracy of three models.

```vega-lite
{
  "description": "Test accuracy of three models, as bars",
  "data": {
    "values": [
      { "model": "Logistic regression", "accuracy": 0.86 },
      { "model": "Decision tree", "accuracy": 0.81 },
      { "model": "Random forest", "accuracy": 0.89 }
    ]
  },
  "mark": "bar",
  "encoding": {
    "x": { "field": "model", "type": "nominal", "title": "Model", "sort": null },
    "y": {
      "field": "accuracy",
      "type": "quantitative",
      "title": "Test accuracy",
      "scale": { "domain": [0, 1] }
    }
  }
}
```

Caption: [Table 4.1](https://blog.kiarashs.ir/blog/a-complete-example/#tbl-accuracy) as a chart.

### The pipeline

```mermaid
flowchart LR
  data[Data] --> model[Model] --> loss[Loss]
  loss --> optimiser[Optimiser] --> model
```

Caption: One step of training.

```tikz
% alt: The sigmoid curve rising from 0 to 1, crossing one half at zero
\begin{tikzpicture}[>=Stealth, xscale=0.55, yscale=2]
  \draw[->] (-5.5,0) -- (5.8,0) node[right] {$z$};
  \draw[->] (0,-0.05) -- (0,1.2) node[above] {$\sigma(z)$};
  \draw[dashed] (0,1) -- (5.5,1);
  \draw[thick, domain=-5.5:5.5, smooth, samples=80] plot (\x, {1/(1+exp(-\x))});
  \node[left] at (0,1) {$1$};
  \node[above left] at (0,0.5) {$1/2$};
\end{tikzpicture}
```

Caption: The sigmoid, $\sigma(z) = 1 / (1 + e^{-z})$.

### The boundary

A black-on-white sketch with no dark version of its own is inverted on the
dark theme when its path ends in `#invert`; switch the theme to see it.

![Two classes of points either side of a dashed decision boundary](https://blog.kiarashs.ir/posts/complete-example/boundary.svg)

Caption: The boundary the model learns, sketched.

### Chemistry

The renderer has chemistry too: $\ce{2 H2 + O2 -> 2 H2O}$, with
$\Delta H = \pu{-572 kJ/mol}$.

## Media

### A recording

![A three-note chime](https://blog.kiarashs.ir/posts/complete-example/chime.wav)

Caption: A sound, written as an image is, played by the browser's own player.

### A place

![Azadi Tower, Tehran](geo:35.6997,51.3380?z=15)

Caption: A map, loaded from OpenStreetMap only when asked for.

## Notes

> [!TIP]- How the references are written
> Every reference in this post is a link with no text: `[](#fig-lr-b)`,
> `[](#eq-loss)`, `[](/blog/writing-like-a-paper)`. The build fills in the
> words, and warns about any that point at nothing.

<details>
<summary>What the frontmatter of this post says</summary>

```yaml
numbered: true
numberWithin: section
macros:
  # Quoted: in YAML a space before # starts a comment.
  \KL: 'D_{\mathrm{KL}}\left(#1 \,\Vert\, #2\right)'
  \loss: \mathcal{L}
```

</details>

## Abbreviations

- **SGD**: stochastic gradient descent
- **AUC**: area under the ROC curve
