Complete Assigned Readings

Open a section to study the full text and its source attribution. Course links open the assigned section directly.

1 . 1 The Need for Efficiency

Assigned source reading · Pat Morin

Pat Morin — Open Data Structures, pseudocode edition 0.1G

Original source · Creative Commons Attribution 2.5 Canada · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.

1.1 The Need for Efficiency

In the next section, we look at the operations supported by the most commonly used data structures. Anyone with a bit of programming experience will see that these operations are not hard to implement correctly. We can store the data in an array or a linked list and each operation can be implemented by iterating over all the elements of the array or list and possibly adding or removing an element.

This kind of implementation is easy, but not very efficient. Does this really matter? Computers are becoming faster and faster. Maybe the obvious implementation is good enough. Let's do some rough calculations to find out.

1.1.0.0.1 Number of operations:

Imagine an application with a moderately-sized data set, say of one million ($ 10^6$), items. It is reasonable, in most applications, to assume that the application will want to look up each item at least once. This means we can expect to do at least one million ($ 10^6$) searches in this data. If each of these $ 10^6$ searches inspects each of the $ 10^6$ items, this gives a total of $ 10^6\times 10^6=10^{12}$ (one thousand billion) inspections.

1.1.0.0.2 Processor speeds:

At the time of writing, even a very fast desktop computer can not do more than one billion ($ 10^9$) operations per second.1.1This means that this application will take at least $ 10^{12}/10^9 = 1000$ seconds, or roughly 16 minutes and 40 seconds. Sixteen minutes is an eon in computer time, but a person might be willing to put up with it (if he or she were headed out for a coffee break).

1.1.0.0.3 Bigger data sets:

Now consider a company like Google, that indexes over 8.5 billion web pages. By our calculations, doing any kind of query over this data would take at least 8.5 seconds. We already know that this isn't the case; web searches complete in much less than 8.5 seconds, and they do much more complicated queries than just asking if a particular page is in their list of indexed pages. At the time of writing, Google receives approximately $ 4,500$ queries per second, meaning that they would require at least $ 4,500\times 8.5=38,250$ very fast servers just to keep up.

1.1.0.0.4 The solution:

These examples tell us that the obvious implementations of data structures do not scale well when the number of items, $ \ensuremath{\ensuremath{\mathit{n}}}$, in the data structure and the number of operations, $ m$, performed on the data structure are both large. In these cases, the time (measured in, say, machine instructions) is roughly $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}\times m$.

The solution, of course, is to carefully organize data within the data structure so that not every operation requires every data item to be inspected. Although it sounds impossible at first, we will see data structures where a search requires looking at only two items on average, independent of the number of items stored in the data structure. In our billion instruction per second computer it takes only $ 0.000000002$ seconds to search in a data structure containing a billion items (or a trillion, or a quadrillion, or even a quintillion items).

We will also see implementations of data structures that keep the items in sorted order, where the number of items inspected during an operation grows very slowly as a function of the number of items in the data structure. For example, we can maintain a sorted set of one billion items while inspecting at most 60 items during any operation. In our billion instruction per second computer, these operations take $ 0.00000006$ seconds each.

The remainder of this chapter briefly reviews some of the main concepts used throughout the rest of the book. Section 1.2 describes the interfaces implemented by all of the data structures described in this book and should be considered required reading. The remaining sections discuss:

A reader with or without a background in these areas can easily skip them now and come back to them later if necessary.



Footnotes

... second.1.1
Computer speeds are at most a few gigahertz (billions of cycles per second), and each operation typically takes a few cycles.
opendatastructures.org

2 . 1 ArrayStack: Fast Stack Operations Using an Array

Assigned source reading · Pat Morin

Pat Morin — Open Data Structures, pseudocode edition 0.1G

Original source · Creative Commons Attribution 2.5 Canada · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.

Subsections


2.1 ArrayStack: Fast Stack Operations Using an Array

An ArrayStack implements the list interface using an array $ \ensuremath{\ensuremath{\mathit{a}}}$, called the backing array. The list element with index $ \ensuremath{\ensuremath{\mathit{i}}}$ is stored in $ \ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{i}}]}$. At most times, $ \ensuremath{\ensuremath{\mathit{a}}}$ is larger than strictly necessary, so an integer $ \ensuremath{\ensuremath{\mathit{n}}}$ is used to keep track of the number of elements actually stored in $ \ensuremath{\ensuremath{\mathit{a}}}$. In this way, the list elements are stored in $ \ensuremath{\ensuremath{\mathit{a}}[0]}$,..., $ \ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{n}}-1]}$ and, at all times, $ \ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{a}})}} \ge \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$.


\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{initialize}(...
...th{\ensuremath{\mathit{n}} \gets \ensuremath{0}}\\
\end{flushleft}\end{leftbar}

2.1.1 The Basics

Accessing and modifying the elements of an ArrayStack using $ \ensuremath{\mathrm{get}(\ensuremath{\mathit{i}})}$ and $ \ensuremath{\mathrm{set}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ is trivial. After performing any necessary bounds-checking we simply return or set, respectively, $ \ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{i}}]}$.


\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{get}(\ensure...
...bf{return}} \ensuremath{\ensuremath{\mathit{y}}}\\
\end{flushleft}\end{leftbar}

The operations of adding and removing elements from an ArrayStack are illustrated in Figure 2.1. To implement the $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ operation, we first check if $ \ensuremath{\ensuremath{\mathit{a}}}$ is already full. If so, we call the method $ \ensuremath{\mathrm{resize}()}$ to increase the size of $ \ensuremath{\ensuremath{\mathit{a}}}$. How $ \ensuremath{\mathrm{resize}()}$ is implemented will be discussed later. For now, it is sufficient to know that, after a call to $ \ensuremath{\mathrm{resize}()}$, we can be sure that $ \ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{a}})}}
> \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$. With this out of the way, we now shift the elements $ \ensuremath{\ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{i}}]}},\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{n}}-1]}}$ right by one position to make room for $ \ensuremath{\ensuremath{\mathit{x}}}$, set $ \ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{i}}]}$ equal to $ \ensuremath{\ensuremath{\mathit{x}}}$, and increment $ \ensuremath{\ensuremath{\mathit{n}}}$.

Figure 2.1: A sequence of $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$ operations on an ArrayStack. Arrows denote elements being copied. Operations that result in a call to $ \ensuremath{\mathrm{resize}()}$ are marked with an asterisk.
\includegraphics[scale=0.90909]{figs-python/arraystack}


\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{add}(\ensure...
... \gets \ensuremath{\ensuremath{\mathit{n}} + 1}}\\
\end{flushleft}\end{leftbar}
If we ignore the cost of the potential call to $ \ensuremath{\mathrm{resize}()}$, then the cost of the $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ operation is proportional to the number of elements we have to shift to make room for $ \ensuremath{\ensuremath{\mathit{x}}}$. Therefore the cost of this operation (ignoring the cost of resizing $ \ensuremath{\ensuremath{\mathit{a}}}$) is $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}})$.

Implementing the $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$ operation is similar. We shift the elements $ \ensuremath{\ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{i}}+1]}},\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{n}}-1]}}$ left by one position (overwriting $ \ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{i}}]}$) and decrease the value of $ \ensuremath{\ensuremath{\mathit{n}}}$. After doing this, we check if $ \ensuremath{\ensuremath{\mathit{n}}}$ is getting much smaller than $ \ensuremath{\mathrm{length}(\ensuremath{\mathit{a}})}$ by checking if $ \ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{a}})}} \ge 3\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$. If so, then we call $ \ensuremath{\mathrm{resize}()}$ to reduce the size of $ \ensuremath{\ensuremath{\mathit{a}}}$.


\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{remove}(\ens...
...bf{return}} \ensuremath{\ensuremath{\mathit{x}}}\\
\end{flushleft}\end{leftbar}
If we ignore the cost of the $ \ensuremath{\mathrm{resize}()}$ method, the cost of a $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$ operation is proportional to the number of elements we shift, which is $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}})$.

2.1.2 Growing and Shrinking

The $ \ensuremath{\mathrm{resize}()}$ method is fairly straightforward; it allocates a new array $ \ensuremath{\ensuremath{\mathit{b}}}$ whose size is $ 2\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$ and copies the $ \ensuremath{\ensuremath{\mathit{n}}}$ elements of $ \ensuremath{\ensuremath{\mathit{a}}}$ into the first $ \ensuremath{\ensuremath{\mathit{n}}}$ positions in $ \ensuremath{\ensuremath{\mathit{b}}}$, and then sets $ \ensuremath{\ensuremath{\mathit{a}}}$ to $ \ensuremath{\ensuremath{\mathit{b}}}$. Thus, after a call to $ \ensuremath{\mathrm{resize}()}$, $ \ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{a}})}} = 2\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$.


\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{resize}()}\\...
...th{\ensuremath{\mathit{a}} \gets \ensuremath{b}}\\
\end{flushleft}\end{leftbar}

Analyzing the actual cost of the $ \ensuremath{\mathrm{resize}()}$ operation is easy. It allocates an array $ \ensuremath{\ensuremath{\mathit{b}}}$ of size $ 2\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$ and copies the $ \ensuremath{\ensuremath{\mathit{n}}}$ elements of $ \ensuremath{\ensuremath{\mathit{a}}}$ into $ \ensuremath{\ensuremath{\mathit{b}}}$. This takes $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ time.

The running time analysis from the previous section ignored the cost of calls to $ \ensuremath{\mathrm{resize}()}$. In this section we analyze this cost using a technique known as amortized analysis. This technique does not try to determine the cost of resizing during each individual $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$ operation. Instead, it considers the cost of all calls to $ \ensuremath{\mathrm{resize}()}$ during a sequence of $ m$ calls to $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ or $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$. In particular, we will show:

Lemma 2..1   If an empty ArrayStack is created and any sequence of $ m\ge 1$ calls to $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$ are performed, then the total time spent during all calls to $ \ensuremath{\mathrm{resize}()}$ is $ O(m)$.

Proof. We will show that any time $ \ensuremath{\mathrm{resize}()}$ is called, the number of calls to $ \ensuremath{\ensuremath{\mathit{add}}}$ or $ \ensuremath{\ensuremath{\mathit{remove}}}$ since the last call to $ \ensuremath{\mathrm{resize}()}$ is at least $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}/2-1$. Therefore, if $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_i$ denotes the value of $ \ensuremath{\ensuremath{\mathit{n}}}$ during the $ i$th call to $ \ensuremath{\mathrm{resize}()}$ and $ r$ denotes the number of calls to $ \ensuremath{\mathrm{resize}()}$, then the total number of calls to $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ or $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$ is at least

$\displaystyle \sum_{i=1}^{r} (\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_i/2-1) \le m \enspace ,
$

which is equivalent to

$\displaystyle \sum_{i=1}^{r} \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_i \le 2m + 2r \enspace .
$

On the other hand, the total time spent during all calls to $ \ensuremath{\mathrm{resize}()}$ is

$\displaystyle \sum_{i=1}^{r} O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_i) \le O(m+r) = O(m) \enspace ,
$

since $ r$ is not more than $ m$. All that remains is to show that the number of calls to $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ or $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$ between the $ (i-1)$th and the $ i$th call to $ \ensuremath{\mathrm{resize}()}$ is at least $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_i/2$.

There are two cases to consider. In the first case, $ \ensuremath{\mathrm{resize}()}$ is being called by $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ because the backing array $ \ensuremath{\ensuremath{\mathit{a}}}$ is full, i.e., $ \ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{a}})}} = \ensurema...
...h{\ensuremath{\mathit{n}}}}=\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_i$. Consider the previous call to $ \ensuremath{\mathrm{resize}()}$: after this previous call, the size of $ \ensuremath{\ensuremath{\mathit{a}}}$ was $ \ensuremath{\mathrm{length}(\ensuremath{\mathit{a}})}$, but the number of elements stored in $ \ensuremath{\ensuremath{\mathit{a}}}$ was at most $ \ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{a}})}}/2=\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_i/2$. But now the number of elements stored in $ \ensuremath{\ensuremath{\mathit{a}}}$ is $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_i=\ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{a}})}}$, so there must have been at least $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_i/2$ calls to $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ since the previous call to $ \ensuremath{\mathrm{resize}()}$.

The second case occurs when $ \ensuremath{\mathrm{resize}()}$ is being called by $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$ because $ \ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{a}})}} \ge 3\ensur...
...{\ensuremath{\mathit{n}}}}=3\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_i$. Again, after the previous call to $ \ensuremath{\mathrm{resize}()}$ the number of elements stored in $ \ensuremath{\ensuremath{\mathit{a}}}$ was at least $ \ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{a}})/2}}-1$.2.1 Now there are $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_i\le\ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{a}})}}/3$ elements stored in $ \ensuremath{\ensuremath{\mathit{a}}}$. Therefore, the number of $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$ operations since the last call to $ \ensuremath{\mathrm{resize}()}$ is at least

$\displaystyle R$ $\displaystyle \ge \ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{a}})}}/2 - 1 - \ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{a}})}}/3$    
  $\displaystyle = \ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{a}})}}/6 - 1$    
  $\displaystyle = (\ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{a}})}}/3)/2 - 1$    
  $\displaystyle \ge \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_i/2 -1\enspace .$    

In either case, the number of calls to $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ or $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$ that occur between the $ (i-1)$th call to $ \ensuremath{\mathrm{resize}()}$ and the $ i$th call to $ \ensuremath{\mathrm{resize}()}$ is at least $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_i/2-1$, as required to complete the proof. $ \qedsymbol$

2.1.3 Summary

The following theorem summarizes the performance of an ArrayStack:

Theorem 2..1   An ArrayStack implements the List interface. Ignoring the cost of calls to $ \ensuremath{\mathrm{resize}()}$, an ArrayStack supports the operations
  • $ \ensuremath{\mathrm{get}(\ensuremath{\mathit{i}})}$ and $ \ensuremath{\mathrm{set}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ in $ O(1)$ time per operation; and
  • $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$ in $ O(1+\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}})$ time per operation.
Furthermore, beginning with an empty ArrayStack and performing any sequence of $ m$ $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$ operations results in a total of $ O(m)$ time spent during all calls to $ \ensuremath{\mathrm{resize}()}$.

The ArrayStack is an efficient way to implement a Stack. In particular, we can implement $ \ensuremath{\mathrm{push}(\ensuremath{\mathit{x}})}$ as $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{n}},\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{pop}()}$ as $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{n}}-1)}$, in which case these operations will run in $ O(1)$ amortized time.



Footnotes

....2.1
The $ {}-1$ in this formula accounts for the special case that occurs when $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}=0$ and $ \ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{a}})}} = 1$.
opendatastructures.org

5 . 3 Hash Codes

Assigned source reading · Pat Morin

Pat Morin — Open Data Structures, pseudocode edition 0.1G

Original source · Creative Commons Attribution 2.5 Canada · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.

Subsections

5.3 Hash Codes

The hash tables discussed in the previous section are used to associate data with integer keys consisting of $ \ensuremath{\ensuremath{\mathit{w}}}$ bits. In many cases, we have keys that are not integers. They may be strings, objects, arrays, or other compound structures. To use hash tables for these types of data, we must map these data types to $ \ensuremath{\ensuremath{\mathit{w}}}$-bit hash codes. Hash code mappings should have the following properties:

  1. If $ \ensuremath{\ensuremath{\mathit{x}}}$ and $ \ensuremath{\ensuremath{\mathit{y}}}$ are equal, then $ \ensuremath{\ensuremath{\mathit{x}}.\mathrm{hash\_code}()}$ and $ \ensuremath{\ensuremath{\mathit{y}}.\mathrm{hash\_code}()}$ are equal.

  2. If $ \ensuremath{\ensuremath{\mathit{x}}}$ and $ \ensuremath{\ensuremath{\mathit{y}}}$ are not equal, then the probability that $ \ensuremath{\ensuremath{\ensuremath{\mathit{x}}.\mathrm{hash\_code}()}}=\ensuremath{\ensuremath{\ensuremath{\mathit{y}}.\mathrm{hash\_code}()}}$ should be small (close to $ 1/2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}$).

The first property ensures that if we store $ \ensuremath{\ensuremath{\mathit{x}}}$ in a hash table and later look up a value $ \ensuremath{\ensuremath{\mathit{y}}}$ equal to $ \ensuremath{\ensuremath{\mathit{x}}}$, then we will find $ \ensuremath{\ensuremath{\mathit{x}}}$--as we should. The second property minimizes the loss from converting our objects to integers. It ensures that unequal objects usually have different hash codes and so are likely to be stored at different locations in our hash table.

5.3.1 Hash Codes for Primitive Data Types

Small primitive data types like $ \ensuremath{\ensuremath{\mathit{char}}}$, $ \ensuremath{\ensuremath{\mathit{byte}}}$, $ \ensuremath{\ensuremath{\mathit{int}}}$, and $ \ensuremath{\ensuremath{\mathit{float}}}$ are usually easy to find hash codes for. These data types always have a binary representation and this binary representation usually consists of $ \ensuremath{\ensuremath{\mathit{w}}}$ or fewer bits. In these cases, we just treat these bits as the representation of an integer in the range $ \{0,\ldots,2^\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}-1\}$. If two values are different, they get different hash codes. If they are the same, they get the same hash code.

A few primitive data types are made up of more than $ \ensuremath{\ensuremath{\mathit{w}}}$ bits, usually $ c\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}$ bits for some constant integer $ c$. (Java's $ \ensuremath{\ensuremath{\mathit{long}}}$ and $ \ensuremath{\ensuremath{\mathit{double}}}$ types are examples of this with $ c=2$.) These data types can be treated as compound objects made of $ c$ parts, as described in the next section.


5.3.2 Hash Codes for Compound Objects

For a compound object, we want to create a hash code by combining the individual hash codes of the object's constituent parts. This is not as easy as it sounds. Although one can find many hacks for this (for example, combining the hash codes with bitwise exclusive-or operations), many of these hacks turn out to be easy to foil (see Exercises 5.7-5.9). However, if one is willing to do arithmetic with $ 2\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}$ bits of precision, then there are simple and robust methods available. Suppose we have an object made up of several parts $ P_0,\ldots,P_{r-1}$ whose hash codes are $ \ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_0,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_{r-1}$. Then we can choose mutually independent random $ \ensuremath{\ensuremath{\mathit{w}}}$-bit integers $ \ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}_0,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}_{r-1}$ and a random $ 2\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}$-bit odd integer $ \ensuremath{\ensuremath{\mathit{z}}}$ and compute a hash code for our object with

$\displaystyle h(\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_0,\ldots,\ens...
...right)
\ddiv 2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}} \enspace .
$

Note that this hash code has a final step (multiplying by $ \ensuremath{\ensuremath{\mathit{z}}}$ and dividing by $ 2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}$) that uses the multiplicative hash function from Section 5.1.1 to take the $ 2\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}$-bit intermediate result and reduce it to a $ \ensuremath{\ensuremath{\mathit{w}}}$-bit final result. Here is an example of this method applied to a simple compound object with three parts $ \ensuremath{\ensuremath{\mathit{x_0}}}$, $ \ensuremath{\ensuremath{\mathit{x_1}}}$, and $ \ensuremath{\ensuremath{\mathit{x_2}}}$:
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{hash\_code}(...
...{\mathit{w}})}) \ensuremath{\gg} \ensuremath{w}}\\
\end{flushleft}\end{leftbar}
The following theorem shows that, in addition to being straightforward to implement, this method is provably good:

Theorem 5..3   Let $ \ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_0,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_{r-1}$ and $ \ensuremath{\ensuremath{\ensuremath{\mathit{y}}}}_0,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{y}}}}_{r-1}$ each be sequences of $ \ensuremath{\ensuremath{\mathit{w}}}$ bit integers in $ \{0,\ldots,2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}-1\}$ and assume $ \ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_i \neq \ensuremath{\ensuremath{\ensuremath{\mathit{y}}}}_i$ for at least one index $ i\in\{0,\ldots,r-1\}$. Then

$\displaystyle \Pr\{ h(\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_0,\ldot...
...) \}
\le 3/2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}} \enspace .
$

Proof. We will first ignore the final multiplicative hashing step and see how that step contributes later. Define:

$\displaystyle h'(\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_0,\ldots,\en...
...right)\bmod 2^{2\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}} \enspace .
$

Suppose that $ h'(\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_0,\ldots,\ensuremath{\ens...
...\mathit{y}}}}_0,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{y}}}}_{r-1})$. We can rewrite this as:

$\displaystyle \ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}_i(\ensuremath{\...
...athit{y}}}}_i) \bmod 2^{2\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}} = t$ (5.4)

where

$\displaystyle t = \left(\sum_{j=0}^{i-1} \ensuremath{\ensuremath{\ensuremath{\m...
...{x}}}}_j)\right) \bmod 2^{2\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}
$

If we assume, without loss of generality that $ \ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_i> \ensuremath{\ensuremath{\ensuremath{\mathit{y}}}}_i$, then (5.4) becomes

$\displaystyle \ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}_i(\ensuremath{\...
...thit{x}}}}_i-\ensuremath{\ensuremath{\ensuremath{\mathit{y}}}}_i) = t\enspace ,$ (5.5)

since each of $ \ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}_i$ and $ (\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_i-\ensuremath{\ensuremath{\ensuremath{\mathit{y}}}}_i)$ is at most $ 2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}-1$, so their product is at most $ 2^{2\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}-2^{\ensuremath{\ensurem...
...h{\mathit{w}}}}+1}+1 < 2^{2\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}-1$. By assumption, $ \ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_i-\ensuremath{\ensuremath{\ensuremath{\mathit{y}}}}_i\neq 0$, so (5.5) has at most one solution in $ \ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}_i$. Therefore, since $ \ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}_i$ and $ t$ are independent ( $ \ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}_0,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}_{r-1}$ are mutually independent), the probability that we select $ \ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}_i$ so that $ h'(\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_0,\ldots,\ensuremath{\ens...
...\mathit{y}}}}_0,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{y}}}}_{r-1})$ is at most $ 1/2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}$.

