A complete example

·4 min read

Contents18 sections

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.

1 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 covers the basics, and Math and citations the maths. One to a section here writes its number: the method is in Section 3, the results in Section 4. A citation works as before (Knuth, 1984), and so does a footnote, which on a wide screen stands in the margin.11 Numbered sections are asked for with numbered: true in the frontmatter; most posts do not need them.

2 Theory

The symbols used throughout:

XX
The n×dn \times d matrix of inputs, one example to a row.
yy
The labels, each 00 or 11.
ww
The weights, the model's only parameters.
σ\sigma
The logistic function, which maps a score to a probability.

2.1 The loss

Definition 2.1 (Cross-entropy). For labels yi∈{0,1}y_i \in \{0, 1\} and predictions pi=σ(xi⊤w)p_i = \sigma(x_i^\top w), the loss of weights w∈Rdw \in \R^d is

L(w)=−1n∑i=1n[yilog⁡pi+(1−yi)log⁡(1−pi)].(2.1)\loss(w) = -\frac{1}{n} \sum_{i=1}^{n} \Big[ y_i \log p_i + (1 - y_i) \log (1 - p_i) \Big]. \tag{2.1}

\loss and \KL are this post's own macros, defined in its frontmatter; \R and \E come with the site. Minimising (2.1) is the same as minimising Ex[DKL(ptrue ∥ pw)]\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:

∇L(w)=X⊤(p−y)/n∇2L(w)=X⊤SX/n \begin{align} \nabla \loss(w) &= X^\top (p - y) / n \tag{2.2a} \\ \nabla^2 \loss(w) &= X^\top S X / n \tag{2.2b} \end{align}

Theorem 2.2 (Convexity). L\loss is convex in ww, so gradient descent with a small enough step reaches its minimum w^=arg min⁡wL(w)\hat w = \argmin_w \loss(w).

Proof of Theorem 2.2. The Hessian is (2.2b), with S=diag⁡(pi(1−pi))S = \operatorname{diag}\big(p_i (1 - p_i)\big), and v⊤X⊤SXv=∥S1/2Xv∥2≥0v^\top X^\top S X v = \lVert S^{1/2} X v \rVert^2 \ge 0 for every vv. ∎

2.2 Exercises

Exercise 2.3. Show that the gradient of (2.1) is X⊤(p−y)/nX^\top (p - y) / n.

Solution to Exercise 2.3.

Write ℓi=−yilog⁡pi−(1−yi)log⁡(1−pi)\ell_i = -y_i \log p_i - (1 - y_i) \log (1 - p_i). Since σ′(z)=σ(z)(1−σ(z))\sigma'(z) = \sigma(z)\big(1 - \sigma(z)\big), the chain rule gives ∂ℓi/∂w=(pi−yi) xi\partial \ell_i / \partial w = (p_i - y_i)\, x_i. Averaging over ii gives X⊤(p−y)/nX^\top (p - y) / n.

3 Method

3.1 The algorithm

A step from w down the slope of a bowl towards its minimum
Figure 3.1. One step: down the slope, by η\eta times it.

Algorithm 3.1 is Theorem 2.2 put to work, one step at a time as in Figure 3.1. It uses all the data for every step; drawing a few rows at a time instead is stochastic gradient descent (SGD), which scales to data that does not fit in memory. SGD is left out here for clarity.

Algorithm 3.1 Gradient descent for logistic regression

Require: data X,yX, y, step size η\eta, number of steps TT

1w←0w \gets 0

2for t=1t = 1 to TT do

3p←σ(Xw)p \gets \sigma(X w)

4w←w−η X⊤(p−y)/nw \gets w - \eta\, X^\top (p - y) / n

5end for

6return ww

3.2 The code

Listing 3.1 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.

Listing 3.1. The fit method of fit.py.
fit.py, from line 16
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

A file can also be read from elsewhere. Listing 3.2 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.

Listing 3.2. The predict method, read from GitHub at a fixed commit.
fit.py, from line 25
def predict(self, X):
    return (sigmoid(X @ self.w) >= 0.5).astype(int)