The final step of the hash function is to apply multiplicative hashing to reduce our $ 2\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}$-bit intermediate result $ h'(\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_0,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_{r-1})$ to a $ \ensuremath{\ensuremath{\mathit{w}}}$-bit final result $ h(\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_0,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_{r-1})$. By Theorem 5.3, if $ h'(\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_0,\ldots,\ensuremath{\ens...
...\mathit{y}}}}_0,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{y}}}}_{r-1})$, then $ \Pr\{h(\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_0,\ldots,\ensuremath{...
...thit{y}}}}_{r-1})\} \le 2/2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}$.

To summarize,

  $\displaystyle \Pr\left\{\begin{array}{l} h(\ensuremath{\ensuremath{\ensuremath{...
...ots,\ensuremath{\ensuremath{\ensuremath{\mathit{y}}}}_{r-1})\end{array}\right\}$    
  $\displaystyle = \Pr\left\{\begin{array}{ll} \mbox{$h'(\ensuremath{\ensuremath{\...
...div 2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}$} \end{array}\right\}$    
  $\displaystyle \le 1/2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}} + 2/2...
...} = 3/2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}} \enspace . \qedhere$    

$ \qedsymbol$


5.3.3 Hash Codes for Arrays and Strings

The method from the previous section works well for objects that have a fixed, constant, number of components. However, it breaks down when we want to use it with objects that have a variable number of components, since it requires a random $ \ensuremath{\ensuremath{\mathit{w}}}$-bit integer $ \ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}_i$ for each component. We could use a pseudorandom sequence to generate as many $ \ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}_i$'s as we need, but then the $ \ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}_i$'s are not mutually independent, and it becomes difficult to prove that the pseudorandom numbers don't interact badly with the hash function we are using. In particular, the values of $ t$ and $ \ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}_i$ in the proof of Theorem 5.3 are no longer independent.

A more rigorous approach is to base our hash codes on polynomials over prime fields; these are just regular polynomials that are evaluated modulo some prime number, $ \ensuremath{\ensuremath{\mathit{p}}}$. This method is based on the following theorem, which says that polynomials over prime fields behave pretty-much like usual polynomials:

Theorem 5..4   Let $ \ensuremath{\ensuremath{\ensuremath{\mathit{p}}}}$ be a prime number, and let $ f(\ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}) = \ensuremath{\ensuremath...
...math{\mathit{x}}}}_{r-1}\ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}^{r-1}$ be a non-trivial polynomial with coefficients $ \ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_i\in\{0,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{p}}}}-1\}$. Then the equation $ f(\ensuremath{\ensuremath{\ensuremath{\mathit{z}}}})\bmod \ensuremath{\ensuremath{\ensuremath{\mathit{p}}}} = 0$ has at most $ r-1$ solutions for $ \ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}\in\{0,\ldots,p-1\}$.

To use Theorem 5.4, we hash a sequence of integers $ \ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_0,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_{r-1}$ with each $ \ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_i\in \{0,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{p}}}}-2\}$ using a random integer $ \ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}\in\{0,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{p}}}}-1\}$ via the formula

$\displaystyle h(\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_0,\ldots,\ens...
...}}^r \right)\bmod \ensuremath{\ensuremath{\ensuremath{\mathit{p}}}} \enspace .
$

Note the extra $ (\ensuremath{\ensuremath{\ensuremath{\mathit{p}}}}-1)\ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}^r$ term at the end of the formula. It helps to think of $ (\ensuremath{\ensuremath{\ensuremath{\mathit{p}}}}-1)$ as the last element, $ \ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_r$, in the sequence $ \ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_0,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_{r}$. Note that this element differs from every other element in the sequence (each of which is in the set $ \{0,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{p}}}}-2\}$). We can think of $ \ensuremath{\ensuremath{\ensuremath{\mathit{p}}}}-1$ as an end-of-sequence marker.

The following theorem, which considers the case of two sequences of the same length, shows that this hash function gives a good return for the small amount of randomization needed to choose $ \ensuremath{\ensuremath{\mathit{z}}}$:

Theorem 5..5   Let $ \ensuremath{\ensuremath{\ensuremath{\mathit{p}}}}>2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}+1$ be a prime, let $ \ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_0,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_{r-1}$ and $ \ensuremath{\ensuremath{\ensuremath{\mathit{y}}}}_0,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{y}}}}_{r-1}$ each be sequences of $ \ensuremath{\ensuremath{\mathit{w}}}$-bit integers in $ \{0,\ldots,2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}-1\}$, and assume $ \ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_i \neq \ensuremath{\ensuremath{\ensuremath{\mathit{y}}}}_i$ for at least one index $ i\in\{0,\ldots,r-1\}$. Then

$\displaystyle \Pr\{ h(\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_0,\ldot...
...
\le (r-1)/\ensuremath{\ensuremath{\ensuremath{\mathit{p}}}} \} \enspace .
$

Proof. The equation $ h(\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_0,\ldots,\ensuremath{\ensu...
...\mathit{y}}}}_0,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{y}}}}_{r-1})$ can be rewritten as

$\displaystyle \left( (\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_0-\ensu...
...z}}}}^{r-1} \right)\bmod \ensuremath{\ensuremath{\ensuremath{\mathit{p}}}} = 0.$ (5.6)

Since $ \ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_\ensuremath{\ensuremath{\ens...
...ath{\ensuremath{\mathit{y}}}}_\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}$, this polynomial is non-trivial. Therefore, by Theorem 5.4, it has at most $ r-1$ solutions in $ \ensuremath{\ensuremath{\mathit{z}}}$. The probability that we pick $ \ensuremath{\ensuremath{\mathit{z}}}$ to be one of these solutions is therefore at most $ (r-1)/\ensuremath{\ensuremath{\ensuremath{\mathit{p}}}}$. $ \qedsymbol$

Note that this hash function also deals with the case in which two sequences have different lengths, even when one of the sequences is a prefix of the other. This is because this function effectively hashes the infinite sequence

$\displaystyle \ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_0,\ldots,\ensur...
...-1}, \ensuremath{\ensuremath{\ensuremath{\mathit{p}}}}-1,0,0,\ldots \enspace .
$

This guarantees that if we have two sequences of length $ r$ and $ r'$ with $ r > r'$, then these two sequences differ at index $ i=r$. In this case, (5.6) becomes

$\displaystyle \left(
\sum_{i=0}^{i=r'-1}(\ensuremath{\ensuremath{\ensuremath{\...
... \right)\bmod \ensuremath{\ensuremath{\ensuremath{\mathit{p}}}} = 0 \enspace ,
$

which, by Theorem 5.4, has at most $ r$ solutions in $ \ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}$. This combined with Theorem 5.5 suffice to prove the following more general theorem:

Theorem 5..6   Let $ \ensuremath{\ensuremath{\ensuremath{\mathit{p}}}}>2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}+1$ be a prime, let $ \ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_0,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_{r-1}$ and $ \ensuremath{\ensuremath{\ensuremath{\mathit{y}}}}_0,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{y}}}}_{r'-1}$ be distinct sequences of $ \ensuremath{\ensuremath{\mathit{w}}}$-bit integers in $ \{0,\ldots,2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}-1\}$. Then

$\displaystyle \Pr\{ h(\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_0,\ldot...
...le \max\{r,r'\}/\ensuremath{\ensuremath{\ensuremath{\mathit{p}}}} \enspace .
$

The following example code shows how this hash function is applied to an object that contains an array, $ \ensuremath{\ensuremath{\mathit{x}}}$, of values:
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{hash\_code}(...
...\ensuremath{\ensuremath{\mathit{s}}\bmod 2^{32}}\\
\end{flushleft}\end{leftbar}

The preceding code sacrifices some collision probability for implementation convenience. In particular, it applies the multiplicative hash function from Section 5.1.1, with $ \ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}=31$ to reduce $ \ensuremath{\ensuremath{\mathit{x}}[\ensuremath{\mathit{i}}].\mathrm{hash\_code}()}$ to a 31-bit value. This is so that the additions and multiplications that are done modulo the prime $ \ensuremath{\ensuremath{\ensuremath{\mathit{p}}}}=2^{32}-5$ can be carried out using unsigned 63-bit arithmetic. Thus the probability of two different sequences, the longer of which has length $ r$, having the same hash code is at most

$\displaystyle 2/2^{31} + r/(2^{32}-5)
$

rather than the $ r/(2^{32}-5)$ specified in Theorem 5.6.

opendatastructures.org

10 . Heaps

Assigned source reading · Pat Morin

Pat Morin — Open Data Structures, pseudocode edition 0.1G

Original source · Creative Commons Attribution 2.5 Canada · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.


10. Heaps

In this chapter, we discuss two implementations of the extremely useful priority Queue data structure. Both of these structures are a special kind of binary tree called a heap, which means ``a disorganized pile.'' This is in contrast to binary search trees that can be thought of as a highly organized pile.

The first heap implementation uses an array to simulate a complete binary tree. This very fast implementation is the basis of one of the fastest known sorting algorithms, namely heapsort (see Section 11.1.3). The second implementation is based on more flexible binary trees. It supports a $ \ensuremath{\mathrm{meld}(\ensuremath{\mathit{h}})}$ operation that allows the priority queue to absorb the elements of a second priority queue $ \ensuremath{\ensuremath{\mathit{h}}}$.



Subsections

opendatastructures.org

13 . 1 BinaryTrie: A digital search tree

Assigned source reading · Pat Morin

Pat Morin — Open Data Structures, pseudocode edition 0.1G

Original source · Creative Commons Attribution 2.5 Canada · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.


13.1 BinaryTrie: A digital search tree

A BinaryTrie encodes a set of $ \ensuremath{\ensuremath{\mathit{w}}}$ bit integers in a binary tree. All leaves in the tree have depth $ \ensuremath{\ensuremath{\mathit{w}}}$ and each integer is encoded as a root-to-leaf path. The path for the integer $ \ensuremath{\ensuremath{\mathit{x}}}$ turns left at level $ \ensuremath{\ensuremath{\mathit{i}}}$ if the $ \ensuremath{\ensuremath{\mathit{i}}}$th most significant bit of $ \ensuremath{\ensuremath{\mathit{x}}}$ is a 0 and turns right if it is a 1. Figure 13.1 shows an example for the case $ \ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}=4$, in which the trie stores the integers 3(0011), 9(1001), 12(1100), and 13(1101).

Figure 13.1: The integers stored in a binary trie are encoded as root-to-leaf paths.
\includegraphics[width=\textwidth ]{figs-python/binarytrie-ex-1}

Because the search path for a value $ \ensuremath{\ensuremath{\mathit{x}}}$ depends on the bits of $ \ensuremath{\ensuremath{\mathit{x}}}$, it will be helpful to name the children of a node, $ \ensuremath{\ensuremath{\mathit{u}}}$, $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{child}}[0]}$ ( $ \ensuremath{\ensuremath{\mathit{left}}}$) and $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{child}}[1]}$ ( $ \ensuremath{\ensuremath{\mathit{right}}}$). These child pointers will actually serve double-duty. Since the leaves in a binary trie have no children, the pointers are used to string the leaves together into a doubly-linked list. For a leaf in the binary trie $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{child}}[0]}$ ( $ \ensuremath{\ensuremath{\mathit{prev}}}$) is the node that comes before $ \ensuremath{\ensuremath{\mathit{u}}}$ in the list and $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{child}}[1]}$ ( $ \ensuremath{\ensuremath{\mathit{next}}}$) is the node that follows $ \ensuremath{\ensuremath{\mathit{u}}}$ in the list. A special node, $ \ensuremath{\ensuremath{\mathit{dummy}}}$, is used both before the first node and after the last node in the list (see Section 3.2).

Each node, $ \ensuremath{\ensuremath{\mathit{u}}}$, also contains an additional pointer $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{jump}}}$. If $ \ensuremath{\ensuremath{\mathit{u}}}$'s left child is missing, then $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{jump}}}$ points to the smallest leaf in $ \ensuremath{\ensuremath{\mathit{u}}}$'s subtree. If $ \ensuremath{\ensuremath{\mathit{u}}}$'s right child is missing, then $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{jump}}}$ points to the largest leaf in $ \ensuremath{\ensuremath{\mathit{u}}}$'s subtree. An example of a BinaryTrie, showing $ \ensuremath{\ensuremath{\mathit{jump}}}$ pointers and the doubly-linked list at the leaves, is shown in Figure 13.2.

Figure 13.2: A BinaryTrie with $ \ensuremath{\ensuremath{\mathit{jump}}}$ pointers shown as curved dashed edges.
\includegraphics[width=\textwidth ]{figs-python/binarytrie-ex-2}

The $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$ operation in a BinaryTrie is fairly straightforward. We try to follow the search path for $ \ensuremath{\ensuremath{\mathit{x}}}$ in the trie. If we reach a leaf, then we have found $ \ensuremath{\ensuremath{\mathit{x}}}$. If we reach a node $ \ensuremath{\ensuremath{\mathit{u}}}$ where we cannot proceed (because $ \ensuremath{\ensuremath{\mathit{u}}}$ is missing a child), then we follow $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{jump}}}$, which takes us either to the smallest leaf larger than $ \ensuremath{\ensuremath{\mathit{x}}}$ or the largest leaf smaller than $ \ensuremath{\ensuremath{\mathit{x}}}$. Which of these two cases occurs depends on whether $ \ensuremath{\ensuremath{\mathit{u}}}$ is missing its left or right child, respectively. In the former case ( $ \ensuremath{\ensuremath{\mathit{u}}}$ is missing its left child), we have found the node we want. In the latter case ( $ \ensuremath{\ensuremath{\mathit{u}}}$ is missing its right child), we can use the linked list to reach the node we want. Each of these cases is illustrated in Figure 13.3.
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{find}(\ensur...
...\ensuremath{\mathit{u}}.\ensuremath{\mathit{x}}}\\
\end{flushleft}\end{leftbar}

Figure 13.3: The paths followed by $ \ensuremath{\mathrm{find}(5)}$ and $ \ensuremath{\mathrm{find}(8)}$.
\includegraphics[width=\textwidth ]{figs-python/binarytrie-ex-3}
The running-time of the $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$ method is dominated by the time it takes to follow a root-to-leaf path, so it runs in $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}})$ time.

The $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ operation in a BinaryTrie is also fairly straightforward, but has a lot of work to do:

  1. It follows the search path for $ \ensuremath{\ensuremath{\mathit{x}}}$ until reaching a node $ \ensuremath{\ensuremath{\mathit{u}}}$ where it can no longer proceed.
  2. It creates the remainder of the search path from $ \ensuremath{\ensuremath{\mathit{u}}}$ to a leaf that contains $ \ensuremath{\ensuremath{\mathit{x}}}$.
  3. It adds the node, $ \ensuremath{u}'$, containing $ \ensuremath{\ensuremath{\mathit{x}}}$ to the linked list of leaves (it has access to the predecessor, $ \ensuremath{\ensuremath{\mathit{pred}}}$, of $ \ensuremath{u}'$ in the linked list from the $ \ensuremath{\ensuremath{\mathit{jump}}}$ pointer of the last node, $ \ensuremath{\ensuremath{\mathit{u}}}$, encountered during step 1.)
  4. It walks back up the search path for $ \ensuremath{\ensuremath{\mathit{x}}}$ adjusting $ \ensuremath{\ensuremath{\mathit{jump}}}$ pointers at the nodes whose $ \ensuremath{\ensuremath{\mathit{jump}}}$ pointer should now point to $ \ensuremath{\ensuremath{\mathit{x}}}$.
An addition is illustrated in Figure 13.4.
Figure 13.4: Adding the values 2 and 15 to the BinaryTrie in Figure 13.2.
\includegraphics[width=\textwidth ]{figs-python/binarytrie-add}

\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{add}(\ensure...
...return}} \ensuremath{\ensuremath{\mathit{true}}}\\
\end{flushleft}\end{leftbar}
This method performs one walk down the search path for $ \ensuremath{\ensuremath{\mathit{x}}}$ and one walk back up. Each step of these walks takes constant time, so the $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ method runs in $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}})$ time.

The $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ operation undoes the work of $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$. Like $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$, it has a lot of work to do:

  1. It follows the search path for $ \ensuremath{\ensuremath{\mathit{x}}}$ until reaching the leaf, $ \ensuremath{\ensuremath{\mathit{u}}}$, containing $ \ensuremath{\ensuremath{\mathit{x}}}$.
  2. It removes $ \ensuremath{\ensuremath{\mathit{u}}}$ from the doubly-linked list.
  3. It deletes $ \ensuremath{\ensuremath{\mathit{u}}}$ and then walks back up the search path for $ \ensuremath{\ensuremath{\mathit{x}}}$ deleting nodes until reaching a node $ \ensuremath{\ensuremath{\mathit{v}}}$ that has a child that is not on the search path for $ \ensuremath{\ensuremath{\mathit{x}}}$.
  4. It walks upwards from $ \ensuremath{\ensuremath{\mathit{v}}}$ to the root updating any $ \ensuremath{\ensuremath{\mathit{jump}}}$ pointers that point to $ \ensuremath{\ensuremath{\mathit{u}}}$.
A removal is illustrated in Figure 13.5.
Figure 13.5: Removing the value 9 from the BinaryTrie in Figure 13.2.
\includegraphics[scale=0.90909]{figs-python/binarytrie-remove}

\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{remove}(\ens...
...return}} \ensuremath{\ensuremath{\mathit{true}}}\\
\end{flushleft}\end{leftbar}

Theorem 13..1   A BinaryTrie implements the SSet interface for $ \ensuremath{\ensuremath{\mathit{w}}}$-bit integers. A BinaryTrie supports the operations $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$, $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$, and $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$ in $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}})$ time per operation. The space used by a BinaryTrie that stores $ \ensuremath{\ensuremath{\mathit{n}}}$ values is $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}\cdot\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}})$.

opendatastructures.org

Control flow and error handling

Assigned source reading · Mozilla Contributors

MDN Web Docs — Mozilla Contributors

Original source · Creative Commons Attribution-ShareAlike 2.5 or later · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.

Control flow and error handling

JavaScript supports a compact set of statements, specifically control flow statements, that you can use to incorporate a great deal of interactivity in your application. This chapter provides an overview of these statements.

The JavaScript reference contains exhaustive details about the statements in this chapter. The semicolon (;) character is used to separate statements in JavaScript code.

Any JavaScript expression is also a statement. See Expressions and operators for complete information about expressions.

Block statement

The most basic statement is a block statement, which is used to group statements. The block is delimited by a pair of curly braces:

js
{
  statement1;
  statement2;
  // …
  statementN;
}

Example

Block statements are commonly used with control flow statements (if, for, while).

js
while (x < 10) {
  x++;
}

Here, { x++; } is the block statement.

Note: var-declared variables are not block-scoped, but are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. For example:

js
var x = 1;
{
  var x = 2;
}
console.log(x); // 2

This outputs 2 because the var x statement within the block is in the same scope as the var x statement before the block. (In C or Java, the equivalent code would have output 1.)

This scoping effect can be mitigated by using let or const.

Conditional statements

A conditional statement is a set of commands that executes if a specified condition is true. JavaScript supports two conditional statements: if...else and switch.

if...else statement

Use the if statement to execute a statement if a logical condition is true. Use the optional else clause to execute a statement if the condition is false.

An if statement looks like this:

js
if (condition) {
  statement1;
} else {
  statement2;
}

Here, the condition can be any expression that evaluates to true or false. (See Boolean for an explanation of what evaluates to true and false.)

If condition evaluates to true, statement1 is executed. Otherwise, statement2 is executed. statement1 and statement2 can be any statement, including further nested if statements.

You can also compound the statements using else if to have multiple conditions tested in sequence, as follows:

js
if (condition1) {
  statement1;
} else if (condition2) {
  statement2;
} else if (conditionN) {
  statementN;
} else {
  statementLast;
}

In the case of multiple conditions, only the first logical condition which evaluates to true will be executed. To execute multiple statements, group them within a block statement ({ /* … */ }).

Best practice

In general, it's good practice to always use block statements—especially when nesting if statements:

js
if (condition) {
  // Statements for when condition is true
  // …
} else {
  // Statements for when condition is false
  // …
}

In general it's good practice to not have an if...else with an assignment like x = y as a condition:

js
if (x = y) {
  // statements here
}

However, in the rare case you find yourself wanting to do something like that, the while documentation has a Using an assignment as a condition section with guidance on a general best-practice syntax you should know about and follow.

Falsy values

The following values evaluate to false (also known as Falsy values):

  • false
  • undefined
  • null
  • 0
  • NaN
  • the empty string ("")

All other values—including all objects—evaluate to true when passed to a conditional statement.

Note: Do not confuse the primitive boolean values true and false with the true and false values of the Boolean object!

For example:

js
const b = new Boolean(false);
if (b) {
  // this condition evaluates to true
}
if (b == true) {
  // this condition evaluates to false
}

Example

In the following example, the function checkData returns true if the number of characters in a Text object is three. Otherwise, it displays an alert and returns false.

js
function checkData() {
  if (document.form1.threeChar.value.length === 3) {
    return true;
  }
  alert(
    `Enter exactly three characters. ${document.form1.threeChar.value} is not valid.`,
  );
  return false;
}

switch statement

A switch statement allows a program to evaluate an expression and attempt to match the expression's value to a case label. If a match is found, the program executes the associated statement.