Callouts explain a listing line by line:

model = LogisticRegression(step=0.5)
model.fit(X_train, y_train)
accuracy = (model.predict(X_test) == y_test).mean()
  1. A larger step than the default, which Figure 4.1 shows is still safe.
  2. Five hundred steps of Algorithm 3.1.
  3. The share of test points classified correctly; see Table 4.1.

The same model in two languages:

model = LogisticRegression().fit(X, y)
model <- glm(y ~ ., data = d, family = binomial)

And what changed when the loop learnt to stop early:

    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

4 Results

4.1 Step sizes

Loss falling slowly
(a) Too small
Loss falling quickly to a floor
(b) About right
Loss oscillating and climbing
(c) Too large
Figure 4.1. Training loss for three step sizes.

The step in Figure 4.1b is the one used for the rest of the post; Figure 4.1c diverges. The row is set wider than the text, #wide on its first picture, so the three plots are not squeezed into the column.

4.2 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
(a) Noisy
The same photograph without the noise
(b) Denoised
Figure 4.2. A photograph before and after denoising.

4.3 Accuracy

Table 4.1 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; area under the ROC curve (AUC), which does not, would be the other number to report.

Table 4.1. Test accuracy of three models.
ModelTest accuracyTraining time (s)Note
Logistic regression0.861.2linear, fast
Decision tree0.810.4depth 6
Random forest0.897.9200 trees, depth 8
Logistic regressionDecision treeRandom forestModel0.00.20.40.60.81.0Test accuracy
Logistic regressionDecision treeRandom forestModel0.00.20.40.60.81.0Test accuracy
Logistic regressionDecision treeRandom forestModel0.00.20.40.60.81.0Test accuracy
Logistic regressionDecision treeRandom forestModel0.00.20.40.60.81.0Test accuracy
Logistic regressionDecision treeRandom forestModel0.00.20.40.60.81.0Test accuracy
Logistic regressionDecision treeRandom forestModel0.00.20.40.60.81.0Test accuracy
Data (3 rows)
modelaccuracy
Logistic regression0.86
Decision tree0.81
Random forest0.89
Figure 4.3. Table 4.1 as a chart.

4.4 The pipeline

Data

Model

Loss

Optimiser

Data

Model

Loss

Optimiser

Figure 4.4. One step of training.
Figure 4.5. The sigmoid, σ(z)=1/(1+e−z)\sigma(z) = 1 / (1 + e^{-z}).

4.5 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
Figure 4.6. The boundary the model learns, sketched.

4.6 Chemistry

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

5 Media

5.1 A recording

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

5.2 A place

Figure 5.2. A map, loaded from OpenStreetMap only when asked for.

6 Notes

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.

What the frontmatter of this post says
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}

Footnotes

  1. Numbered sections are asked for with numbered: true in the frontmatter; most posts do not need them. ↩

Knuth, D. E. (1984). Literate Programming. The Computer Journal, 27(2), 97–111. https://doi.org/10.1093/comjnl/27.2.97
Cite this post
BibTeX
@misc{soleimanzadeh2026complete,
  author  = {Soleimanzadeh, Kiarash},
  title   = {A complete example},
  year    = {2026},
  url     = {https://blog.kiarashs.ir/blog/a-complete-example},
  urldate = {2026-10-29}
}
APA
Soleimanzadeh, K. (2026, October 29). A complete example. Kiarash Soleimanzadeh. https://blog.kiarashs.ir/blog/a-complete-example
IEEE
K. Soleimanzadeh, "A complete example," Kiarash Soleimanzadeh, Oct. 29, 2026. [Online]. Available: https://blog.kiarashs.ir/blog/a-complete-example
Plain text
Kiarash Soleimanzadeh. “A complete example.” Kiarash Soleimanzadeh, 29 October 2026. https://blog.kiarashs.ir/blog/a-complete-example

Kiarash Soleimanzadeh

Comments