A switch statement looks like this:

js
switch (expression) {
  case label1:
    statements1;
    break;
  case label2:
    statements2;
    break;
  // …
  default:
    statementsDefault;
}

JavaScript evaluates the above switch statement as follows:

  • The program first looks for a case clause with a label matching the value of expression and then transfers control to that clause, executing the associated statements.
  • If no matching label is found, the program looks for the optional default clause:
    • If a default clause is found, the program transfers control to that clause, executing the associated statements.
    • If no default clause is found, the program resumes execution at the statement following the end of switch.
    • (By convention, the default clause is written as the last clause, but it does not need to be so.)

break statements

The optional break statement associated with each case clause ensures that the program breaks out of switch once the matched statement is executed, and then continues execution at the statement following switch. If break is omitted, the program continues execution inside the switch statement (and will execute statements under the next case, and so on).

Example

In the following example, if fruitType evaluates to "Bananas", the program matches the value with case "Bananas" and executes the associated statement. When break is encountered, the program exits the switch and continues execution from the statement following switch. If break were omitted, the statement for case "Cherries" would also be executed.

js
switch (fruitType) {
  case "Oranges":
    console.log("Oranges are $0.59 a pound.");
    break;
  case "Apples":
    console.log("Apples are $0.32 a pound.");
    break;
  case "Bananas":
    console.log("Bananas are $0.48 a pound.");
    break;
  case "Cherries":
    console.log("Cherries are $3.00 a pound.");
    break;
  case "Mangoes":
    console.log("Mangoes are $0.56 a pound.");
    break;
  case "Papayas":
    console.log("Papayas are $2.79 a pound.");
    break;
  default:
    console.log(`Sorry, we are out of ${fruitType}.`);
}
console.log("Is there anything else you'd like?");

Exception handling statements

You can throw exceptions using the throw statement and handle them using the try...catch statements.

Exception types

Just about any object can be thrown in JavaScript. Nevertheless, not all thrown objects are created equal. While it is common to throw numbers or strings as errors, it is frequently more effective to use one of the exception types specifically created for this purpose:

throw statement

Use the throw statement to throw an exception. A throw statement specifies the value to be thrown:

js
throw expression;

You may throw any expression, not just expressions of a specific type. The following code throws several exceptions of varying types:

js
throw "Error2"; // String type
throw 42; // Number type
throw true; // Boolean type
throw {
  toString() {
    return "I'm an object!";
  },
};

try...catch statement

The try...catch statement marks a block of statements to try, and specifies one or more responses should an exception be thrown. If an exception is thrown, the try...catch statement catches it.

The try...catch statement consists of a try block, which contains one or more statements, and a catch block, containing statements that specify what to do if an exception is thrown in the try block.

In other words, you want the try block to succeed—but if it does not, you want control to pass to the catch block. If any statement within the try block (or in a function called from within the try block) throws an exception, control immediately shifts to the catch block. If no exception is thrown in the try block, the catch block is skipped. The finally block executes after the try and catch blocks execute but before the statements following the try...catch statement.

The following example uses a try...catch statement. The example calls a function that retrieves a month name from an array based on the value passed to the function. If the value does not correspond to a month number (1 – 12), an exception is thrown with the value 'Invalid month code' and the statements in the catch block set the monthName variable to 'unknown'.

js
function getMonthName(mo) {
  mo--; // Adjust month number for array index (so that 0 = Jan, 11 = Dec)
  // prettier-ignore
  const months = [
    "Jan", "Feb", "Mar", "Apr", "May", "Jun",
    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
  ];
  if (!months[mo]) {
    throw new Error("Invalid month code"); // throw keyword is used here
  }
  return months[mo];
}

try {
  // statements to try
  monthName = getMonthName(myMonth); // function could throw exception
} catch (e) {
  monthName = "unknown";
  logMyErrors(e); // pass exception object to error handler (i.e. your own function)
}

The catch block

You can use a catch block to handle all exceptions that may be generated in the try block.

js
catch (exception) {
  statements
}

The catch block specifies an identifier (exception in the preceding syntax) that holds the value specified by the throw statement. You can use this identifier to get information about the exception that was thrown.

JavaScript creates this identifier when the catch block is entered. The identifier lasts only for the duration of the catch block. Once the catch block finishes executing, the identifier no longer exists.

For example, the following code throws an exception. When the exception occurs, control transfers to the catch block.

js
try {
  throw "myException"; // generates an exception
} catch (err) {
  // statements to handle any exceptions
  logMyErrors(err); // pass exception object to error handler
}

Note: When logging errors to the console inside a catch block, using console.error() rather than console.log() is advised for debugging. It formats the message as an error, and adds it to the list of error messages generated by the page.

The finally block

The finally block contains statements to be executed after the try and catch blocks execute. Additionally, the finally block executes before the code that follows the try...catch...finally statement.

It is also important to note that the finally block will execute whether or not an exception is thrown. If an exception is thrown, however, the statements in the finally block execute even if no catch block handles the exception that was thrown.

You can use the finally block to make your script fail gracefully when an exception occurs. For example, you may need to release a resource that your script has tied up.

The following example opens a file and then executes statements that use the file. (Server-side JavaScript allows you to access files.) If an exception is thrown while the file is open, the finally block closes the file before the script fails. Using finally here ensures that the file is never left open, even if an error occurs.

js
openMyFile();
try {
  writeMyFile(theData); // This may throw an error
} catch (e) {
  handleError(e); // If an error occurred, handle it
} finally {
  closeMyFile(); // Always close the resource
}

If the finally block returns a value, this value becomes the return value of the entire try...catch...finally production, regardless of any return statements in the try and catch blocks:

js
function f() {
  try {
    console.log(0);
    throw "bogus";
  } catch (e) {
    console.log(1);
    // This return statement is suspended
    // until finally block has completed
    return true;
    console.log(2); // not reachable
  } finally {
    console.log(3);
    return false; // overwrites the previous "return"
    // `f` exits here
    console.log(4); // not reachable
  }
  console.log(5); // not reachable
}
console.log(f()); // 0, 1, 3, false

Overwriting of return values by the finally block also applies to exceptions thrown or re-thrown inside of the catch block:

js
function f() {
  try {
    throw "bogus";
  } catch (e) {
    console.log('caught inner "bogus"');
    // This throw statement is suspended until
    // finally block has completed
    throw e;
  } finally {
    return false; // overwrites the previous "throw"
    // `f` exits here
  }
}

try {
  console.log(f());
} catch (e) {
  // this is never reached!
  // while f() executes, the `finally` block returns false,
  // which overwrites the `throw` inside the above `catch`
  console.log('caught outer "bogus"');
}

// Logs:
// caught inner "bogus"
// false

Nesting try...catch statements

You can nest one or more try...catch statements.

If an inner try block does not have a corresponding catch block:

  1. it must contain a finally block, and
  2. the enclosing try...catch statement's catch block is checked for a match.

For more information, see nested try-blocks on the try...catch reference page.

Utilizing Error objects

Depending on the type of error, you may be able to use the name and message properties to get a more refined message.

The name property provides the general class of Error (such as DOMException or Error), while message generally provides a more succinct message than one would get by converting the error object to a string.

If you are throwing your own exceptions, in order to take advantage of these properties (such as if your catch block doesn't discriminate between your own exceptions and system ones), you can use the Error constructor.

For example:

js
function doSomethingErrorProne() {
  if (ourCodeMakesAMistake()) {
    throw new Error("The message");
  }
  doSomethingToGetAJavaScriptError();
}

try {
  doSomethingErrorProne();
} catch (e) {
  // Now, we actually use `console.error()`
  console.error(e.name); // 'Error'
  console.error(e.message); // 'The message', or a JavaScript error message
}

3.4. Transactions #

Assigned source reading · The PostgreSQL Global Development Group and The Regents of the University of California

Portions Copyright © 1996–2026 The PostgreSQL Global Development Group. Portions Copyright © 1994 The Regents of the University of California.

Original source · PostgreSQL License · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.

Full license and notices
License
PostgreSQL is released under the
PostgreSQL License
,
a liberal Open Source license, similar to the BSD or MIT licenses.
PostgreSQL Database Management System
(also known as Postgres, formerly as Postgres95)
Portions Copyright © 1996-2026, The PostgreSQL Global Development Group
Portions Copyright © 1994, The Regents of the University of California
Permission to use, copy, modify, and distribute this software and its
  documentation for any purpose, without fee, and without a written agreement
  is hereby granted, provided that the above copyright notice and this
  paragraph and the following two paragraphs appear in all copies.
IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
  DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
  LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
  DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE
  POSSIBILITY OF SUCH DAMAGE.
THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
  AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
  ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO
  PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
Will PostgreSQL ever be released under a different license?
The PostgreSQL Global Development Group remains committed to making
  PostgreSQL available as free and open source software in perpetuity. There are
  no plans to change the PostgreSQL License or release PostgreSQL under a
  different license.
If you would like to read more about this topic, then please take a look at
  the
mailing list archives
at one of the many discussions
  on this subject.

3.4. Transactions #

Transactions are a fundamental concept of all database systems. The essential point of a transaction is that it bundles multiple steps into a single, all-or-nothing operation. The intermediate states between the steps are not visible to other concurrent transactions, and if some failure occurs that prevents the transaction from completing, then none of the steps affect the database at all.

For example, consider a bank database that contains balances for various customer accounts, as well as total deposit balances for branches. Suppose that we want to record a payment of $100.00 from Alice's account to Bob's account. Simplifying outrageously, the SQL commands for this might look like:

UPDATE accounts SET balance = balance - 100.00
    WHERE name = 'Alice';
UPDATE branches SET balance = balance - 100.00
    WHERE name = (SELECT branch_name FROM accounts WHERE name = 'Alice');
UPDATE accounts SET balance = balance + 100.00
    WHERE name = 'Bob';
UPDATE branches SET balance = balance + 100.00
    WHERE name = (SELECT branch_name FROM accounts WHERE name = 'Bob');

The details of these commands are not important here; the important point is that there are several separate updates involved to accomplish this rather simple operation. Our bank's officers will want to be assured that either all these updates happen, or none of them happen. It would certainly not do for a system failure to result in Bob receiving $100.00 that was not debited from Alice. Nor would Alice long remain a happy customer if she was debited without Bob being credited. We need a guarantee that if something goes wrong partway through the operation, none of the steps executed so far will take effect. Grouping the updates into a transaction gives us this guarantee. A transaction is said to be atomic: from the point of view of other transactions, it either happens completely or not at all.

We also want a guarantee that once a transaction is completed and acknowledged by the database system, it has indeed been permanently recorded and won't be lost even if a crash ensues shortly thereafter. For example, if we are recording a cash withdrawal by Bob, we do not want any chance that the debit to his account will disappear in a crash just after he walks out the bank door. A transactional database guarantees that all the updates made by a transaction are logged in permanent storage (i.e., on disk) before the transaction is reported complete.

Another important property of transactional databases is closely related to the notion of atomic updates: when multiple transactions are running concurrently, each one should not be able to see the incomplete changes made by others. For example, if one transaction is busy totalling all the branch balances, it would not do for it to include the debit from Alice's branch but not the credit to Bob's branch, nor vice versa. So transactions must be all-or-nothing not only in terms of their permanent effect on the database, but also in terms of their visibility as they happen. The updates made so far by an open transaction are invisible to other transactions until the transaction completes, whereupon all the updates become visible simultaneously.

In PostgreSQL, a transaction is set up by surrounding the SQL commands of the transaction with BEGIN and COMMIT commands. So our banking transaction would actually look like:

BEGIN;
UPDATE accounts SET balance = balance - 100.00
    WHERE name = 'Alice';
-- etc etc
COMMIT;

If, partway through the transaction, we decide we do not want to commit (perhaps we just noticed that Alice's balance went negative), we can issue the command ROLLBACK instead of COMMIT, and all our updates so far will be canceled.

PostgreSQL actually treats every SQL statement as being executed within a transaction. If you do not issue a BEGIN command, then each individual statement has an implicit BEGIN and (if successful) COMMIT wrapped around it. A group of statements surrounded by BEGIN and COMMIT is sometimes called a transaction block.

Note

Some client libraries issue BEGIN and COMMIT commands automatically, so that you might get the effect of transaction blocks without asking. Check the documentation for the interface you are using.

It's possible to control the statements in a transaction in a more granular fashion through the use of savepoints. Savepoints allow you to selectively discard parts of the transaction, while committing the rest. After defining a savepoint with SAVEPOINT, you can if needed roll back to the savepoint with ROLLBACK TO. All the transaction's database changes between defining the savepoint and rolling back to it are discarded, but changes earlier than the savepoint are kept.

After rolling back to a savepoint, it continues to be defined, so you can roll back to it several times. Conversely, if you are sure you won't need to roll back to a particular savepoint again, it can be released, so the system can free some resources. Keep in mind that either releasing or rolling back to a savepoint will automatically release all savepoints that were defined after it.

All this is happening within the transaction block, so none of it is visible to other database sessions. When and if you commit the transaction block, the committed actions become visible as a unit to other sessions, while the rolled-back actions never become visible at all.

Remembering the bank database, suppose we debit $100.00 from Alice's account, and credit Bob's account, only to find later that we should have credited Wally's account. We could do it using savepoints like this:

BEGIN;
UPDATE accounts SET balance = balance - 100.00
    WHERE name = 'Alice';
SAVEPOINT my_savepoint;
UPDATE accounts SET balance = balance + 100.00
    WHERE name = 'Bob';
-- oops ... forget that and use Wally's account
ROLLBACK TO my_savepoint;
UPDATE accounts SET balance = balance + 100.00
    WHERE name = 'Wally';
COMMIT;

This example is, of course, oversimplified, but there's a lot of control possible in a transaction block through the use of savepoints. Moreover, ROLLBACK TO is the only way to regain control of a transaction block that was put in aborted state by the system due to an error, short of rolling it back completely and starting again.

HTTP caching

Assigned source reading · Mozilla Contributors

MDN Web Docs — Mozilla Contributors

Original source · Creative Commons Attribution-ShareAlike 2.5 or later · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.

HTTP caching

The HTTP cache stores a response associated with a request and reuses the stored response for subsequent requests.

There are several advantages to reusability. First, since there is no need to deliver the request to the origin server, then the closer the client and cache are, the faster the response will be. The most typical example is when the browser itself stores a cache for browser requests.

Also, when a response is reusable, the origin server does not need to process the request — so it does not need to parse and route the request, restore the session based on the cookie, query the DB for results, or render the template engine. That reduces the load on the server.

Proper operation of the cache is critical to the health of the system.

Types of caches

In the HTTP Caching spec, there are two main types of caches: private caches and shared caches.

Private caches

A private cache is a cache tied to a specific client — typically a browser cache. Since the stored response is not shared with other clients, a private cache can store a personalized response for that user.

On the other hand, if personalized contents are stored in a cache other than a private cache, then other users may be able to retrieve those contents — which may cause unintentional information leakage.

If a response contains personalized content and you want to store the response only in the private cache, you must specify a private directive.

http
Cache-Control: private

Personalized contents are usually controlled by cookies, but the presence of a cookie does not always indicate that it is private, and thus a cookie alone does not make the response private.

Shared cache

The shared cache is located between the client and the server and can store responses that can be shared among users. And shared caches can be further sub-classified into proxy caches and managed caches.

Proxy caches

In addition to the function of access control, some proxies implement caching to reduce traffic out of the network. This is usually not managed by the service developer, so it must be controlled by appropriate HTTP headers and so on. However, in the past, outdated proxy-cache implementations — such as implementations that do not properly understand the HTTP Caching standard — have often caused problems for developers.

Kitchen-sink headers like the following are used to try to work around "old and not updated proxy cache" implementations that do not understand current HTTP Caching spec directives like no-store.

http
Cache-Control: no-store, no-cache, max-age=0, must-revalidate, proxy-revalidate

However, in recent years, as HTTPS has become more common and client/server communication has become encrypted, proxy caches in the path can only tunnel a response and can't behave as a cache, in many cases. So in that scenario, there is no need to worry about outdated proxy cache implementations that cannot even see the response.

On the other hand, if a TLS bridge proxy decrypts all communications in a person-in-the-middle manner by installing a certificate from a CA (certificate authority) managed by the organization on the PC, and performs access control, etc. — it is possible to see the contents of the response and cache it. However, since CT (certificate transparency) has become widespread in recent years, and some browsers only allow certificates issued with an SCT (signed certificate timestamp), this method requires the application of an enterprise policy. In such a controlled environment, there is no need to worry about the proxy cache being "out of date and not updated".

Managed caches

Managed caches are explicitly deployed by service developers to offload the origin server and to deliver content efficiently. Examples include reverse proxies, CDNs, and service workers in combination with the Cache API.

The characteristics of managed caches vary depending on the product deployed. In most cases, you can control the cache's behavior through the Cache-Control header and your own configuration files or dashboards.

For example, the HTTP Caching specification essentially does not define a way to explicitly delete a cache — but with a managed cache, the stored response can be deleted at any time through dashboard operations, API calls, restarts, and so on. That allows for a more proactive caching strategy.

It is also possible to ignore the standard HTTP Caching spec protocols in favor of explicit manipulation. For example, the following can be specified to opt-out of a private cache or proxy cache, while using your own strategy to cache only in a managed cache.

http
Cache-Control: no-store

For example, Varnish Cache uses VCL (Varnish Configuration Language, a type of DSL) logic to handle cache storage, while service workers in combination with the Cache API allow you to create that logic in JavaScript.

That means if a managed cache intentionally ignores a no-store directive, there is no need to perceive it as being "non-compliant" with the standard. What you should do is, avoid using kitchen-sink headers, but carefully read the documentation of whatever managed-cache mechanism you're using, and ensure you're controlling the cache properly in the ways provided by the mechanism you've chosen to use.

Note that some CDNs provide their own headers that are effective only for that CDN (for example, Surrogate-Control). Currently, work is underway to define a CDN-Cache-Control header to standardize those.

Types of caches, including a private cache in the browser, a shared (proxy) cache, a reverse proxy cache, and a shared (managed) cache in a CDN, leading to the origin server's cache

Heuristic caching

HTTP is designed to cache as much as possible, so even if no Cache-Control is given, responses will get stored and reused if certain conditions are met. This is called heuristic caching.

For example, take the following response. This response was last updated 1 year ago.

http
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 1024
Date: Tue, 22 Feb 2022 22:22:22 GMT
Last-Modified: Tue, 22 Feb 2021 22:22:22 GMT

<!doctype html>
…

It is heuristically known that content which has not been updated for a full year will not be updated for some time after that. Therefore, the client stores this response (despite the lack of max-age) and reuses it for a while. How long to reuse is up to the implementation, but the specification recommends about 10% (in this case 0.1 year) of the time after storing.

Heuristic caching is a workaround that came before Cache-Control support became widely adopted, and basically all responses should explicitly specify a Cache-Control header.

Fresh and stale based on age

Stored HTTP responses have two states: fresh and stale. The fresh state usually indicates that the response is still valid and can be reused, while the stale state means that the cached response has already expired.

The criterion for determining when a response is fresh and when it is stale is age. In HTTP, age is the time elapsed since the response was generated. This is similar to the TTL in other caching mechanisms.

Take the following example response (604800 seconds is one week):

http
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 1024
Date: Tue, 22 Feb 2022 22:22:22 GMT
Cache-Control: max-age=604800

<!doctype html>
…

The cache that stored the example response calculates the time elapsed since the response was generated and uses the result as the response's age.

For the example response, the meaning of max-age is the following:

  • If the age of the response is less than one week, the response is fresh.
  • If the age of the response is more than one week, the response is stale.

As long as the stored response remains fresh, it will be used to fulfill client requests.

When a response is stored in a shared cache, it is possible to tell the client the age of the response. Continuing with the example, if the shared cache stored the response for one day, the shared cache would send the following response to subsequent client requests.

http
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 1024
Date: Tue, 22 Feb 2022 22:22:22 GMT
Cache-Control: max-age=604800
Age: 86400

<!doctype html>
…

The client which receives that response will find it to be fresh for the remaining 518400 seconds, the difference between the response's max-age and Age.

Expires or max-age

In HTTP/1.0, freshness used to be specified by the Expires header.

The Expires header specifies the lifetime of the cache using an explicit time rather than by specifying an elapsed time.

http
Expires: Tue, 28 Feb 2022 22:22:22 GMT

However, the time format is difficult to parse, many implementation bugs were found, and it is possible to induce problems by intentionally shifting the system clock; therefore, max-age — for specifying an elapsed time — was adopted for Cache-Control in HTTP/1.1.

If both Expires and Cache-Control: max-age are available, max-age is defined to be preferred. So it is not necessary to provide Expires now that HTTP/1.1 is widely used.

Vary

The way that responses are distinguished from one another is essentially based on their URLs:

URL Response body
https://example.com/index.html <!doctype html>...
https://example.com/style.css body { ...
https://example.com/script.js function main () { ...

But the contents of responses are not always the same, even if they have the same URL. Especially when content negotiation is performed, the response from the server can depend on the values of the Accept, Accept-Language, and Accept-Encoding request headers.

For example, for English content returned with an Accept-Language: en header and cached, it is undesirable to then reuse that cached response for requests that have an Accept-Language: ja request header. In this case, you can cause the responses to be cached separately — based on language — by adding Accept-Language to the value of the Vary header.

http
Vary: Accept-Language

That causes the cache to be keyed based on a composite of the response URL and the Accept-Language request header — rather than being based just on the response URL.

URL Accept-Language Response body
https://example.com/index.html ja-JP <!doctype html>...
https://example.com/index.html en-US <!doctype html>...
https://example.com/style.css ja-JP body { ...
https://example.com/script.js ja-JP function main () { ...

Also, if you are providing content optimization (for example, for responsive design) based on the user agent, you may be tempted to include User-Agent in the value of the Vary header. However, the User-Agent request header generally has a very large number of variations, which drastically reduces the chance that the cache will be reused. So if possible, instead consider a way to vary behavior based on feature detection rather than based on the User-Agent request header.

For applications that employ cookies to prevent others from reusing cached personalized content, you should specify Cache-Control: private instead of specifying a cookie for Vary.

Validation

Stale responses are not immediately discarded. HTTP has a mechanism to transform a stale response into a fresh one by asking the origin server. This is called validation, or sometimes, revalidation.

Validation is done by using a conditional request that includes an If-Modified-Since or If-None-Match request header.

If-Modified-Since

The following response was generated at 22:22:22 and has a max-age of 1 hour, so you know that it is fresh until 23:22:22.

http
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 1024
Date: Tue, 22 Feb 2022 22:22:22 GMT
Last-Modified: Tue, 22 Feb 2022 22:00:00 GMT
Cache-Control: max-age=3600

<!doctype html>
…

At 23:22:22, the response becomes stale and the cache cannot be reused. So the request below shows a client sending a request with an If-Modified-Since request header, to ask the server if there have been any changes made since the specified time.

http
GET /index.html HTTP/1.1
Host: example.com
Accept: text/html
If-Modified-Since: Tue, 22 Feb 2022 22:00:00 GMT

The server will respond with 304 Not Modified if the content has not changed since the specified time.

Since this response only indicates "no change", there is no response body — there's just a status code — so the transfer size is extremely small.

http
HTTP/1.1 304 Not Modified
Content-Type: text/html
Date: Tue, 22 Feb 2022 23:22:22 GMT
Last-Modified: Tue, 22 Feb 2022 22:00:00 GMT
Cache-Control: max-age=3600

Upon receiving that response, the client reverts the stored stale response back to being fresh and can reuse it during the remaining 1 hour.

The server can obtain the modification time from the operating-system file system, which is relatively easy to do for the case of serving static files. However, there are some problems; for example, the time format is complex and difficult to parse, and distributed servers have difficulty synchronizing file-update times.

To solve such problems, the ETag response header was standardized as an alternative.

ETag/If-None-Match

The value of the ETag response header is an arbitrary value generated by the server. There are no restrictions on how the server must generate the value, so servers are free to set the value based on whatever means they choose — such as a hash of the body contents or a version number.

As an example, if a hash value is used for the ETag header and the hash value of the index.html resource is 33a64df5, the response will be as follows:

http
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 1024
Date: Tue, 22 Feb 2022 22:22:22 GMT
ETag: "33a64df5"
Cache-Control: max-age=3600

<!doctype html>
…

If that response is stale, the client takes the value of the ETag response header for the cached response, and puts it into the If-None-Match request header, to ask the server if the resource has been modified:

http
GET /index.html HTTP/1.1
Host: example.com
Accept: text/html
If-None-Match: "33a64df5"

The server will return 304 Not Modified if the value of the ETag header it determines for the requested resource is the same as the If-None-Match value in the request.

But if the server determines the requested resource should now have a different ETag value, the server will instead respond with a 200 OK and the latest version of the resource.

Note: RFC9110 prefers that servers send both ETag and Last-Modified for a 200 response if possible. During cache revalidation, if both If-Modified-Since and If-None-Match are present, then If-None-Match takes precedence for the validator. If you are only considering caching, you may think that Last-Modified is unnecessary. However, Last-Modified is not just useful for caching; it is a standard HTTP header that is also used by content-management (CMS) systems to display the last-modified time, by crawlers to adjust crawl frequency, and for other various purposes. So considering the overall HTTP ecosystem, it is better to provide both ETag and Last-Modified.

Force Revalidation

If you do not want a response to be reused, but instead want to always fetch the latest content from the server, you can use the no-cache directive to force validation.

By adding Cache-Control: no-cache to the response along with Last-Modified and ETag — as shown below — the client will receive a 200 OK response if the requested resource has been updated, or will otherwise receive a 304 Not Modified response if the requested resource has not been updated.

http
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 1024
Date: Tue, 22 Feb 2022 22:22:22 GMT
Last-Modified: Tue, 22 Feb 2022 22:00:00 GMT
ETag: "deadbeef"
Cache-Control: no-cache

<!doctype html>
…

Note: The no-cache directive (or equivalent, such as max-age=0, must-revalidate) does not guarantee revalidation for history navigations — such as those made using the Back button. If the back/forward cache (bfcache) is used, the browser restores a snapshot of the page without revalidating. Even when bfcache is not used, the browser may still serve the cached response without revalidating. This is allowed by the specification because history navigations are usually treated as restoring a snapshot of a historical session and not a new request for a previously visited page.

It is often stated that the combination of max-age=0 and must-revalidate has the same meaning as no-cache.

http
Cache-Control: max-age=0, must-revalidate

max-age=0 means that the response is immediately stale, and must-revalidate means that it must not be reused without revalidation once it is stale — so, in combination, the semantics seem to be the same as no-cache.

However, that usage of max-age=0 is a remnant of the fact that many implementations prior to HTTP/1.1 were unable to handle the no-cache directive — and so to deal with that limitation, max-age=0 was used as a workaround.

But now that HTTP/1.1-conformant servers are widely deployed, there's no reason to ever use that max-age=0 and must-revalidate combination — you should instead just use no-cache.

Don't cache

The no-cache directive does not prevent the storing of responses but instead prevents the reuse of responses without revalidation.

If you don't want a response stored in any cache, use no-store.

http
Cache-Control: no-store

However, in general, a "do not cache" requirement in practice amounts to the following set of circumstances:

  • Don't want the response stored by anyone other than the specific client, for privacy reasons.
  • Want to provide up-to-date information always.
  • Don't know what could happen in outdated implementations.

Under that set of circumstances, no-store is not always the most-appropriate directive.

The following sections look at the circumstances in more detail.

Do not share with others

It would be problematic if a response with personalized content is unexpectedly visible to other users of a cache.

In such a case, using the private directive will cause the personalized response to only be stored with the specific client and not be leaked to any other user of the cache.

http
Cache-Control: private

Provide up-to-date content every time

The no-store directive prevents a response from being stored, but does not delete any already-stored response for the same URL.

In other words, if there is an old response already stored for a particular URL, returning no-store will not prevent the old response from being reused.

However, a no-cache directive will force the client to send a validation request before reusing any stored response.

http
Cache-Control: no-cache

If the server does not support conditional requests, you can force the client to access the server every time and always get the latest response with 200 OK.

Dealing with outdated implementations

As a workaround for outdated implementations that ignore no-store, you may see kitchen-sink headers such as the following being used.

http
Cache-Control: no-store, no-cache, max-age=0, must-revalidate, proxy-revalidate

It is recommended to use no-cache as an alternative for dealing with such outdated implementations, and it is not a problem if no-cache is given from the beginning, since the server will always receive the request.

If it is the shared cache that you are concerned about, you can make sure to prevent unintended caching by also adding private:

http
Cache-Control: no-cache, private

What's lost by no-store

You may think adding no-store would be the right way to opt-out of caching.

However, it's not recommended to grant no-store liberally, because you lose many advantages that HTTP and browsers have, including the browser's back/forward cache.

Therefore, to get the advantages of the full feature set of the web platform, prefer the use of no-cache in combination with private.

Reload and force reload

Validation can be performed for requests as well as responses.

The reload and force reload actions are common examples of validation performed from the browser side.

Reload

For recovering from window corruption or updating to the latest version of the resource, browsers provide a reload function for users.

A simplified view of the HTTP request sent during a browser reload looks as follows:

http
GET / HTTP/1.1
Host: example.com
Cache-Control: max-age=0
If-None-Match: "deadbeef"
If-Modified-Since: Tue, 22 Feb 2022 20:20:20 GMT

(The requests from Chrome, Edge, and Firefox look very much like the above; the requests from Safari will look a bit different.)

The max-age=0 directive in the request specifies "reuse of responses with an age of 0 or less" — so, in effect, intermediately stored responses are not reused.

As a result, a request is validated by If-None-Match and If-Modified-Since.

That behavior is also defined in the Fetch standard and can be reproduced in JavaScript by calling fetch() with the cache mode set to no-cache (note that reload is not the right mode for this case):

js
// Note: "reload" is not the right mode for a normal reload; "no-cache" is
fetch("/", { cache: "no-cache" });

Force reload

Browsers use max-age=0 during reloads for backward-compatibility reasons — because many outdated implementations prior to HTTP/1.1 did not understand no-cache. But no-cache is fine now in this use case, and force reload is an additional way to bypass cached responses.

The HTTP Request during a browser force reload looks as follows:

http
GET / HTTP/1.1
Host: example.com
Pragma: no-cache
Cache-Control: no-cache

(The requests from Chrome, Edge, and Firefox look very much like the above; the requests from Safari will look a bit different.)

Since that's not a conditional request with no-cache, you can be sure you'll get a 200 OK from the origin server.

That behavior is also defined in the Fetch standard and can be reproduced in JavaScript by calling fetch() with the cache mode set to reload (note that it's not force-reload):

js
// Note: "reload" — rather than "no-cache" — is the right mode for a "force reload"
fetch("/", { cache: "reload" });

Avoiding revalidation

Content that never changes should be given a long max-age by using cache busting — that is, by including a version number, hash value, etc., in the request URL.

However, when the user reloads, a revalidation request is sent even though the server knows that the content is immutable.

To prevent that, the immutable directive can be used to explicitly indicate that revalidation is not required because the content never changes.

http
Cache-Control: max-age=31536000, immutable

That prevents unnecessary revalidation during reloads.

Note that, instead of implementing that directive, Chrome has changed its implementation so that revalidation is not performed during reloads for subresources.

Deleting stored responses

There is no way to delete responses on an intermediate server that have been stored with a long max-age.

Imagine that the following response from https://example.com/ was stored.

http
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 1024
Cache-Control: max-age=31536000

<!doctype html>
…

You may want to overwrite that response once it expired on the server, but there is nothing the server can do once the response is stored — since no more requests reach the server due to caching.

One of the methods mentioned in the specification is to send a request for the same URL with an unsafe method such as POST, but for many clients that is difficult to do.

The Clear-Site-Data: cache header and directive value can be used to clear browser caches — but has no effect on intermediate caches. Otherwise responses will remain in the browser cache until max-age expires, unless the user manually performs a reload, force-reload, or clear-history action.

Caching reduces access to the server, which means that the server loses control of that URL. If the server does not want to lose control of a URL — for example, in the case that a resource is frequently updated — you should add no-cache so that the server will always receive requests and send the intended responses.

Request collapse

The shared cache is primarily located before the origin server and is intended to reduce traffic to the origin server.

Thus, if multiple identical requests arrive at a shared cache at the same time, the intermediate cache will forward a single request on behalf of itself to the origin, which can then reuse the result for all clients. This is called request collapse.

Request collapse occurs when requests are arriving at the same time, so even if max-age=0 or no-cache is given in the response, it will be reused.

If the response is personalized to a particular user and you do not want it to be shared in collapse, you should add the private directive:

Request collapse shown as multiple clients sending GET requests and a cache consolidating them into one GET to the origin. The origin server responds with a 200 OK that the cache shares back to all clients.

Common caching patterns

There are many directives in the Cache-Control spec, and it may be difficult to understand all of them. But most websites can be covered by a combination of a handful of patterns.

This section describes the common patterns in designing caches.

Default settings

As mentioned above, the default behavior for caching (that is, for a response without Cache-Control) is not simply "don't cache" but implicit caching according to so-called "heuristic caching".

To avoid that heuristic caching, it's preferable to explicitly give all responses a default Cache-Control header.

To ensure that by default the latest versions of resources will always be transferred, it's common practice to make the default Cache-Control value include no-cache:

http
Cache-Control: no-cache

In addition, if the service implements cookies or other login methods, and the content is personalized for each user, private must be given too, to prevent sharing with other users:

http
Cache-Control: no-cache, private

Cache Busting

The resources that work best with caching are static immutable files whose contents never change. And for resources that do change, it is a common best practice to change the URL each time the content changes, so that the URL unit can be cached for a longer period.

As an example, consider the following HTML:

html
<script src="bundle.js"></script>
<link rel="stylesheet" href="build.css" />
<body>
  hello
</body>

In modern web development, JavaScript and CSS resources are frequently updated as development progresses. Also, if the versions of JavaScript and CSS resources that a client uses are out of sync, the display will break.

So the HTML above makes it difficult to cache bundle.js and build.css with max-age.

Therefore, you can serve the JavaScript and CSS with URLs that include a changing part based on a version number or hash value. Some of the ways to do that are shown below.

# version in filename
bundle.v123.js

# version in query
bundle.js?v=123

# hash in filename
bundle.YsAIAAAA-QG4G6kCMAMBAAAAAAAoK.js

# hash in query
bundle.js?v=YsAIAAAA-QG4G6kCMAMBAAAAAAAoK

Since the cache distinguishes resources from one another based on their URLs, the cache will not be reused again if the URL changes when a resource is updated.

html
<script src="bundle.v123.js"></script>
<link rel="stylesheet" href="build.v123.css" />
<body>
  hello
</body>

With that design, both JavaScript and CSS resources can be cached for a long time. So how long should max-age be set to? The QPACK specification provides an answer to that question.

QPACK is a standard for compressing HTTP header fields, with tables of commonly-used field values defined.

Some commonly-used cache-header values are shown below.

36 cache-control max-age=0
37 cache-control max-age=604800
38 cache-control max-age=2592000
39 cache-control no-cache
40 cache-control no-store
41 cache-control public, max-age=31536000

If you select one of those numbered options, you can compress values in 1 byte when transferred via HTTP3.

Numbers 37, 38, and 41 are for periods of one week, one month, and one year.

Because the cache removes old entries when new entries are saved, the probability that a stored response still exists after one week is not that high — even if max-age is set to 1 week. Therefore, in practice, it does not make much difference which one you choose.

Note that number 41 has the longest max-age (1 year), but with public.

The public value has the effect of making the response storable even if the Authorization header is present.

Note: The public directive should only be used if there is a need to store the response when the Authorization header is set. It is not required otherwise, because a response will be stored in the shared cache as long as max-age is given.

So if the response is personalized with basic authentication, the presence of public may cause problems. If you are concerned about that, you can choose the second-longest value, 38 (1 month).

http
# response for bundle.v123.js

# If you never personalize responses via Authorization
Cache-Control: public, max-age=31536000

# If you can't be certain
Cache-Control: max-age=2592000

Validation

Don't forget to set the Last-Modified and ETag headers, so that you don't have to re-transmit a resource when reloading. It's easy to generate those headers for pre-built static files.

The ETag value here may be a hash of the file.

http
# response for bundle.v123.js
Last-Modified: Tue, 22 Feb 2022 20:20:20 GMT
ETag: "YsAIAAAA-QG4G6kCMAMBAAAAAAAoK"

In addition, immutable can be added to prevent validation on reload.

The combined result is shown below.

http
# bundle.v123.js
HTTP/1.1 200 OK
Content-Type: text/javascript
Content-Length: 1024
Cache-Control: public, max-age=31536000, immutable
Last-Modified: Tue, 22 Feb 2022 20:20:20 GMT
ETag: "YsAIAAAA-QG4G6kCMAMBAAAAAAAoK"

Cache busting is a technique to make a response cacheable over a long period by changing the URL when the content changes. The technique can be applied to all subresources, such as images.

Note: When evaluating the use of immutable and QPACK: If you're concerned that immutable changes the predefined value provided by QPACK, consider that in this case, the immutable part can be encoded separately by splitting the Cache-Control value into two lines — though this is dependent on the encoding algorithm a particular QPACK implementation uses.

http
Cache-Control: public, max-age=31536000
Cache-Control: immutable

Main resources

Unlike subresources, main resources cannot be cache busted because their URLs can't be decorated in the same way that subresource URLs can be.

If the following HTML itself is stored, the latest version cannot be displayed even if the content is updated on the server side.

html
<script src="bundle.v123.js"></script>
<link rel="stylesheet" href="build.v123.css" />
<body>
  hello
</body>

For that case, no-cache would be appropriate — rather than no-store — since we don't want to store HTML, but instead just want it to always be up-to-date.

Furthermore, adding Last-Modified and ETag will allow clients to send conditional requests, and a 304 Not Modified can be returned if there have been no updates to the HTML:

http
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 1024
Cache-Control: no-cache
Last-Modified: Tue, 22 Feb 2022 20:20:20 GMT
ETag: "AAPuIbAOdvAGEETbgAAAAAAABAAE"

That setting is appropriate for non-personalized HTML, but for a response that gets personalized using cookies — for example, after a login — don't forget to also specify private:

http
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 1024
Cache-Control: no-cache, private
Last-Modified: Tue, 22 Feb 2022 20:20:20 GMT
ETag: "AAPuIbAOdvAGEETbgAAAAAAABAAE"
Set-Cookie: __Host-SID=AHNtAyt3fvJrUL5g5tnGwER; Secure; Path=/; HttpOnly

The same can be used for favicon.ico, manifest.json, .well-known, and API endpoints whose URLs cannot be changed using cache busting.

Most web content can be covered by a combination of the two patterns described above.

More about managed caches

With the method described in previous sections, subresources can be cached for a long time by using cache busting, but main resources (which are usually HTML documents) can't be.

Caching main resources is difficult because, using just standard directives from the HTTP Caching specification, there's no way to actively delete cache contents when content is updated on the server.

However, it is possible by deploying a managed cache such as a CDN or service worker.

For example, a CDN that allows cache purging via an API or dashboard operation would allow for a more aggressive caching strategy by storing the main resource and explicitly purging the relevant cache only when an update occurs on the server.

A service worker could do the same if it could delete the contents in the Cache API when an update occurs on the server.

For more information, see the documentation for your CDN, and consult the service worker documentation.

See also

22.9. Naive Bayes Open the notebook in SageMaker Studio Lab

Assigned source reading · Aston Zhang, Zachary C. Lipton, Mu Li and Alexander J. Smola

Dive into Deep Learning — the authors and contributors; text CC BY-SA 4.0; accompanying code under its separately stated license.

Original source · Creative Commons Attribution-ShareAlike 4.0 · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.

22.9. Naive Bayes
Open the notebook in SageMaker Studio Lab

Throughout the previous sections, we learned about the theory of probability and random variables. To put this theory to work, let’s introduce the naive Bayes classifier. This uses nothing but probabilistic fundamentals to allow us to perform classification of digits.

Learning is all about making assumptions. If we want to classify a new data example that we have never seen before we have to make some assumptions about which data examples are similar to each other. The naive Bayes classifier, a popular and remarkably clear algorithm, assumes all features are independent from each other to simplify the computation. In this section, we will apply this model to recognize characters in images.

%matplotlib inline
import math
import torch
import torchvision
from d2l import torch as d2l

d2l.use_svg_display()

22.9.1. Optical Character Recognition

MNIST (LeCun et al., 1998) is one of widely used datasets. It contains 60,000 images for training and 10,000 images for validation. Each image contains a handwritten digit from 0 to 9. The task is classifying each image into the corresponding digit.

Gluon provides a MNIST class in the data.vision module to automatically retrieve the dataset from the Internet. Subsequently, Gluon will use the already-downloaded local copy. We specify whether we are requesting the training set or the test set by setting the value of the parameter train to True or False, respectively. Each image is a grayscale image with both width and height of \(28\) with shape (\(28\),\(28\),\(1\)). We use a customized transformation to remove the last channel dimension. In addition, the dataset represents each pixel by an unsigned \(8\)-bit integer. We quantize them into binary features to simplify the problem.

data_transform = torchvision.transforms.Compose([
    torchvision.transforms.ToTensor(),
    lambda x: torch.floor(x * 255 / 128).squeeze(dim=0)
])

mnist_train = torchvision.datasets.MNIST(
    root='./temp', train=True, transform=data_transform, download=True)
mnist_test = torchvision.datasets.MNIST(
    root='./temp', train=False, transform=data_transform, download=True)
Downloading http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz
Downloading http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz to ./temp/MNIST/raw/train-images-idx3-ubyte.gz
100%|██████████| 9912422/9912422 [00:00<00:00, 115752065.81it/s]
Extracting ./temp/MNIST/raw/train-images-idx3-ubyte.gz to ./temp/MNIST/raw

Downloading http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz
Downloading http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz to ./temp/MNIST/raw/train-labels-idx1-ubyte.gz
100%|██████████| 28881/28881 [00:00<00:00, 5234904.66it/s]
Extracting ./temp/MNIST/raw/train-labels-idx1-ubyte.gz to ./temp/MNIST/raw

Downloading http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz
Downloading http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz to ./temp/MNIST/raw/t10k-images-idx3-ubyte.gz
100%|██████████| 1648877/1648877 [00:00<00:00, 43715298.68it/s]Extracting ./temp/MNIST/raw/t10k-images-idx3-ubyte.gz to ./temp/MNIST/raw


Downloading http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz
Downloading http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz to ./temp/MNIST/raw/t10k-labels-idx1-ubyte.gz
100%|██████████| 4542/4542 [00:00<00:00, 21501725.47it/s]
Extracting ./temp/MNIST/raw/t10k-labels-idx1-ubyte.gz to ./temp/MNIST/raw

We can access a particular example, which contains the image and the corresponding label.

image, label = mnist_train[2]
image.shape, label
(torch.Size([28, 28]), 4)

Our example, stored here in the variable image, corresponds to an image with a height and width of \(28\) pixels.

image.shape, image.dtype
(torch.Size([28, 28]), torch.float32)

Our code stores the label of each image as a scalar. Its type is a \(32\)-bit integer.

label, type(label)
(4, int)

We can also access multiple examples at the same time.

images = torch.stack([mnist_train[i][0] for i in range(10, 38)], dim=0)
labels = torch.tensor([mnist_train[i][1] for i in range(10, 38)])
images.shape, labels.shape
(torch.Size([28, 28, 28]), torch.Size([28]))

Let’s visualize these examples.

d2l.show_images(images, 2, 9);
../_images/output_naive-bayes_6e475d_75_0.svg

22.9.2. The Probabilistic Model for Classification

In a classification task, we map an example into a category. Here an example is a grayscale \(28\times 28\) image, and a category is a digit. (Refer to Section 4.1 for a more detailed explanation.) One natural way to express the classification task is via the probabilistic question: what is the most likely label given the features (i.e., image pixels)? Denote by \(\mathbf x\in\mathbb R^d\) the features of the example and \(y\in\mathbb R\) the label. Here features are image pixels, where we can reshape a \(2\)-dimensional image to a vector so that \(d=28^2=784\), and labels are digits. The probability of the label given the features is \(p(y \mid \mathbf{x})\). If we are able to compute these probabilities, which are \(p(y \mid \mathbf{x})\) for \(y=0, \ldots,9\) in our example, then the classifier will output the prediction \(\hat{y}\) given by the expression:

(22.9.1)\[\hat{y} = \mathrm{argmax} \> p(y \mid \mathbf{x}).\]

Unfortunately, this requires that we estimate \(p(y \mid \mathbf{x})\) for every value of \(\mathbf{x} = x_1, ..., x_d\). Imagine that each feature could take one of \(2\) values. For example, the feature \(x_1 = 1\) might signify that the word apple appears in a given document and \(x_1 = 0\) would signify that it does not. If we had \(30\) such binary features, that would mean that we need to be prepared to classify any of \(2^{30}\) (over 1 billion!) possible values of the input vector \(\mathbf{x}\).

Moreover, where is the learning? If we need to see every single possible example in order to predict the corresponding label then we are not really learning a pattern but just memorizing the dataset.

22.9.3. The Naive Bayes Classifier

Fortunately, by making some assumptions about conditional independence, we can introduce some inductive bias and build a model capable of generalizing from a comparatively modest selection of training examples. To begin, let’s use Bayes theorem, to express the classifier as

(22.9.2)\[\hat{y} = \mathrm{argmax}_y \> p(y \mid \mathbf{x}) = \mathrm{argmax}_y \> \frac{p( \mathbf{x} \mid y) p(y)}{p(\mathbf{x})}.\]

Note that the denominator is the normalizing term \(p(\mathbf{x})\) which does not depend on the value of the label \(y\). As a result, we only need to worry about comparing the numerator across different values of \(y\). Even if calculating the denominator turned out to be intractable, we could get away with ignoring it, so long as we could evaluate the numerator. Fortunately, even if we wanted to recover the normalizing constant, we could. We can always recover the normalization term since \(\sum_y p(y \mid \mathbf{x}) = 1\).

Now, let’s focus on \(p( \mathbf{x} \mid y)\). Using the chain rule of probability, we can express the term \(p( \mathbf{x} \mid y)\) as

(22.9.3)\[p(x_1 \mid y) \cdot p(x_2 \mid x_1, y) \cdot ... \cdot p( x_d \mid x_1, ..., x_{d-1}, y).\]

By itself, this expression does not get us any further. We still must estimate roughly \(2^d\) parameters. However, if we assume that the features are conditionally independent of each other, given the label, then suddenly we are in much better shape, as this term simplifies to \(\prod_i p(x_i \mid y)\), giving us the predictor

(22.9.4)\[\hat{y} = \mathrm{argmax}_y \> \prod_{i=1}^d p(x_i \mid y) p(y).\]

If we can estimate \(p(x_i=1 \mid y)\) for every \(i\) and \(y\), and save its value in \(P_{xy}[i, y]\), here \(P_{xy}\) is a \(d\times n\) matrix with \(n\) being the number of classes and \(y\in\{1, \ldots, n\}\), then we can also use this to estimate \(p(x_i = 0 \mid y)\), i.e.,

(22.9.5)\[\begin{split}p(x_i = t_i \mid y) = \begin{cases} P_{xy}[i, y] & \textrm{for } t_i=1 ;\\ 1 - P_{xy}[i, y] & \textrm{for } t_i = 0 . \end{cases}\end{split}\]

In addition, we estimate \(p(y)\) for every \(y\) and save it in \(P_y[y]\), with \(P_y\) a \(n\)-length vector. Then, for any new example \(\mathbf t = (t_1, t_2, \ldots, t_d)\), we could compute

(22.9.6)\[\begin{split}\begin{aligned}\hat{y} &= \mathrm{argmax}_ y \ p(y)\prod_{i=1}^d p(x_t = t_i \mid y) \\ &= \mathrm{argmax}_y \ P_y[y]\prod_{i=1}^d \ P_{xy}[i, y]^{t_i}\, \left(1 - P_{xy}[i, y]\right)^{1-t_i}\end{aligned}\end{split}\]

for any \(y\). So our assumption of conditional independence has taken the complexity of our model from an exponential dependence on the number of features \(\mathcal{O}(2^dn)\) to a linear dependence, which is \(\mathcal{O}(dn)\).

22.9.4. Training

The problem now is that we do not know \(P_{xy}\) and \(P_y\). So we need to estimate their values given some training data first. This is training the model. Estimating \(P_y\) is not too hard. Since we are only dealing with \(10\) classes, we may count the number of occurrences \(n_y\) for each of the digits and divide it by the total amount of data \(n\). For instance, if digit 8 occurs \(n_8 = 5,800\) times and we have a total of \(n = 60,000\) images, the probability estimate is \(p(y=8) = 0.0967\).

X = torch.stack([mnist_train[i][0] for i in range(len(mnist_train))], dim=0)
Y = torch.tensor([mnist_train[i][1] for i in range(len(mnist_train))])

n_y = torch.zeros(10)
for y in range(10):
    n_y[y] = (Y == y).sum()
P_y = n_y / n_y.sum()
P_y
tensor([0.0987, 0.1124, 0.0993, 0.1022, 0.0974, 0.0904, 0.0986, 0.1044, 0.0975,
        0.0992])

Now on to slightly more difficult things \(P_{xy}\). Since we picked black and white images, \(p(x_i \mid y)\) denotes the probability that pixel \(i\) is switched on for class \(y\). Just like before we can go and count the number of times \(n_{iy}\) such that an event occurs and divide it by the total number of occurrences of \(y\), i.e., \(n_y\). But there is something slightly troubling: certain pixels may never be black (e.g., for well cropped images the corner pixels might always be white). A convenient way for statisticians to deal with this problem is to add pseudo counts to all occurrences. Hence, rather than \(n_{iy}\) we use \(n_{iy}+1\) and instead of \(n_y\) we use \(n_{y}+2\) (since there are two possible values pixel \(i\) can take - it can either be black or white). This is also called Laplace Smoothing. It may seem ad-hoc, however it can be motivated from a Bayesian point-of-view by a Beta-binomial model.

n_x = torch.zeros((10, 28, 28))
for y in range(10):
    n_x[y] = torch.tensor(X.numpy()[Y.numpy() == y].sum(axis=0))
P_xy = (n_x + 1) / (n_y + 2).reshape(10, 1, 1)

d2l.show_images(P_xy, 2, 5);
../_images/output_naive-bayes_6e475d_99_0.svg

By visualizing these \(10\times 28\times 28\) probabilities (for each pixel for each class) we could get some mean looking digits.

Now we can use (22.9.6) to predict a new image. Given \(\mathbf x\), the following functions computes \(p(\mathbf x \mid y)p(y)\) for every \(y\).

def bayes_pred(x):
    x = x.unsqueeze(0)  # (28, 28) -> (1, 28, 28)
    p_xy = P_xy * x + (1 - P_xy)*(1 - x)
    p_xy = p_xy.reshape(10, -1).prod(dim=1)  # p(x|y)
    return p_xy * P_y

image, label = mnist_test[0]
bayes_pred(image)
tensor([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])

This went horribly wrong! To find out why, let’s look at the per pixel probabilities. They are typically numbers between \(0.001\) and \(1\). We are multiplying \(784\) of them. At this point it is worth mentioning that we are calculating these numbers on a computer, hence with a fixed range for the exponent. What happens is that we experience numerical underflow, i.e., multiplying all the small numbers leads to something even smaller until it is rounded down to zero. We discussed this as a theoretical issue in Section 22.7, but we see the phenomena clearly here in practice.

As discussed in that section, we fix this by use the fact that \(\log a b = \log a + \log b\), i.e., we switch to summing logarithms. Even if both \(a\) and \(b\) are small numbers, the logarithm values should be in a proper range.

a = 0.1
print('underflow:', a**784)
print('logarithm is normal:', 784*math.log(a))
underflow: 0.0
logarithm is normal: -1805.2267129073316

Since the logarithm is an increasing function, we can rewrite (22.9.6) as

(22.9.7)\[\hat{y} = \mathrm{argmax}_y \ \log P_y[y] + \sum_{i=1}^d \Big[t_i\log P_{xy}[x_i, y] + (1-t_i) \log (1 - P_{xy}[x_i, y]) \Big].\]

We can implement the following stable version:

log_P_xy = torch.log(P_xy)
log_P_xy_neg = torch.log(1 - P_xy)
log_P_y = torch.log(P_y)

def bayes_pred_stable(x):
    x = x.unsqueeze(0)  # (28, 28) -> (1, 28, 28)
    p_xy = log_P_xy * x + log_P_xy_neg * (1 - x)
    p_xy = p_xy.reshape(10, -1).sum(axis=1)  # p(x|y)
    return p_xy + log_P_y

py = bayes_pred_stable(image)
py
tensor([-268.9725, -301.7044, -245.1951, -218.8738, -193.4570, -206.0909,
        -292.5226, -114.6257, -220.3313, -163.1784])

We may now check if the prediction is correct.

py.argmax(dim=0) == label
tensor(True)

If we now predict a few validation examples, we can see the Bayes classifier works pretty well.

def predict(X):
    return [bayes_pred_stable(x).argmax(dim=0).type(torch.int32).item()
            for x in X]

X = torch.stack([mnist_test[i][0] for i in range(18)], dim=0)
y = torch.tensor([mnist_test[i][1] for i in range(18)])
preds = predict(X)
d2l.show_images(X, 2, 9, titles=[str(d) for d in preds]);
../_images/output_naive-bayes_6e475d_159_0.svg

Finally, let’s compute the overall accuracy of the classifier.

X = torch.stack([mnist_test[i][0] for i in range(len(mnist_test))], dim=0)
y = torch.tensor([mnist_test[i][1] for i in range(len(mnist_test))])
preds = torch.tensor(predict(X), dtype=torch.int32)
float((preds == y).sum()) / len(y)  # Validation accuracy
0.8427

Modern deep networks achieve error rates of less than \(0.01\). The relatively poor performance is due to the incorrect statistical assumptions that we made in our model: we assumed that each and every pixel are independently generated, depending only on the label. This is clearly not how humans write digits, and this wrong assumption led to the downfall of our overly naive (Bayes) classifier.

22.9.5. Summary

  • Using Bayes’ rule, a classifier can be made by assuming all observed features are independent.

  • This classifier can be trained on a dataset by counting the number of occurrences of combinations of labels and pixel values.

  • This classifier was the gold standard for decades for tasks such as spam detection.

22.9.6. Exercises

  1. Consider the dataset \([[0,0], [0,1], [1,0], [1,1]]\) with labels given by the XOR of the two elements \([0,1,1,0]\). What are the probabilities for a Naive Bayes classifier built on this dataset. Does it successfully classify our points? If not, what assumptions are violated?

  2. Suppose that we did not use Laplace smoothing when estimating probabilities and a data example arrived at testing time which contained a value never observed in training. What would the model output?

  3. The naive Bayes classifier is a specific example of a Bayesian network, where the dependence of random variables are encoded with a graph structure. While the full theory is beyond the scope of this section (see Koller and Friedman (2009) for full details), explain why allowing explicit dependence between the two input variables in the XOR model allows for the creation of a successful classifier.

5.1. Multilayer Perceptrons Open the notebook in SageMaker Studio Lab

Assigned source reading · Aston Zhang, Zachary C. Lipton, Mu Li and Alexander J. Smola

Dive into Deep Learning — the authors and contributors; text CC BY-SA 4.0; accompanying code under its separately stated license.

Original source · Creative Commons Attribution-ShareAlike 4.0 · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.

5.1. Multilayer Perceptrons
Open the notebook in SageMaker Studio Lab

In Section 4.1, we introduced softmax regression, implementing the algorithm from scratch (Section 4.4) and using high-level APIs (Section 4.5). This allowed us to train classifiers capable of recognizing 10 categories of clothing from low-resolution images. Along the way, we learned how to wrangle data, coerce our outputs into a valid probability distribution, apply an appropriate loss function, and minimize it with respect to our model’s parameters. Now that we have mastered these mechanics in the context of simple linear models, we can launch our exploration of deep neural networks, the comparatively rich class of models with which this book is primarily concerned.

%matplotlib inline
import torch
from d2l import torch as d2l

5.1.1. Hidden Layers

We described affine transformations in Section 3.1.1.1 as linear transformations with added bias. To begin, recall the model architecture corresponding to our softmax regression example, illustrated in Fig. 4.1.1. This model maps inputs directly to outputs via a single affine transformation, followed by a softmax operation. If our labels truly were related to the input data by a simple affine transformation, then this approach would be sufficient. However, linearity (in affine transformations) is a strong assumption.

5.1.1.1. Limitations of Linear Models

For example, linearity implies the weaker assumption of monotonicity, i.e., that any increase in our feature must either always cause an increase in our model’s output (if the corresponding weight is positive), or always cause a decrease in our model’s output (if the corresponding weight is negative). Sometimes that makes sense. For example, if we were trying to predict whether an individual will repay a loan, we might reasonably assume that all other things being equal, an applicant with a higher income would always be more likely to repay than one with a lower income. While monotonic, this relationship likely is not linearly associated with the probability of repayment. An increase in income from $0 to $50,000 likely corresponds to a bigger increase in likelihood of repayment than an increase from $1 million to $1.05 million. One way to handle this might be to postprocess our outcome such that linearity becomes more plausible, by using the logistic map (and thus the logarithm of the probability of outcome).

Note that we can easily come up with examples that violate monotonicity. Say for example that we want to predict health as a function of body temperature. For individuals with a normal body temperature above 37°C (98.6°F), higher temperatures indicate greater risk. However, if the body temperatures drops below 37°C, lower temperatures indicate greater risk! Again, we might resolve the problem with some clever preprocessing, such as using the distance from 37°C as a feature.

But what about classifying images of cats and dogs? Should increasing the intensity of the pixel at location (13, 17) always increase (or always decrease) the likelihood that the image depicts a dog? Reliance on a linear model corresponds to the implicit assumption that the only requirement for differentiating cats and dogs is to assess the brightness of individual pixels. This approach is doomed to fail in a world where inverting an image preserves the category.

And yet despite the apparent absurdity of linearity here, as compared with our previous examples, it is less obvious that we could address the problem with a simple preprocessing fix. That is, because the significance of any pixel depends in complex ways on its context (the values of the surrounding pixels). While there might exist a representation of our data that would take into account the relevant interactions among our features, on top of which a linear model would be suitable, we simply do not know how to calculate it by hand. With deep neural networks, we used observational data to jointly learn both a representation via hidden layers and a linear predictor that acts upon that representation.

This problem of nonlinearity has been studied for at least a century (Fisher, 1925). For instance, decision trees in their most basic form use a sequence of binary decisions to decide upon class membership (Quinlan, 1993). Likewise, kernel methods have been used for many decades to model nonlinear dependencies (Aronszajn, 1950). This has found its way into nonparametric spline models (Wahba, 1990) and kernel methods (Schölkopf and Smola, 2002). It is also something that the brain solves quite naturally. After all, neurons feed into other neurons which, in turn, feed into other neurons again (Ramón y Cajal and Azoulay, 1894). Consequently we have a sequence of relatively simple transformations.

5.1.1.2. Incorporating Hidden Layers

We can overcome the limitations of linear models by incorporating one or more hidden layers. The easiest way to do this is to stack many fully connected layers on top of one another. Each layer feeds into the layer above it, until we generate outputs. We can think of the first \(L-1\) layers as our representation and the final layer as our linear predictor. This architecture is commonly called a multilayer perceptron, often abbreviated as MLP (Fig. 5.1.1).

../_images/mlp.svg

Fig. 5.1.1 An MLP with a hidden layer of five hidden units.

This MLP has four inputs, three outputs, and its hidden layer contains five hidden units. Since the input layer does not involve any calculations, producing outputs with this network requires implementing the computations for both the hidden and output layers; thus, the number of layers in this MLP is two. Note that both layers are fully connected. Every input influences every neuron in the hidden layer, and each of these in turn influences every neuron in the output layer. Alas, we are not quite done yet.

5.1.1.3. From Linear to Nonlinear

As before, we denote by the matrix \(\mathbf{X} \in \mathbb{R}^{n \times d}\) a minibatch of \(n\) examples where each example has \(d\) inputs (features). For a one-hidden-layer MLP whose hidden layer has \(h\) hidden units, we denote by \(\mathbf{H} \in \mathbb{R}^{n \times h}\) the outputs of the hidden layer, which are hidden representations. Since the hidden and output layers are both fully connected, we have hidden-layer weights \(\mathbf{W}^{(1)} \in \mathbb{R}^{d \times h}\) and biases \(\mathbf{b}^{(1)} \in \mathbb{R}^{1 \times h}\) and output-layer weights \(\mathbf{W}^{(2)} \in \mathbb{R}^{h \times q}\) and biases \(\mathbf{b}^{(2)} \in \mathbb{R}^{1 \times q}\). This allows us to calculate the outputs \(\mathbf{O} \in \mathbb{R}^{n \times q}\) of the one-hidden-layer MLP as follows:

(5.1.1)\[\begin{split}\begin{aligned} \mathbf{H} & = \mathbf{X} \mathbf{W}^{(1)} + \mathbf{b}^{(1)}, \\ \mathbf{O} & = \mathbf{H}\mathbf{W}^{(2)} + \mathbf{b}^{(2)}. \end{aligned}\end{split}\]

Note that after adding the hidden layer, our model now requires us to track and update additional sets of parameters. So what have we gained in exchange? You might be surprised to find out that—in the model defined above—we gain nothing for our troubles! The reason is plain. The hidden units above are given by an affine function of the inputs, and the outputs (pre-softmax) are just an affine function of the hidden units. An affine function of an affine function is itself an affine function. Moreover, our linear model was already capable of representing any affine function.

To see this formally we can just collapse out the hidden layer in the above definition, yielding an equivalent single-layer model with parameters \(\mathbf{W} = \mathbf{W}^{(1)}\mathbf{W}^{(2)}\) and \(\mathbf{b} = \mathbf{b}^{(1)} \mathbf{W}^{(2)} + \mathbf{b}^{(2)}\):

(5.1.2)\[\mathbf{O} = (\mathbf{X} \mathbf{W}^{(1)} + \mathbf{b}^{(1)})\mathbf{W}^{(2)} + \mathbf{b}^{(2)} = \mathbf{X} \mathbf{W}^{(1)}\mathbf{W}^{(2)} + \mathbf{b}^{(1)} \mathbf{W}^{(2)} + \mathbf{b}^{(2)} = \mathbf{X} \mathbf{W} + \mathbf{b}.\]

In order to realize the potential of multilayer architectures, we need one more key ingredient: a nonlinear activation function \(\sigma\) to be applied to each hidden unit following the affine transformation. For instance, a popular choice is the ReLU (rectified linear unit) activation function (Nair and Hinton, 2010) \(\sigma(x) = \mathrm{max}(0, x)\) operating on its arguments elementwise. The outputs of activation functions \(\sigma(\cdot)\) are called activations. In general, with activation functions in place, it is no longer possible to collapse our MLP into a linear model:

(5.1.3)\[\begin{split}\begin{aligned} \mathbf{H} & = \sigma(\mathbf{X} \mathbf{W}^{(1)} + \mathbf{b}^{(1)}), \\ \mathbf{O} & = \mathbf{H}\mathbf{W}^{(2)} + \mathbf{b}^{(2)}.\\ \end{aligned}\end{split}\]

Since each row in \(\mathbf{X}\) corresponds to an example in the minibatch, with some abuse of notation, we define the nonlinearity \(\sigma\) to apply to its inputs in a rowwise fashion, i.e., one example at a time. Note that we used the same notation for softmax when we denoted a rowwise operation in Section 4.1.1.3. Quite frequently the activation functions we use apply not merely rowwise but elementwise. That means that after computing the linear portion of the layer, we can calculate each activation without looking at the values taken by the other hidden units.

To build more general MLPs, we can continue stacking such hidden layers, e.g., \(\mathbf{H}^{(1)} = \sigma_1(\mathbf{X} \mathbf{W}^{(1)} + \mathbf{b}^{(1)})\) and \(\mathbf{H}^{(2)} = \sigma_2(\mathbf{H}^{(1)} \mathbf{W}^{(2)} + \mathbf{b}^{(2)})\), one atop another, yielding ever more expressive models.

5.1.1.4. Universal Approximators

We know that the brain is capable of very sophisticated statistical analysis. As such, it is worth asking, just how powerful a deep network could be. This question has been answered multiple times, e.g., in Cybenko (1989) in the context of MLPs, and in Micchelli (1984) in the context of reproducing kernel Hilbert spaces in a way that could be seen as radial basis function (RBF) networks with a single hidden layer. These (and related results) suggest that even with a single-hidden-layer network, given enough nodes (possibly absurdly many), and the right set of weights, we can model any function. Actually learning that function is the hard part, though. You might think of your neural network as being a bit like the C programming language. The language, like any other modern language, is capable of expressing any computable program. But actually coming up with a program that meets your specifications is the hard part.

Moreover, just because a single-hidden-layer network can learn any function does not mean that you should try to solve all of your problems with one. In fact, in this case kernel methods are way more effective, since they are capable of solving the problem exactly even in infinite dimensional spaces (Kimeldorf and Wahba, 1971, Schölkopf et al., 2001). In fact, we can approximate many functions much more compactly by using deeper (rather than wider) networks (Simonyan and Zisserman, 2014). We will touch upon more rigorous arguments in subsequent chapters.

5.1.2. Activation Functions

Activation functions decide whether a neuron should be activated or not by calculating the weighted sum and further adding bias to it. They are differentiable operators for transforming input signals to outputs, while most of them add nonlinearity. Because activation functions are fundamental to deep learning, let’s briefly survey some common ones.

5.1.2.1. ReLU Function

The most popular choice, due to both simplicity of implementation and its good performance on a variety of predictive tasks, is the rectified linear unit (ReLU) (Nair and Hinton, 2010). ReLU provides a very simple nonlinear transformation. Given an element \(x\), the function is defined as the maximum of that element and \(0\):

(5.1.4)\[\operatorname{ReLU}(x) = \max(x, 0).\]

Informally, the ReLU function retains only positive elements and discards all negative elements by setting the corresponding activations to 0. To gain some intuition, we can plot the function. As you can see, the activation function is piecewise linear.

x = torch.arange(-8.0, 8.0, 0.1, requires_grad=True)
y = torch.relu(x)
d2l.plot(x.detach(), y.detach(), 'x', 'relu(x)', figsize=(5, 2.5))
../_images/output_mlp_76f463_18_0.svg

When the input is negative, the derivative of the ReLU function is 0, and when the input is positive, the derivative of the ReLU function is 1. Note that the ReLU function is not differentiable when the input takes value precisely equal to 0. In these cases, we default to the left-hand-side derivative and say that the derivative is 0 when the input is 0. We can get away with this because the input may never actually be zero (mathematicians would say that it is nondifferentiable on a set of measure zero). There is an old adage that if subtle boundary conditions matter, we are probably doing (real) mathematics, not engineering. That conventional wisdom may apply here, or at least, the fact that we are not performing constrained optimization (Mangasarian, 1965, Rockafellar, 1970). We plot the derivative of the ReLU function below.

y.backward(torch.ones_like(x), retain_graph=True)
d2l.plot(x.detach(), x.grad, 'x', 'grad of relu', figsize=(5, 2.5))
../_images/output_mlp_76f463_33_0.svg

The reason for using ReLU is that its derivatives are particularly well behaved: either they vanish or they just let the argument through. This makes optimization better behaved and it mitigated the well-documented problem of vanishing gradients that plagued previous versions of neural networks (more on this later).

Note that there are many variants to the ReLU function, including the parametrized ReLU (pReLU) function (He et al., 2015). This variation adds a linear term to ReLU, so some information still gets through, even when the argument is negative:

(5.1.5)\[\operatorname{pReLU}(x) = \max(0, x) + \alpha \min(0, x).\]

5.1.2.2. Sigmoid Function

The sigmoid function transforms those inputs whose values lie in the domain \(\mathbb{R}\), to outputs that lie on the interval (0, 1). For that reason, the sigmoid is often called a squashing function: it squashes any input in the range (-inf, inf) to some value in the range (0, 1):

(5.1.6)\[\operatorname{sigmoid}(x) = \frac{1}{1 + \exp(-x)}.\]

In the earliest neural networks, scientists were interested in modeling biological neurons that either fire or do not fire. Thus the pioneers of this field, going all the way back to McCulloch and Pitts, the inventors of the artificial neuron, focused on thresholding units (McCulloch and Pitts, 1943). A thresholding activation takes value 0 when its input is below some threshold and value 1 when the input exceeds the threshold.

When attention shifted to gradient-based learning, the sigmoid function was a natural choice because it is a smooth, differentiable approximation to a thresholding unit. Sigmoids are still widely used as activation functions on the output units when we want to interpret the outputs as probabilities for binary classification problems: you can think of the sigmoid as a special case of the softmax. However, the sigmoid has largely been replaced by the simpler and more easily trainable ReLU for most use in hidden layers. Much of this has to do with the fact that the sigmoid poses challenges for optimization (LeCun et al., 1998) since its gradient vanishes for large positive and negative arguments. This can lead to plateaus that are difficult to escape from. Nonetheless sigmoids are important. In later chapters (e.g., Section 10.1) on recurrent neural networks, we will describe architectures that leverage sigmoid units to control the flow of information across time.

Below, we plot the sigmoid function. Note that when the input is close to 0, the sigmoid function approaches a linear transformation.

y = torch.sigmoid(x)
d2l.plot(x.detach(), y.detach(), 'x', 'sigmoid(x)', figsize=(5, 2.5))
../_images/output_mlp_76f463_48_0.svg

The derivative of the sigmoid function is given by the following equation:

(5.1.7)\[\frac{d}{dx} \operatorname{sigmoid}(x) = \frac{\exp(-x)}{(1 + \exp(-x))^2} = \operatorname{sigmoid}(x)\left(1-\operatorname{sigmoid}(x)\right).\]

The derivative of the sigmoid function is plotted below. Note that when the input is 0, the derivative of the sigmoid function reaches a maximum of 0.25. As the input diverges from 0 in either direction, the derivative approaches 0.

# Clear out previous gradients
x.grad.data.zero_()
y.backward(torch.ones_like(x),retain_graph=True)
d2l.plot(x.detach(), x.grad, 'x', 'grad of sigmoid', figsize=(5, 2.5))
../_images/output_mlp_76f463_63_0.svg

5.1.2.3. Tanh Function

Like the sigmoid function, the tanh (hyperbolic tangent) function also squashes its inputs, transforming them into elements on the interval between \(-1\) and \(1\):

(5.1.8)\[\operatorname{tanh}(x) = \frac{1 - \exp(-2x)}{1 + \exp(-2x)}.\]

We plot the tanh function below. Note that as input nears 0, the tanh function approaches a linear transformation. Although the shape of the function is similar to that of the sigmoid function, the tanh function exhibits point symmetry about the origin of the coordinate system (Kalman and Kwasny, 1992).

y = torch.tanh(x)
d2l.plot(x.detach(), y.detach(), 'x', 'tanh(x)', figsize=(5, 2.5))
../_images/output_mlp_76f463_78_0.svg

The derivative of the tanh function is:

(5.1.9)\[\frac{d}{dx} \operatorname{tanh}(x) = 1 - \operatorname{tanh}^2(x).\]

It is plotted below. As the input nears 0, the derivative of the tanh function approaches a maximum of 1. And as we saw with the sigmoid function, as input moves away from 0 in either direction, the derivative of the tanh function approaches 0.

# Clear out previous gradients
x.grad.data.zero_()
y.backward(torch.ones_like(x),retain_graph=True)
d2l.plot(x.detach(), x.grad, 'x', 'grad of tanh', figsize=(5, 2.5))
../_images/output_mlp_76f463_93_0.svg

5.1.3. Summary and Discussion

We now know how to incorporate nonlinearities to build expressive multilayer neural network architectures. As a side note, your knowledge already puts you in command of a similar toolkit to a practitioner circa 1990. In some ways, you have an advantage over anyone working back then, because you can leverage powerful open-source deep learning frameworks to build models rapidly, using only a few lines of code. Previously, training these networks required researchers to code up layers and derivatives explicitly in C, Fortran, or even Lisp (in the case of LeNet).

A secondary benefit is that ReLU is significantly more amenable to optimization than the sigmoid or the tanh function. One could argue that this was one of the key innovations that helped the resurgence of deep learning over the past decade. Note, though, that research in activation functions has not stopped. For instance, the GELU (Gaussian error linear unit) activation function \(x \Phi(x)\) by Hendrycks and Gimpel (2016) (\(\Phi(x)\) is the standard Gaussian cumulative distribution function) and the Swish activation function \(\sigma(x) = x \operatorname{sigmoid}(\beta x)\) as proposed in Ramachandran et al. (2017) can yield better accuracy in many cases.

5.1.4. Exercises

  1. Show that adding layers to a linear deep network, i.e., a network without nonlinearity \(\sigma\) can never increase the expressive power of the network. Give an example where it actively reduces it.

  2. Compute the derivative of the pReLU activation function.

  3. Compute the derivative of the Swish activation function \(x \operatorname{sigmoid}(\beta x)\).

  4. Show that an MLP using only ReLU (or pReLU) constructs a continuous piecewise linear function.

  5. Sigmoid and tanh are very similar.

    1. Show that \(\operatorname{tanh}(x) + 1 = 2 \operatorname{sigmoid}(2x)\).

    2. Prove that the function classes parametrized by both nonlinearities are identical. Hint: affine layers have bias terms, too.

  6. Assume that we have a nonlinearity that applies to one minibatch at a time, such as the batch normalization (Ioffe and Szegedy, 2015). What kinds of problems do you expect this to cause?

  7. Provide an example where the gradients vanish for the sigmoid activation function.

1.10. Decision Trees

Assigned source reading · The scikit-learn developers

Copyright (c) 2007–2026 The scikit-learn developers. All rights reserved.

Original source · BSD 3-Clause License · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.

Full license and notices
BSD 3-Clause License

Copyright (c) 2007-2026 The scikit-learn developers.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

* Neither the name of the copyright holder nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

1.10. Decision Trees

Decision Trees (DTs) are a non-parametric supervised learning method used for classification and regression. The goal is to create a model that predicts the value of a target variable by learning simple decision rules inferred from the data features. A tree can be seen as a piecewise constant approximation.

For instance, in the example below, decision trees learn from data to approximate a sine curve with a set of if-then-else decision rules. The deeper the tree, the more complex the decision rules and the fitter the model.

../_images/sphx_glr_plot_tree_regression_001.png

Some advantages of decision trees are:

  • Simple to understand and to interpret. Trees can be visualized.

  • Requires little data preparation. Other techniques often require data normalization, dummy variables need to be created and blank values to be removed. Some tree and algorithm combinations support missing values.

  • The cost of using the tree (i.e., predicting data) is logarithmic in the number of data points used to train the tree.

  • Able to handle both numerical and categorical data. However, the scikit-learn implementation does not support categorical variables for now. Other techniques are usually specialized in analyzing datasets that have only one type of variable. See algorithms for more information.

  • Able to handle multi-output problems.

  • Uses a white box model. If a given situation is observable in a model, the explanation for the condition is easily explained by boolean logic. By contrast, in a black box model (e.g., in an artificial neural network), results may be more difficult to interpret.

  • Possible to validate a model using statistical tests. That makes it possible to account for the reliability of the model.

  • Performs well even if its assumptions are somewhat violated by the true model from which the data were generated.

The disadvantages of decision trees include:

  • Decision-tree learners can create over-complex trees that do not generalize the data well. This is called overfitting. Mechanisms such as pruning, setting the minimum number of samples required at a leaf node or setting the maximum depth of the tree are necessary to avoid this problem.

  • Decision trees can be unstable because small variations in the data might result in a completely different tree being generated. This problem is mitigated by using decision trees within an ensemble.

  • Predictions of decision trees are neither smooth nor continuous, but piecewise constant approximations as seen in the above figure. Therefore, they are not good at extrapolation.

  • The problem of learning an optimal decision tree is known to be NP-complete under several aspects of optimality and even for simple concepts. Consequently, practical decision-tree learning algorithms are based on heuristic algorithms such as the greedy algorithm where locally optimal decisions are made at each node. Such algorithms cannot guarantee to return the globally optimal decision tree. This can be mitigated by training multiple trees in an ensemble learner, where the features and samples are randomly sampled with replacement.

  • There are concepts that are hard to learn because decision trees do not express them easily, such as XOR, parity or multiplexer problems.

  • Decision tree learners create biased trees if some classes dominate. It is therefore recommended to balance the dataset prior to fitting with the decision tree.

1.10.1. Classification

DecisionTreeClassifier is a class capable of performing multi-class classification on a dataset.

As with other classifiers, DecisionTreeClassifier takes as input two arrays: an array X, sparse or dense, of shape (n_samples, n_features) holding the training samples, and an array Y of integer values, shape (n_samples,), holding the class labels for the training samples:

>>> from sklearn import tree
>>> X = [[0, 0], [1, 1]]
>>> Y = [0, 1]
>>> clf = tree.DecisionTreeClassifier()
>>> clf = clf.fit(X, Y)

After being fitted, the model can then be used to predict the class of samples:

>>> clf.predict([[2., 2.]])
array([1])

In case that there are multiple classes with the same and highest probability, the classifier will predict the class with the lowest index amongst those classes.

As an alternative to outputting a specific class, the probability of each class can be predicted, which is the fraction of training samples of the class in a leaf:

>>> clf.predict_proba([[2., 2.]])
array([[0., 1.]])

DecisionTreeClassifier is capable of both binary (where the labels are [-1, 1]) classification and multiclass (where the labels are [0, …, K-1]) classification.

Using the Iris dataset, we can construct a tree as follows:

>>> from sklearn.datasets import load_iris
>>> from sklearn import tree
>>> iris = load_iris()
>>> X, y = iris.data, iris.target
>>> clf = tree.DecisionTreeClassifier()
>>> clf = clf.fit(X, y)

Once trained, you can plot the tree with the plot_tree function:

>>> tree.plot_tree(clf)
[...]
../_images/sphx_glr_plot_iris_dtc_002.png
Alternative ways to export trees

We can also export the tree in Graphviz format using the export_graphviz exporter. If you use the conda package manager, the graphviz binaries and the python package can be installed with conda install python-graphviz.

Alternatively binaries for graphviz can be downloaded from the graphviz project homepage, and the Python wrapper installed from pypi with pip install graphviz.

Below is an example graphviz export of the above tree trained on the entire iris dataset; the results are saved in an output file iris.pdf:

>>> import graphviz
>>> dot_data = tree.export_graphviz(clf, out_file=None)
>>> graph = graphviz.Source(dot_data)
>>> graph.render("iris")

The export_graphviz exporter also supports a variety of aesthetic options, including coloring nodes by their class (or value for regression) and using explicit variable and class names if desired. Jupyter notebooks also render these plots inline automatically:

>>> dot_data = tree.export_graphviz(clf, out_file=None,
...                      feature_names=iris.feature_names,
...                      class_names=iris.target_names,
...                      filled=True, rounded=True,
...                      special_characters=True)
>>> graph = graphviz.Source(dot_data)
>>> graph
../_images/iris.svg
../_images/sphx_glr_plot_iris_dtc_001.png

Alternatively, the tree can also be exported in textual format with the function export_text. This method doesn’t require the installation of external libraries and is more compact:

>>> from sklearn.datasets import load_iris
>>> from sklearn.tree import DecisionTreeClassifier
>>> from sklearn.tree import export_text
>>> iris = load_iris()
>>> decision_tree = DecisionTreeClassifier(random_state=0, max_depth=2)
>>> decision_tree = decision_tree.fit(iris.data, iris.target)
>>> r = export_text(decision_tree, feature_names=iris['feature_names'])
>>> print(r)
|--- petal width (cm) <= 0.80
|   |--- class: 0
|--- petal width (cm) >  0.80
|   |--- petal width (cm) <= 1.75
|   |   |--- class: 1
|   |--- petal width (cm) >  1.75
|   |   |--- class: 2

Examples

1.10.2. Regression

../_images/sphx_glr_plot_tree_regression_001.png

Decision trees can also be applied to regression problems, using the DecisionTreeRegressor class.

As in the classification setting, the fit method will take as argument arrays X and y, only that in this case y is expected to have floating point values instead of integer values:

>>> from sklearn import tree
>>> X = [[0, 0], [2, 2]]
>>> y = [0.5, 2.5]
>>> clf = tree.DecisionTreeRegressor()
>>> clf = clf.fit(X, y)
>>> clf.predict([[1, 1]])
array([0.5])

Examples

1.10.3. Multi-output problems

A multi-output problem is a supervised learning problem with several outputs to predict, that is when Y is a 2d array of shape (n_samples, n_outputs).

When there is no correlation between the outputs, a very simple way to solve this kind of problem is to build n independent models, i.e. one for each output, and then to use those models to independently predict each one of the n outputs. However, because it is likely that the output values related to the same input are themselves correlated, an often better way is to build a single model capable of predicting simultaneously all n outputs. First, it requires lower training time since only a single estimator is built. Second, the generalization accuracy of the resulting estimator may often be increased.

With regard to decision trees, this strategy can readily be used to support multi-output problems. This requires the following changes:

  • Store n output values in leaves, instead of 1;

  • Use splitting criteria that compute the average reduction across all n outputs.

This module offers support for multi-output problems by implementing this strategy in both DecisionTreeClassifier and DecisionTreeRegressor. If a decision tree is fit on an output array Y of shape (n_samples, n_outputs) then the resulting estimator will:

  • Output n_output values upon predict;

  • Output a list of n_output arrays of class probabilities upon predict_proba.

The use of multi-output trees for regression is demonstrated in Decision Tree Regression. In this example, the input X is a single real value and the outputs Y are the sine and cosine of X.

../_images/sphx_glr_plot_tree_regression_002.png

The use of multi-output trees for classification is demonstrated in Face completion with a multi-output estimators. In this example, the inputs X are the pixels of the upper half of faces and the outputs Y are the pixels of the lower half of those faces.

../_images/sphx_glr_plot_multioutput_face_completion_001.png

Examples

References

1.10.4. Complexity

The following table shows the worst-case complexity estimates for a balanced binary tree:

Splitter

Total training cost

Total inference cost

“best”

\(\mathcal{O}(n_{features} \, n^2_{samples} \log(n_{samples}))\)

\(\mathcal{O}(\log(n_{samples}))\)

“random”

\(\mathcal{O}(n_{features} \, n^2_{samples})\)

\(\mathcal{O}(\log(n_{samples}))\)

In general, the training cost to construct a balanced binary tree at each node is

\[\mathcal{O}(n_{features}n_{samples}\log (n_{samples})) + \mathcal{O}(n_{features}n_{samples})\]

The first term is the cost of sorting \(n_{samples}\) repeated for \(n_{features}\). The second term is the linear scan over candidate split points to find the feature that offers the largest reduction in the impurity criterion. The latter is sub-leading for the greedy splitter strategy “best”, and is therefore typically discarded.

Regardless of the splitting strategy, after summing the cost over all internal nodes, the total complexity scales linearly with \(n_{nodes}=n_{leaves}-1\), which is \(\mathcal{O}(n_{samples})\) in the worst-case complexity, that is, when the tree is grown until each sample ends up in its own leaf.

Many implementations such as scikit-learn use efficient caching tricks to keep track of the general order of indices at each node such that the features do not need to be re-sorted at each node; hence, the time complexity of these implementations is just \(\mathcal{O}(n_{features}n_{samples}\log(n_{samples}))\) [1].

Inference cost is independent of the splitter strategy. It depends only on the tree depth, \(\mathcal{O}(\text{depth})\). In an approximately balanced binary tree, each split halves the data, and then the number of such halvings grows with the depth as powers of two. If this process continues until each sample is isolated in its own leaf, the resulting depth is \(\mathcal{O}(\log(n_{samples}))\).

References

1.10.5. Tips on practical use

  • Decision trees tend to overfit on data with a large number of features. Getting the right ratio of samples to number of features is important, since a tree with few samples in high dimensional space is very likely to overfit.

  • Consider performing dimensionality reduction (PCA, ICA, or Feature selection) beforehand to give your tree a better chance of finding features that are discriminative.

  • Understanding the decision tree structure will help in gaining more insights about how the decision tree makes predictions, which is important for understanding the important features in the data.

  • Visualize your tree as you are training by using the export function. Use max_depth=3 as an initial tree depth to get a feel for how the tree is fitting to your data, and then increase the depth.

  • Remember that the number of samples required to populate the tree doubles for each additional level the tree grows to. Use max_depth to control the size of the tree to prevent overfitting.

  • Use min_samples_split or min_samples_leaf to ensure that multiple samples inform every decision in the tree, by controlling which splits will be considered. A very small number will usually mean the tree will overfit, whereas a large number will prevent the tree from learning the data. Try min_samples_leaf=5 as an initial value. If the sample size varies greatly, a float number can be used as percentage in these two parameters. While min_samples_split can create arbitrarily small leaves, min_samples_leaf guarantees that each leaf has a minimum size, avoiding low-variance, over-fit leaf nodes in regression problems. For classification with few classes, min_samples_leaf=1 is often the best choice.

    Note that min_samples_split considers samples directly and independent of sample_weight, if provided (e.g. a node with m weighted samples is still treated as having exactly m samples). Consider min_weight_fraction_leaf or min_impurity_decrease if accounting for sample weights is required at splits.

  • Balance your dataset before training to prevent the tree from being biased toward the classes that are dominant. Class balancing can be done by sampling an equal number of samples from each class, or preferably by normalizing the sum of the sample weights (sample_weight) for each class to the same value. Also note that weight-based pre-pruning criteria, such as min_weight_fraction_leaf, will then be less biased toward dominant classes than criteria that are not aware of the sample weights, like min_samples_leaf.

  • If the samples are weighted, it will be easier to optimize the tree structure using weight-based pre-pruning criterion such as min_weight_fraction_leaf, which ensures that leaf nodes contain at least a fraction of the overall sum of the sample weights.

  • All decision trees use np.float32 arrays internally. If training data is not in this format, a copy of the dataset will be made.

  • If the input matrix X is very sparse, it is recommended to convert to sparse csc_matrix before calling fit and sparse csr_matrix before calling predict. Training time can be orders of magnitude faster for a sparse matrix input compared to a dense matrix when features have zero values in most of the samples.

1.10.6. Tree algorithms: ID3, C4.5, C5.0 and CART

What are all the various decision tree algorithms and how do they differ from each other? Which one is implemented in scikit-learn?

Various decision tree algorithms

ID3 (Iterative Dichotomiser 3) was developed in 1986 by Ross Quinlan. The algorithm creates a multiway tree, finding for each node (i.e. in a greedy manner) the categorical feature that will yield the largest information gain for categorical targets. Trees are grown to their maximum size and then a pruning step is usually applied to improve the ability of the tree to generalize to unseen data.

C4.5 is the successor to ID3 and removed the restriction that features must be categorical by dynamically defining a discrete attribute (based on numerical variables) that partitions the continuous attribute value into a discrete set of intervals. C4.5 converts the trained trees (i.e. the output of the ID3 algorithm) into sets of if-then rules. The accuracy of each rule is then evaluated to determine the order in which they should be applied. Pruning is done by removing a rule’s precondition if the accuracy of the rule improves without it.

C5.0 is Quinlan’s latest version release under a proprietary license. It uses less memory and builds smaller rulesets than C4.5 while being more accurate.

CART (Classification and Regression Trees) is very similar to C4.5, but it differs in that it supports numerical target variables (regression) and does not compute rule sets. CART constructs binary trees using the feature and threshold that yield the largest information gain at each node.

scikit-learn uses an optimized version of the CART algorithm; however, the scikit-learn implementation does not support categorical variables for now.

1.10.7. Mathematical formulation

Given training vectors \(x_i \in R^n\), i=1,…, l and a label vector \(y \in R^l\), a decision tree recursively partitions the feature space such that the samples with the same labels or similar target values are grouped together.

Let the data at node \(m\) be represented by \(Q_m\) with \(n_m\) samples. For each candidate split \(\theta = (j, t_m)\) consisting of a feature \(j\) and threshold \(t_m\), partition the data into \(Q_m^{left}(\theta)\) and \(Q_m^{right}(\theta)\) subsets

\[ \begin{align}\begin{aligned}Q_m^{left}(\theta) = \{(x, y) | x_j \leq t_m\}\\Q_m^{right}(\theta) = Q_m \setminus Q_m^{left}(\theta)\end{aligned}\end{align} \]

The quality of a candidate split of node \(m\) is then computed using an impurity function or loss function \(H()\), the choice of which depends on the task being solved (classification or regression)

\[G(Q_m, \theta) = \frac{n_m^{left}}{n_m} H(Q_m^{left}(\theta)) + \frac{n_m^{right}}{n_m} H(Q_m^{right}(\theta))\]

Select the parameters that minimises the impurity

\[\theta^* = \operatorname{argmin}_\theta G(Q_m, \theta)\]

The strategy to choose the split at each node is controlled by the splitter parameter:

  • With the best splitter (default, splitter='best'), \(\theta^*\) is found by performing a greedy exhaustive search over all available features and all possible thresholds \(t_m\) (i.e. midpoints between sorted, distinct feature values), selecting the pair that exactly minimizes \(G(Q_m, \theta)\).

  • With the random splitter (splitter='random'), \(\theta^*\) is found by sampling a single random candidate threshold for each available feature. This performs a stochastic approximation of the greedy search, effectively reducing computation time (see Complexity).

ExtraTreeClassifier and ExtraTreeRegressor use splitter='random' by default and share the same implementation as their corresponding decision tree estimators, apart from default parameter values.

After choosing the optimal split \(\theta^*\) at node \(m\), the same splitting procedure is then applied recursively to each partition \(Q_m^{left}(\theta^*)\) and \(Q_m^{right}(\theta^*)\) until a stopping condition is reached, such as:

  • the maximum allowable depth is reached (max_depth);

  • \(n_m\) is smaller than min_samples_split;

  • the impurity decrease for this split is smaller than min_impurity_decrease.

See the respective estimator docstring for other stopping conditions.

1.10.7.1. Classification criteria

If a target is a classification outcome taking on values 0,1,…,K-1, for node \(m\), let

\[p_{mk} = \frac{1}{n_m} \sum_{y \in Q_m} I(y = k)\]

be the proportion of class k observations in node \(m\). If \(m\) is a terminal node, predict_proba for this region is set to \(p_{mk}\). Common measures of impurity are the following.

Gini:

\[H(Q_m) = \sum_k p_{mk} (1 - p_{mk})\]

Log Loss or Entropy:

\[H(Q_m) = - \sum_k p_{mk} \log(p_{mk})\]
Shannon entropy

The entropy criterion computes the Shannon entropy of the possible classes. It takes the class frequencies of the training data points that reached a given leaf \(m\) as their probability. Using the Shannon entropy as tree node splitting criterion is equivalent to minimizing the log loss (also known as cross-entropy and multinomial deviance) between the true labels \(y_i\) and the probabilistic predictions \(T_k(x_i)\) of the tree model \(T\) for class \(k\).

To see this, first recall that the log loss of a tree model \(T\) computed on a dataset \(D\) is defined as follows:

\[\mathrm{LL}(D, T) = -\frac{1}{n} \sum_{(x_i, y_i) \in D} \sum_k I(y_i = k) \log(T_k(x_i))\]

where \(D\) is a training dataset of \(n\) pairs \((x_i, y_i)\).

In a classification tree, the predicted class probabilities within leaf nodes are constant, that is: for all \((x_i, y_i) \in Q_m\), one has: \(T_k(x_i) = p_{mk}\) for each class \(k\).

This property makes it possible to rewrite \(\mathrm{LL}(D, T)\) as the sum of the Shannon entropies computed for each leaf of \(T\) weighted by the number of training data points that reached each leaf:

\[\mathrm{LL}(D, T) = \sum_{m \in T} \frac{n_m}{n} H(Q_m)\]

1.10.7.2. Regression criteria

If the target is a continuous value, then for node \(m\), common criteria to minimize as for determining locations for future splits are Mean Squared Error (MSE or L2 error), Poisson deviance as well as Mean Absolute Error (MAE or L1 error). MSE and Poisson deviance both set the predicted value of terminal nodes to the learned mean value \(\bar{y}_m\) of the node whereas the MAE sets the predicted value of terminal nodes to the median \(median(y)_m\).

Mean Squared Error:

\[ \begin{align}\begin{aligned}\bar{y}_m = \frac{1}{n_m} \sum_{y \in Q_m} y\\H(Q_m) = \frac{1}{n_m} \sum_{y \in Q_m} (y - \bar{y}_m)^2\end{aligned}\end{align} \]

Mean Poisson deviance:

\[H(Q_m) = \frac{2}{n_m} \sum_{y \in Q_m} (y \log\frac{y}{\bar{y}_m} - y + \bar{y}_m)\]

Setting criterion="poisson" might be a good choice if your target is a count or a frequency (count per some unit). In any case, \(y >= 0\) is a necessary condition to use this criterion. For performance reasons the actual implementation minimizes the half mean poisson deviance, i.e. the mean poisson deviance divided by 2.

Mean Absolute Error:

\[ \begin{align}\begin{aligned}median(y)_m = \underset{y \in Q_m}{\mathrm{median}}(y)\\H(Q_m) = \frac{1}{n_m} \sum_{y \in Q_m} |y - median(y)_m|\end{aligned}\end{align} \]

Note that it is 3–6× slower to fit than the MSE criterion as of version 1.8.

1.10.8. Missing Values Support

DecisionTreeClassifier, DecisionTreeRegressor have built-in support for missing values using splitter='best', where the splits are determined in a greedy fashion. ExtraTreeClassifier, and ExtraTreeRegressor have built-in support for missing values for splitter='random', where the splits are determined randomly. For more details on how the splitter differs on non-missing values, see the Forest section.

First we will describe how DecisionTreeClassifier, DecisionTreeRegressor handle missing-values in the data.

For each potential threshold on the non-missing data, the splitter will evaluate the split with all the missing values going to the left node or the right node.

Decisions are made as follows:

  • By default when predicting, the samples with missing values are classified with the class used in the split found during training:

    >>> from sklearn.tree import DecisionTreeClassifier
    >>> import numpy as np
    
    >>> X = np.array([0, 1, 6, np.nan]).reshape(-1, 1)
    >>> y = [0, 0, 1, 1]
    
    >>> tree = DecisionTreeClassifier(random_state=0).fit(X, y)
    >>> tree.predict(X)
    array([0, 0, 1, 1])
    
  • If the criterion evaluation is the same for both nodes, then the tie for missing value at predict time is broken by going to the right node. The splitter also checks the split where all the missing values go to one child and non-missing values go to the other:

    >>> from sklearn.tree import DecisionTreeClassifier
    >>> import numpy as np
    
    >>> X = np.array([np.nan, -1, np.nan, 1]).reshape(-1, 1)
    >>> y = [0, 0, 1, 1]
    
    >>> tree = DecisionTreeClassifier(random_state=0, max_depth=1).fit(X, y)
    
    >>> X_test = np.array([np.nan]).reshape(-1, 1)
    >>> tree.predict(X_test)
    array([1])
    
  • If no missing values are seen during training for a given feature, then during prediction missing values are mapped to the child with the most samples:

    >>> from sklearn.tree import DecisionTreeClassifier
    >>> import numpy as np
    
    >>> X = np.array([0, 1, 2, 3]).reshape(-1, 1)
    >>> y = [0, 1, 1, 1]
    
    >>> tree = DecisionTreeClassifier(random_state=0).fit(X, y)
    
    >>> X_test = np.array([np.nan]).reshape(-1, 1)
    >>> tree.predict(X_test)
    array([1])
    

ExtraTreeClassifier, and ExtraTreeRegressor handle missing values in a slightly different way. When splitting a node, a random threshold will be chosen to split the non-missing values on. Then the non-missing values will be sent to the left and right child based on the randomly selected threshold, while the missing values will also be randomly sent to the left or right child. This is repeated for every feature considered at each split. The best split among these is chosen.

During prediction, the treatment of missing-values is the same as that of the decision tree:

  • By default when predicting, the samples with missing values are classified with the class used in the split found during training.

  • If no missing values are seen during training for a given feature, then during prediction missing values are mapped to the child with the most samples.

1.10.9. Minimal Cost-Complexity Pruning

Minimal cost-complexity pruning is an algorithm used to prune a tree to avoid over-fitting, described in Chapter 3 of [BRE]. This algorithm is parameterized by \(\alpha\ge0\) known as the complexity parameter. The complexity parameter is used to define the cost-complexity measure, \(R_\alpha(T)\) of a given tree \(T\):

\[R_\alpha(T) = R(T) + \alpha|\widetilde{T}|\]

where \(|\widetilde{T}|\) is the number of terminal nodes in \(T\) and \(R(T)\) is traditionally defined as the total misclassification rate of the terminal nodes. Alternatively, scikit-learn uses the total sample weighted impurity of the terminal nodes for \(R(T)\). As shown above, the impurity of a node depends on the criterion. Minimal cost-complexity pruning finds the subtree of \(T\) that minimizes \(R_\alpha(T)\).

The cost complexity measure of a single node is \(R_\alpha(t)=R(t)+\alpha\). The branch, \(T_t\), is defined to be a tree where node \(t\) is its root. In general, the impurity of a node is greater than the sum of impurities of its terminal nodes, \(R(T_t)<R(t)\). However, the cost complexity measure of a node, \(t\), and its branch, \(T_t\), can be equal depending on \(\alpha\). We define the effective \(\alpha\) of a node to be the value where they are equal, \(R_\alpha(T_t)=R_\alpha(t)\) or \(\alpha_{eff}(t)=\frac{R(t)-R(T_t)}{|T|-1}\). A non-terminal node with the smallest value of \(\alpha_{eff}\) is the weakest link and will be pruned. This process stops when the pruned tree’s minimal \(\alpha_{eff}\) is greater than the ccp_alpha parameter.

Examples

References

[BRE]

L. Breiman, J. Friedman, R. Olshen, and C. Stone. Classification and Regression Trees. Wadsworth, Belmont, CA, 1984.

HTTP response status codes

Assigned source reading · Mozilla Contributors

MDN Web Docs — Mozilla Contributors

Original source · Creative Commons Attribution-ShareAlike 2.5 or later · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.

HTTP response status codes

HTTP response status codes indicate whether a specific HTTP request has been successfully completed. Responses are grouped in five classes:

  1. Informational responses (100 – 199)
  2. Successful responses (200 – 299)
  3. Redirection messages (300 – 399)
  4. Client error responses (400 – 499)
  5. Server error responses (500 – 599)

The status codes listed below are defined by RFC 9110.

Note: If you receive a response that is not listed here, it is a non-standard response, possibly custom to the server's software.

Informational responses

100 Continue

This interim response indicates that the client should continue the request or ignore the response if the request is already finished.

101 Switching Protocols

This code is sent in response to an Upgrade request header from the client and indicates the protocol the server is switching to.

102 Processing

This code was used in Web Distributed Authoring (WebDAV contexts to indicate that a request had been received by the server, but no status was available at the time of the response. The status code was first introduced in RFC 2518, but it was removed from WebDAV in RFC 4918. The response code has been deprecated and it is no longer used.

103 Early Hints

This status code is primarily intended to be used with the Link header, letting the user agent start preloading resources while the server prepares a response or preconnect to an origin from which the page will need resources.

Successful responses

200 OK

The request succeeded. The result and meaning of "success" depends on the HTTP method:

  • GET: The resource has been fetched and transmitted in the message body.
  • HEAD: Representation headers are included in the response without any message body.
  • PUT or POST: The resource describing the result of the action is transmitted in the message body.
  • TRACE: The message body contains the request as received by the server.
201 Created

The request succeeded, and a new resource was created as a result. This is typically the response sent after POST requests, or some PUT requests.

202 Accepted

The request has been received but not yet acted upon. It is noncommittal, since there is no way in HTTP to later send an asynchronous response indicating the outcome of the request. It is intended for cases where another process or server handles the request, or for batch processing.

203 Non-Authoritative Information

This response code means the returned metadata is not exactly the same as is available from the origin server, but is collected from a local or a third-party copy. This is mostly used for mirrors or backups of another resource. Except for that specific case, the 200 OK response is preferred to this status.

204 No Content

There is no content to send for this request, but the headers are useful. The user agent may update its cached headers for this resource with the new ones.

205 Reset Content

Tells the user agent to reset the document which sent this request.

206 Partial Content

This response code is used in response to a range request when the client has requested a part or parts of a resource.

207 Multi-Status (WebDAV)

Conveys information about multiple resources, for situations where multiple status codes might be appropriate.

208 Already Reported (WebDAV)

Used inside a <dav:propstat> response element to avoid repeatedly enumerating the internal members of multiple bindings to the same collection.

226 IM Used (HTTP Delta encoding)

The server has fulfilled a GET request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance.

Redirection messages

300 Multiple Choices

In agent-driven content negotiation, the request has more than one possible response and the user agent or user should choose one of them. There is no standardized way for clients to automatically choose one of the responses, so this is rarely used.

301 Moved Permanently

The URL of the requested resource has been changed permanently. The new URL is given in the response.

302 Found

This response code means that the URI of requested resource has been changed temporarily. Further changes in the URI might be made in the future, so the same URI should be used by the client in future requests.

303 See Other

The server sent this response to direct the client to get the requested resource at another URI with a GET request.

304 Not Modified

This is used for caching purposes. It tells the client that the response has not been modified, so the client can continue to use the same cached version of the response.

305 Use Proxy

Defined in a previous version of the HTTP specification to indicate that a requested response must be accessed by a proxy. It has been deprecated due to security concerns regarding in-band configuration of a proxy.

306 unused

This response code is no longer used; but is reserved. It was used in a previous version of the HTTP/1.1 specification.

307 Temporary Redirect

The server sends this response to direct the client to get the requested resource at another URI with the same method that was used in the prior request. This has the same semantics as the 302 Found response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the redirected request.

308 Permanent Redirect

This means that the resource is now permanently located at another URI, specified by the Location response header. This has the same semantics as the 301 Moved Permanently HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request.

Client error responses

400 Bad Request

The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).

401 Unauthorized

Although the HTTP standard specifies "unauthorized", semantically this response means "unauthenticated". That is, the client must authenticate itself to get the requested response.

402 Payment Required

The initial purpose of this code was for digital payment systems, however this status code is rarely used and no standard convention exists.

403 Forbidden

The client does not have access rights to the content; that is, it is unauthorized, so the server is refusing to give the requested resource. Unlike 401 Unauthorized, the client's identity is known to the server.

404 Not Found

The server cannot find the requested resource. In the browser, this means the URL is not recognized. In an API, this can also mean that the endpoint is valid but the resource itself does not exist. Servers may also send this response instead of 403 Forbidden to hide the existence of a resource from an unauthorized client. This response code is probably the most well known due to its frequent occurrence on the web.

405 Method Not Allowed

The request method is known by the server but is not supported by the target resource. For example, an API may not allow DELETE on a resource, or the TRACE method entirely.

406 Not Acceptable

This response is sent when the web server, after performing server-driven content negotiation, doesn't find any content that conforms to the criteria given by the user agent.

407 Proxy Authentication Required

This is similar to 401 Unauthorized but authentication is needed to be done by a proxy.

408 Request Timeout

This response is sent on an idle connection by some servers, even without any previous request by the client. It means that the server would like to shut down this unused connection. This response is used much more since some browsers use HTTP pre-connection mechanisms to speed up browsing. Some servers may shut down a connection without sending this message.

409 Conflict

This response is sent when a request conflicts with the current state of the server. In WebDAV remote web authoring, 409 responses are errors sent to the client so that a user might be able to resolve a conflict and resubmit the request.

410 Gone

This response is sent when the requested content has been permanently deleted from server, with no forwarding address. Clients are expected to remove their caches and links to the resource. The HTTP specification intends this status code to be used for "limited-time, promotional services". APIs should not feel compelled to indicate resources that have been deleted with this status code.

411 Length Required

Server rejected the request because the Content-Length header field is not defined and the server requires it.

412 Precondition Failed

In conditional requests, the client has indicated preconditions in its headers which the server does not meet.

413 Content Too Large

The request body is larger than limits defined by server. The server might close the connection or return a Retry-After header field.

414 URI Too Long

The URI requested by the client is longer than the server is willing to interpret.

415 Unsupported Media Type

The media format of the requested data is not supported by the server, so the server is rejecting the request.

416 Range Not Satisfiable

The ranges specified by the Range header field in the request cannot be fulfilled. It's possible that the range is outside the size of the target resource's data.

417 Expectation Failed

This response code means the expectation indicated by the Expect request header field cannot be met by the server.

418 I'm a teapot

The server refuses the attempt to brew coffee with a teapot.

421 Misdirected Request

The request was directed at a server that is not able to produce a response. This can be sent by a server that is not configured to produce responses for the combination of scheme and authority that are included in the request URI.

422 Unprocessable Content (WebDAV)

The request was well-formed but was unable to be followed due to semantic errors.

423 Locked (WebDAV)

The resource that is being accessed is locked.

424 Failed Dependency (WebDAV)

The request failed due to failure of a previous request.

425 Too Early

Indicates that the server is unwilling to risk processing a request that might be replayed.

426 Upgrade Required

The server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol. The server sends an Upgrade header in a 426 response to indicate the required protocol(s).

428 Precondition Required

The origin server requires the request to be conditional. This response is intended to prevent the 'lost update' problem, where a client GETs a resource's state, modifies it and PUTs it back to the server, when meanwhile a third party has modified the state on the server, leading to a conflict.

429 Too Many Requests

The user has sent too many requests in a given amount of time (rate limiting).

431 Request Header Fields Too Large

The server is unwilling to process the request because its header fields are too large. The request may be resubmitted after reducing the size of the request header fields.

The user agent requested a resource that cannot legally be provided, such as a web page censored by a government.

Server error responses

500 Internal Server Error

The server has encountered a situation it does not know how to handle. This error is generic, indicating that the server cannot find a more appropriate 5XX status code to respond with.

501 Not Implemented

The request method is not supported by the server and cannot be handled. The only methods that servers are required to support (and therefore must not return this code) are GET and HEAD.

502 Bad Gateway

This error response means that the server, while working as a gateway to get a response needed to handle the request, got an invalid response.

503 Service Unavailable

The server is not ready to handle the request. Common causes are a server that is down for maintenance or that is overloaded. Note that together with this response, a user-friendly page explaining the problem should be sent. This response should be used for temporary conditions and the Retry-After HTTP header should, if possible, contain the estimated time before the recovery of the service. The webmaster must also take care about the caching-related headers that are sent along with this response, as these temporary condition responses should usually not be cached.

504 Gateway Timeout

This error response is given when the server is acting as a gateway and cannot get a response in time.

505 HTTP Version Not Supported

The HTTP version used in the request is not supported by the server.

506 Variant Also Negotiates

The server has an internal configuration error: during content negotiation, the chosen variant is configured to engage in content negotiation itself, which results in circular references when creating responses.

507 Insufficient Storage (WebDAV)

The method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the request.

508 Loop Detected (WebDAV)

The server detected an infinite loop while processing the request.

510 Not Extended

The client request declares an HTTP Extension (RFC 2774) that should be used to process the request, but the extension is not supported.

511 Network Authentication Required

Indicates that the client needs to authenticate to gain network access.

Browser compatibility

See also

11.7. The Transformer Architecture Open the notebook in SageMaker Studio Lab

Assigned source reading · Aston Zhang, Zachary C. Lipton, Mu Li and Alexander J. Smola

Dive into Deep Learning — the authors and contributors; text CC BY-SA 4.0; accompanying code under its separately stated license.

Original source · Creative Commons Attribution-ShareAlike 4.0 · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.

11.7. The Transformer Architecture
Open the notebook in SageMaker Studio Lab

We have compared CNNs, RNNs, and self-attention in Section 11.6.2. Notably, self-attention enjoys both parallel computation and the shortest maximum path length. Therefore, it is appealing to design deep architectures by using self-attention. Unlike earlier self-attention models that still rely on RNNs for input representations (Cheng et al., 2016, Lin et al., 2017, Paulus et al., 2017), the Transformer model is solely based on attention mechanisms without any convolutional or recurrent layer (Vaswani et al., 2017). Though originally proposed for sequence-to-sequence learning on text data, Transformers have been pervasive in a wide range of modern deep learning applications, such as in areas to do with language, vision, speech, and reinforcement learning.

import math
import pandas as pd
import torch
from torch import nn
from d2l import torch as d2l

11.7.1. Model

As an instance of the encoder–decoder architecture, the overall architecture of the Transformer is presented in Fig. 11.7.1. As we can see, the Transformer is composed of an encoder and a decoder. In contrast to Bahdanau attention for sequence-to-sequence learning in Fig. 11.4.2, the input (source) and output (target) sequence embeddings are added with positional encoding before being fed into the encoder and the decoder that stack modules based on self-attention.

../_images/transformer.svg

Fig. 11.7.1 The Transformer architecture.

Now we provide an overview of the Transformer architecture in Fig. 11.7.1. At a high level, the Transformer encoder is a stack of multiple identical layers, where each layer has two sublayers (either is denoted as \(\textrm{sublayer}\)). The first is a multi-head self-attention pooling and the second is a positionwise feed-forward network. Specifically, in the encoder self-attention, queries, keys, and values are all from the outputs of the previous encoder layer. Inspired by the ResNet design of Section 8.6, a residual connection is employed around both sublayers. In the Transformer, for any input \(\mathbf{x} \in \mathbb{R}^d\) at any position of the sequence, we require that \(\textrm{sublayer}(\mathbf{x}) \in \mathbb{R}^d\) so that the residual connection \(\mathbf{x} + \textrm{sublayer}(\mathbf{x}) \in \mathbb{R}^d\) is feasible. This addition from the residual connection is immediately followed by layer normalization (Ba et al., 2016). As a result, the Transformer encoder outputs a \(d\)-dimensional vector representation for each position of the input sequence.

The Transformer decoder is also a stack of multiple identical layers with residual connections and layer normalizations. As well as the two sublayers described in the encoder, the decoder inserts a third sublayer, known as the encoder–decoder attention, between these two. In the encoder–decoder attention, queries are from the outputs of the decoder’s self-attention sublayer, and the keys and values are from the Transformer encoder outputs. In the decoder self-attention, queries, keys, and values are all from the outputs of the previous decoder layer. However, each position in the decoder is allowed only to attend to all positions in the decoder up to that position. This masked attention preserves the autoregressive property, ensuring that the prediction only depends on those output tokens that have been generated.

We have already described and implemented multi-head attention based on scaled dot products in Section 11.5 and positional encoding in Section 11.6.3. In the following, we will implement the rest of the Transformer model.

11.7.2. Positionwise Feed-Forward Networks

The positionwise feed-forward network transforms the representation at all the sequence positions using the same MLP. This is why we call it positionwise. In the implementation below, the input X with shape (batch size, number of time steps or sequence length in tokens, number of hidden units or feature dimension) will be transformed by a two-layer MLP into an output tensor of shape (batch size, number of time steps, ffn_num_outputs).

class PositionWiseFFN(nn.Module):  #@save
    """The positionwise feed-forward network."""
    def __init__(self, ffn_num_hiddens, ffn_num_outputs):
        super().__init__()
        self.dense1 = nn.LazyLinear(ffn_num_hiddens)
        self.relu = nn.ReLU()
        self.dense2 = nn.LazyLinear(ffn_num_outputs)

    def forward(self, X):
        return self.dense2(self.relu(self.dense1(X)))

The following example shows that the innermost dimension of a tensor changes to the number of outputs in the positionwise feed-forward network. Since the same MLP transforms at all the positions, when the inputs at all these positions are the same, their outputs are also identical.

ffn = PositionWiseFFN(4, 8)
ffn.eval()
ffn(torch.ones((2, 3, 4)))[0]
tensor([[ 0.6300,  0.7739,  0.0278,  0.2508, -0.0519,  0.4881, -0.4105,  0.5163],
        [ 0.6300,  0.7739,  0.0278,  0.2508, -0.0519,  0.4881, -0.4105,  0.5163],
        [ 0.6300,  0.7739,  0.0278,  0.2508, -0.0519,  0.4881, -0.4105,  0.5163]],
       grad_fn=<SelectBackward0>)

11.7.3. Residual Connection and Layer Normalization

Now let’s focus on the “add & norm” component in Fig. 11.7.1. As we described at the beginning of this section, this is a residual connection immediately followed by layer normalization. Both are key to effective deep architectures.

In Section 8.5, we explained how batch normalization recenters and rescales across the examples within a minibatch. As discussed in Section 8.5.2.3, layer normalization is the same as batch normalization except that the former normalizes across the feature dimension, thus enjoying benefits of scale independence and batch size independence. Despite its pervasive applications in computer vision, batch normalization is usually empirically less effective than layer normalization in natural language processing tasks, where the inputs are often variable-length sequences.

The following code snippet compares the normalization across different dimensions by layer normalization and batch normalization.

ln = nn.LayerNorm(2)
bn = nn.LazyBatchNorm1d()
X = torch.tensor([[1, 2], [2, 3]], dtype=torch.float32)
# Compute mean and variance from X in the training mode
print('layer norm:', ln(X), '\nbatch norm:', bn(X))
layer norm: tensor([[-1.0000,  1.0000],
        [-1.0000,  1.0000]], grad_fn=<NativeLayerNormBackward0>)
batch norm: tensor([[-1.0000, -1.0000],
        [ 1.0000,  1.0000]], grad_fn=<NativeBatchNormBackward0>)

Now we can implement the AddNorm class using a residual connection followed by layer normalization. Dropout is also applied for regularization.

class AddNorm(nn.Module):  #@save
    """The residual connection followed by layer normalization."""
    def __init__(self, norm_shape, dropout):
        super().__init__()
        self.dropout = nn.Dropout(dropout)
        self.ln = nn.LayerNorm(norm_shape)

    def forward(self, X, Y):
        return self.ln(self.dropout(Y) + X)

The residual connection requires that the two inputs are of the same shape so that the output tensor also has the same shape after the addition operation.

add_norm = AddNorm(4, 0.5)
shape = (2, 3, 4)
d2l.check_shape(add_norm(torch.ones(shape), torch.ones(shape)), shape)

11.7.4. Encoder

With all the essential components to assemble the Transformer encoder, let’s start by implementing a single layer within the encoder. The following TransformerEncoderBlock class contains two sublayers: multi-head self-attention and positionwise feed-forward networks, where a residual connection followed by layer normalization is employed around both sublayers.

class TransformerEncoderBlock(nn.Module):  #@save
    """The Transformer encoder block."""
    def __init__(self, num_hiddens, ffn_num_hiddens, num_heads, dropout,
                 use_bias=False):
        super().__init__()
        self.attention = d2l.MultiHeadAttention(num_hiddens, num_heads,
                                                dropout, use_bias)
        self.addnorm1 = AddNorm(num_hiddens, dropout)
        self.ffn = PositionWiseFFN(ffn_num_hiddens, num_hiddens)
        self.addnorm2 = AddNorm(num_hiddens, dropout)

    def forward(self, X, valid_lens):
        Y = self.addnorm1(X, self.attention(X, X, X, valid_lens))
        return self.addnorm2(Y, self.ffn(Y))

As we can see, no layer in the Transformer encoder changes the shape of its input.

X = torch.ones((2, 100, 24))
valid_lens = torch.tensor([3, 2])
encoder_blk = TransformerEncoderBlock(24, 48, 8, 0.5)
encoder_blk.eval()
d2l.check_shape(encoder_blk(X, valid_lens), X.shape)

In the following Transformer encoder implementation, we stack num_blks instances of the above TransformerEncoderBlock classes. Since we use the fixed positional encoding whose values are always between \(-1\) and \(1\), we multiply values of the learnable input embeddings by the square root of the embedding dimension to rescale before summing up the input embedding and the positional encoding.

class TransformerEncoder(d2l.Encoder):  #@save
    """The Transformer encoder."""
    def __init__(self, vocab_size, num_hiddens, ffn_num_hiddens,
                 num_heads, num_blks, dropout, use_bias=False):
        super().__init__()
        self.num_hiddens = num_hiddens
        self.embedding = nn.Embedding(vocab_size, num_hiddens)
        self.pos_encoding = d2l.PositionalEncoding(num_hiddens, dropout)
        self.blks = nn.Sequential()
        for i in range(num_blks):
            self.blks.add_module("block"+str(i), TransformerEncoderBlock(
                num_hiddens, ffn_num_hiddens, num_heads, dropout, use_bias))

    def forward(self, X, valid_lens):
        # Since positional encoding values are between -1 and 1, the embedding
        # values are multiplied by the square root of the embedding dimension
        # to rescale before they are summed up
        X = self.pos_encoding(self.embedding(X) * math.sqrt(self.num_hiddens))
        self.attention_weights = [None] * len(self.blks)
        for i, blk in enumerate(self.blks):
            X = blk(X, valid_lens)
            self.attention_weights[
                i] = blk.attention.attention.attention_weights
        return X

Below we specify hyperparameters to create a two-layer Transformer encoder. The shape of the Transformer encoder output is (batch size, number of time steps, num_hiddens).

encoder = TransformerEncoder(200, 24, 48, 8, 2, 0.5)
d2l.check_shape(encoder(torch.ones((2, 100), dtype=torch.long), valid_lens),
                (2, 100, 24))

11.7.5. Decoder

As shown in Fig. 11.7.1, the Transformer decoder is composed of multiple identical layers. Each layer is implemented in the following TransformerDecoderBlock class, which contains three sublayers: decoder self-attention, encoder–decoder attention, and positionwise feed-forward networks. These sublayers employ a residual connection around them followed by layer normalization.

As we described earlier in this section, in the masked multi-head decoder self-attention (the first sublayer), queries, keys, and values all come from the outputs of the previous decoder layer. When training sequence-to-sequence models, tokens at all the positions (time steps) of the output sequence are known. However, during prediction the output sequence is generated token by token; thus, at any decoder time step only the generated tokens can be used in the decoder self-attention. To preserve autoregression in the decoder, its masked self-attention specifies dec_valid_lens so that any query only attends to all positions in the decoder up to the query position.

class TransformerDecoderBlock(nn.Module):
    # The i-th block in the Transformer decoder
    def __init__(self, num_hiddens, ffn_num_hiddens, num_heads, dropout, i):
        super().__init__()
        self.i = i
        self.attention1 = d2l.MultiHeadAttention(num_hiddens, num_heads,
                                                 dropout)
        self.addnorm1 = AddNorm(num_hiddens, dropout)
        self.attention2 = d2l.MultiHeadAttention(num_hiddens, num_heads,
                                                 dropout)
        self.addnorm2 = AddNorm(num_hiddens, dropout)
        self.ffn = PositionWiseFFN(ffn_num_hiddens, num_hiddens)
        self.addnorm3 = AddNorm(num_hiddens, dropout)

    def forward(self, X, state):
        enc_outputs, enc_valid_lens = state[0], state[1]
        # During training, all the tokens of any output sequence are processed
        # at the same time, so state[2][self.i] is None as initialized. When
        # decoding any output sequence token by token during prediction,
        # state[2][self.i] contains representations of the decoded output at
        # the i-th block up to the current time step
        if state[2][self.i] is None:
            key_values = X
        else:
            key_values = torch.cat((state[2][self.i], X), dim=1)
        state[2][self.i] = key_values
        if self.training:
            batch_size, num_steps, _ = X.shape
            # Shape of dec_valid_lens: (batch_size, num_steps), where every
            # row is [1, 2, ..., num_steps]
            dec_valid_lens = torch.arange(
                1, num_steps + 1, device=X.device).repeat(batch_size, 1)
        else:
            dec_valid_lens = None
        # Self-attention
        X2 = self.attention1(X, key_values, key_values, dec_valid_lens)
        Y = self.addnorm1(X, X2)
        # Encoder-decoder attention. Shape of enc_outputs:
        # (batch_size, num_steps, num_hiddens)
        Y2 = self.attention2(Y, enc_outputs, enc_outputs, enc_valid_lens)
        Z = self.addnorm2(Y, Y2)
        return self.addnorm3(Z, self.ffn(Z)), state

To facilitate scaled dot product operations in the encoder–decoder attention and addition operations in the residual connections, the feature dimension (num_hiddens) of the decoder is the same as that of the encoder.

decoder_blk = TransformerDecoderBlock(24, 48, 8, 0.5, 0)
X = torch.ones((2, 100, 24))
state = [encoder_blk(X, valid_lens), valid_lens, [None]]
d2l.check_shape(decoder_blk(X, state)[0], X.shape)

Now we construct the entire Transformer decoder composed of num_blks instances of TransformerDecoderBlock. In the end, a fully connected layer computes the prediction for all the vocab_size possible output tokens. Both of the decoder self-attention weights and the encoder–decoder attention weights are stored for later visualization.

class TransformerDecoder(d2l.AttentionDecoder):
    def __init__(self, vocab_size, num_hiddens, ffn_num_hiddens, num_heads,
                 num_blks, dropout):
        super().__init__()
        self.num_hiddens = num_hiddens
        self.num_blks = num_blks
        self.embedding = nn.Embedding(vocab_size, num_hiddens)
        self.pos_encoding = d2l.PositionalEncoding(num_hiddens, dropout)
        self.blks = nn.Sequential()
        for i in range(num_blks):
            self.blks.add_module("block"+str(i), TransformerDecoderBlock(
                num_hiddens, ffn_num_hiddens, num_heads, dropout, i))
        self.dense = nn.LazyLinear(vocab_size)

    def init_state(self, enc_outputs, enc_valid_lens):
        return [enc_outputs, enc_valid_lens, [None] * self.num_blks]

    def forward(self, X, state):
        X = self.pos_encoding(self.embedding(X) * math.sqrt(self.num_hiddens))
        self._attention_weights = [[None] * len(self.blks) for _ in range (2)]
        for i, blk in enumerate(self.blks):
            X, state = blk(X, state)
            # Decoder self-attention weights
            self._attention_weights[0][
                i] = blk.attention1.attention.attention_weights
            # Encoder-decoder attention weights
            self._attention_weights[1][
                i] = blk.attention2.attention.attention_weights
        return self.dense(X), state

    @property
    def attention_weights(self):
        return self._attention_weights

11.7.6. Training

Let’s instantiate an encoder–decoder model by following the Transformer architecture. Here we specify that both the Transformer encoder and the Transformer decoder have two layers using 4-head attention. As in Section 10.7.6, we train the Transformer model for sequence-to-sequence learning on the English–French machine translation dataset.

data = d2l.MTFraEng(batch_size=128)
num_hiddens, num_blks, dropout = 256, 2, 0.2
ffn_num_hiddens, num_heads = 64, 4
encoder = TransformerEncoder(
    len(data.src_vocab), num_hiddens, ffn_num_hiddens, num_heads,
    num_blks, dropout)
decoder = TransformerDecoder(
    len(data.tgt_vocab), num_hiddens, ffn_num_hiddens, num_heads,
    num_blks, dropout)
model = d2l.Seq2Seq(encoder, decoder, tgt_pad=data.tgt_vocab['<pad>'],
                    lr=0.001)
trainer = d2l.Trainer(max_epochs=30, gradient_clip_val=1, num_gpus=1)
trainer.fit(model, data)
../_images/output_transformer_3f197a_198_0.svg

After training, we use the Transformer model to translate a few English sentences into French and compute their BLEU scores.

engs = ['go .', 'i lost .', 'he\'s calm .', 'i\'m home .']
fras = ['va !', 'j\'ai perdu .', 'il est calme .', 'je suis chez moi .']
preds, _ = model.predict_step(
    data.build(engs, fras), d2l.try_gpu(), data.num_steps)
for en, fr, p in zip(engs, fras, preds):
    translation = []
    for token in data.tgt_vocab.to_tokens(p):
        if token == '<eos>':
            break
        translation.append(token)
    print(f'{en} => {translation}, bleu,'
          f'{d2l.bleu(" ".join(translation), fr, k=2):.3f}')
go . => ['va', '!'], bleu,1.000
i lost . => ['je', 'perdu', '.'], bleu,0.687
he's calm . => ['il', 'est', 'mouillé', '.'], bleu,0.658
i'm home . => ['je', 'suis', 'chez', 'moi', '.'], bleu,1.000

Let’s visualize the Transformer attention weights when translating the final English sentence into French. The shape of the encoder self-attention weights is (number of encoder layers, number of attention heads, num_steps or number of queries, num_steps or number of key-value pairs).

_, dec_attention_weights = model.predict_step(
    data.build([engs[-1]], [fras[-1]]), d2l.try_gpu(), data.num_steps, True)
enc_attention_weights = torch.cat(model.encoder.attention_weights, 0)
shape = (num_blks, num_heads, -1, data.num_steps)
enc_attention_weights = enc_attention_weights.reshape(shape)
d2l.check_shape(enc_attention_weights,
                (num_blks, num_heads, data.num_steps, data.num_steps))

In the encoder self-attention, both queries and keys come from the same input sequence. Since padding tokens do not carry meaning, with specified valid length of the input sequence no query attends to positions of padding tokens. In the following, two layers of multi-head attention weights are presented row by row. Each head independently attends based on a separate representation subspace of queries, keys, and values.

d2l.show_heatmaps(
    enc_attention_weights.cpu(), xlabel='Key positions',
    ylabel='Query positions', titles=['Head %d' % i for i in range(1, 5)],
    figsize=(7, 3.5))
../_images/output_transformer_3f197a_243_0.svg

To visualize the decoder self-attention weights and the encoder–decoder attention weights, we need more data manipulations. For example, we fill the masked attention weights with zero. Note that the decoder self-attention weights and the encoder–decoder attention weights both have the same queries: the beginning-of-sequence token followed by the output tokens and possibly end-of-sequence tokens.

dec_attention_weights_2d = [head[0].tolist()
                            for step in dec_attention_weights
                            for attn in step for blk in attn for head in blk]
dec_attention_weights_filled = torch.tensor(
    pd.DataFrame(dec_attention_weights_2d).fillna(0.0).values)
shape = (-1, 2, num_blks, num_heads, data.num_steps)
dec_attention_weights = dec_attention_weights_filled.reshape(shape)
dec_self_attention_weights, dec_inter_attention_weights = \
    dec_attention_weights.permute(1, 2, 3, 0, 4)

d2l.check_shape(dec_self_attention_weights,
                (num_blks, num_heads, data.num_steps, data.num_steps))
d2l.check_shape(dec_inter_attention_weights,
                (num_blks, num_heads, data.num_steps, data.num_steps))

Because of the autoregressive property of the decoder self-attention, no query attends to key–value pairs after the query position.

d2l.show_heatmaps(
    dec_self_attention_weights[:, :, :, :],
    xlabel='Key positions', ylabel='Query positions',
    titles=['Head %d' % i for i in range(1, 5)], figsize=(7, 3.5))
../_images/output_transformer_3f197a_273_0.svg

Similar to the case in the encoder self-attention, via the specified valid length of the input sequence, no query from the output sequence attends to those padding tokens from the input sequence.

d2l.show_heatmaps(
    dec_inter_attention_weights, xlabel='Key positions',
    ylabel='Query positions', titles=['Head %d' % i for i in range(1, 5)],
    figsize=(7, 3.5))
../_images/output_transformer_3f197a_288_0.svg

Although the Transformer architecture was originally proposed for sequence-to-sequence learning, as we will discover later in the book, either the Transformer encoder or the Transformer decoder is often individually used for different deep learning tasks.

11.7.7. Summary

The Transformer is an instance of the encoder–decoder architecture, though either the encoder or the decoder can be used individually in practice. In the Transformer architecture, multi-head self-attention is used for representing the input sequence and the output sequence, though the decoder has to preserve the autoregressive property via a masked version. Both the residual connections and the layer normalization in the Transformer are important for training a very deep model. The positionwise feed-forward network in the Transformer model transforms the representation at all the sequence positions using the same MLP.

11.7.8. Exercises

  1. Train a deeper Transformer in the experiments. How does it affect the training speed and the translation performance?

  2. Is it a good idea to replace scaled dot product attention with additive attention in the Transformer? Why?

  3. For language modeling, should we use the Transformer encoder, decoder, or both? How would you design this method?

  4. What challenges can Transformers face if input sequences are very long? Why?

  5. How would you improve the computational and memory efficiency of Transformers? Hint: you may refer to the survey paper by Tay et al. (2020).