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.
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.
Imagine an application with a
moderately-sized data set, say of one million (), 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 () searches in this data. If each of these
searches inspects each of the items, this gives a total
of
(one thousand billion) inspections.
At the time of writing, even a very fast
desktop computer can not do more than one billion () operations per
second.1.1This means that this application will take at least
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).
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 queries per second,
meaning that they would require at least
very
fast servers just to keep up.
These examples tell us that the obvious implementations of data structures
do not scale well when the number of items,
, in the data structure
and the number of operations, , performed on the data structure
are both large. In these cases, the time (measured in, say, machine
instructions) is roughly
.
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
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
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:
some mathematical review including exponentials, logarithms,
factorials, asymptotic (big-Oh) notation, probability, and randomization;
the model of computation;
correctness, running time, and space;
an overview of the rest of the chapters; and
the sample code and typesetting conventions.
A reader with or without a background in these areas can easily skip
them now and come back to them later if necessary.
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.
2.1 ArrayStack: Fast Stack Operations Using an Array
An ArrayStack implements the list interface using an array
, called
the backing array. The list element with index
is stored
in
. At most times,
is larger than strictly necessary,
so an integer
is used to keep track of the number of elements
actually stored in
. In this way, the list elements are stored in
,...,
and, at all times,
.
Accessing and modifying the elements of an ArrayStack using
and
is trivial. After performing any necessary bounds-checking
we simply return or set, respectively,
.
The operations of adding and removing elements from an ArrayStack
are illustrated in Figure 2.1. To implement the
operation, we first check if
is already full. If so, we call
the method
to increase the size of
. How
is implemented will be discussed later. For now, it is sufficient to
know that, after a call to
, we can be sure that
. With this out of the way, we now shift the elements
right by one position to make room for
,
set
equal to
, and increment
.
Figure 2.1:
A sequence of
and
operations on an
ArrayStack. Arrows denote elements being copied. Operations that
result in a call to
are marked with an asterisk.
If we ignore the cost of the potential call to
, then the cost
of the
operation is proportional to the number of elements we
have to shift to make room for
. Therefore the cost of this operation
(ignoring the cost of resizing
) is
.
Implementing the
operation is similar. We shift the elements
left by one position (overwriting
) and
decrease the value of
. After doing this, we check if
is getting
much smaller than
by checking if
. If so,
then we call
to reduce the size of
.
If we ignore the cost of the
method, the cost of a
operation is proportional to the number of elements we shift, which
is
.
The
method is fairly straightforward; it allocates a new
array
whose size is
and copies the
elements of
into
the first
positions in
, and then sets
to
. Thus, after a call to
,
.
Analyzing the actual cost of the
operation is easy. It
allocates an array
of size
and copies the
elements of
into
. This takes
time.
The running time analysis from the previous section ignored the cost
of calls to
. 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
and
operation. Instead, it considers the cost of all calls to
during a sequence of calls to
or
.
In particular, we will show:
Lemma 2..1If an empty ArrayStack is created and any sequence of calls
to
and
are performed, then the total time spent
during all calls to
is .
Proof.
We will show that any time
is called, the number of calls
to
or
since the last call to
is at least
. Therefore, if
denotes the value of
during the
th call to
and denotes the number of calls to
, then the total number of calls to
or
is at least
which is equivalent to
On the other hand, the total time spent during all calls to
is
since is not more than . All that remains is to show that the
number of calls to
or
between the th
and the th call to
is at least
.
There are two cases to consider. In the first case,
is
being called by
because the backing array
is full, i.e.,
. Consider the previous call to
:
after this previous call, the size of
was
, but the
number of elements stored in
was at most
.
But now the number of elements stored in
is
,
so there must have been at least
calls to
since
the previous call to
.
The second case occurs when
is being called by
because
. Again, after the
previous call to
the number of elements stored in
was
at least
.2.1 Now there
are
elements stored in
. Therefore, the number
of
operations since the last call to
is at least
In either case, the number of calls to
or
that
occur between the th call to
and the th call to
is at least
, as required to complete the proof.
The following theorem summarizes the performance of an ArrayStack:
Theorem 2..1An ArrayStack implements the List interface. Ignoring the cost of
calls to
, an ArrayStack supports the operations
and
in time per operation; and
and
in
time per operation.
Furthermore, beginning with an empty ArrayStack and performing any
sequence of and
operations results in a
total of time spent during all calls to
.
The ArrayStack is an efficient way to implement a Stack.
In particular, we can implement
as
and
as
, in which case these operations will run in
amortized time.
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.
The hash tables discussed in the previous section are used to associate
data with integer keys consisting of
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
-bit hash codes. Hash code mappings should
have the following properties:
If
and
are equal, then
and
are equal.
If
and
are not equal, then the probability that
should be small (close to
).
The first property ensures that if we store
in a hash table and later
look up a value
equal to
, then we will find
--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.
Small primitive data types like
,
,
, and
are
usually easy to find hash codes for. These data types always have a
binary representation and this binary representation usually consists of
or fewer bits. In these
cases, we just treat these bits as the representation of an integer in
the range
. 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
bits, usually
bits for some constant integer . (Java's
and
types are examples of this with .) These data types can be treated
as compound objects made of 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
bits of
precision, then there are simple and robust methods available.
Suppose we have an object made up of several parts
whose hash codes are
.
Then we can choose mutually independent random
-bit integers
and a random
-bit odd integer
and
compute a hash code for our object with
Note that this hash code has a final step (multiplying by
and
dividing by
) that uses the multiplicative hash function
from Section 5.1.1 to take the
-bit intermediate result and
reduce it to a
-bit final result. Here is an example of this method applied to a simple compound object with three parts
,
, and
:
The following theorem shows that, in addition to being straightforward to implement, this method is provably good:
Theorem 5..3Let
and
each be sequences of
bit integers in
and assume
for at least one index
. Then
Proof.
We will first ignore the final multiplicative hashing step and see how
that step contributes later. Define:
Suppose that
.
We can rewrite this as:
(5.4)
where
If we assume, without loss of generality that
, then
(5.4) becomes
(5.5)
since each of
and
is at most
, so
their product is at most
.
By assumption,
, so (5.5) has at most one
solution in
. Therefore, since
and are
independent (
are mutually independent), the
probability that we select
so that
is at most
.
The final step of the hash function is to apply multiplicative hashing
to reduce our
-bit intermediate result
to
a
-bit final result
. By Theorem 5.3,
if
, then
.
To summarize,
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
-bit integer
for each component.
We could use a pseudorandom sequence to generate as many
's as we
need, but then the
'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
and
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,
. This method is based on the following
theorem, which says that polynomials over prime fields behave pretty-much
like usual polynomials:
Theorem 5..4Let
be a prime number, and let
be a non-trivial polynomial with coefficients
. Then the equation
has at most solutions for
.
To use Theorem 5.4, we hash a sequence of integers
with each
using
a random integer
via the formula
Note the extra
term at the end of the formula. It helps
to think of
as the last element,
, in the sequence
. Note that this element differs from every other
element in the sequence (each of which is in the set
).
We can think of
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
:
Theorem 5..5Let
be a prime, let
and
each be sequences of
-bit integers in
, and assume
for at least
one index
. Then
Proof.
The equation
can be rewritten as
(5.6)
Since
, this polynomial is non-trivial. Therefore,
by Theorem 5.4, it has at most solutions in
.
The probability that we pick
to be one of these solutions is therefore
at most
.
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
This guarantees that if we have two sequences of length and
with , then these two sequences differ at index . In
this case, (5.6) becomes
which, by Theorem 5.4, has at most solutions in
.
This combined with Theorem 5.5 suffice to prove the
following more general theorem:
Theorem 5..6Let
be a prime, let
and
be distinct sequences of
-bit integers in
. Then
The following example code shows how this hash function is applied to
an object that contains an array,
, of values:
The preceding code sacrifices some collision probability for implementation
convenience. In particular, it applies the multiplicative hash function
from Section 5.1.1, with
to reduce
to a
31-bit value. This is so that the additions and multiplications that are
done modulo the prime
can be carried out using unsigned
63-bit arithmetic. Thus the probability of two different sequences,
the longer of which has length , having the same hash code is at most
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
operation that allows the priority queue to
absorb the elements of a second priority queue
.
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
bit integers in a binary tree.
All leaves in the tree have depth
and each integer is encoded as a
root-to-leaf path. The path for the integer
turns left at level
if the
th most significant bit of
is a 0 and turns right if it
is a 1. Figure 13.1 shows an example for the case
,
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.
Because the search path
for a value
depends on the bits of
, it will
be helpful to name the children of a node,
,
(
)
and
(
). 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
(
) is the node that
comes before
in the list and
(
) is the node that
follows
in the list. A special node,
, is used both before
the first node and after the last node in the list (see Section 3.2).
Each node,
, also contains an additional pointer
. If
's
left child is missing, then
points to the smallest leaf in
's subtree. If
's right child is missing, then
points
to the largest leaf in
's subtree. An example of a BinaryTrie,
showing
pointers and the doubly-linked list at the leaves, is
shown in Figure 13.2.
Figure 13.2:
A BinaryTrie with
pointers shown as curved dashed
edges.
The
operation in a BinaryTrie is fairly straightforward.
We try to follow the search path for
in the trie. If we reach a leaf,
then we have found
. If we reach a node
where we cannot proceed
(because
is missing a child), then we follow
, which takes us
either to the smallest leaf larger than
or the largest leaf smaller than
. Which of these two cases occurs depends on whether
is missing
its left or right child, respectively. In the former case (
is missing
its left child), we have found the node we want. In the latter case (
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.
Figure 13.3:
The paths followed by
and
.
The running-time of the
method is dominated by the time it
takes to follow a root-to-leaf path, so it runs in
time.
The
operation in a BinaryTrie is also fairly straightforward,
but has a lot of work to do:
It follows the search path for
until reaching a node
where it can no longer proceed.
It creates the remainder of the search path from
to a leaf
that contains
.
It adds the node,
, containing
to the linked list
of leaves (it has access to the predecessor,
, of
in
the linked list from the
pointer of the last node,
,
encountered during step 1.)
It walks back up the search path for
adjusting
pointers at the nodes whose
pointer should now point to
.
Figure 13.5:
Removing the value 9 from the BinaryTrie in
Figure 13.2.
Theorem 13..1A BinaryTrie implements the SSet interface for
-bit integers. A
BinaryTrie supports the operations
,
, and
in
time per operation. The space used by a BinaryTrie that
stores
values is
.
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.
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 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.
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.
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;
}
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?");
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:
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:
it must contain a finally block, and
the enclosing try...catch statement's catch block is
checked for a match.
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
}
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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:
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.
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.
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.
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.
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:
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.
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" });
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" });
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.
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.
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:
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.
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:
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.
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.
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.
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
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.
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.
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:
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.
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.
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.
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:
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
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
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
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.,
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
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\).
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.
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.1print('underflow:',a**784)print('logarithm is normal:',784*math.log(a))
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
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?
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?
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.
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.
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).
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:
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)}\):
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:
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.
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))
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:
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):
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.
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 gradientsx.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))
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\):
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).
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 gradientsx.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))
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
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.
Compute the derivative of the pReLU activation function.
Compute the derivative of the Swish activation function
\(x \operatorname{sigmoid}(\beta x)\).
Show that an MLP using only ReLU (or pReLU) constructs a continuous
piecewise linear function.
Sigmoid and tanh are very similar.
Show that
\(\operatorname{tanh}(x) + 1 = 2 \operatorname{sigmoid}(2x)\).
Prove that the function classes parametrized by both
nonlinearities are identical. Hint: affine layers have bias terms,
too.
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?
Provide an example where the gradients vanish for the sigmoid
activation function.
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.
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:
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:
Once trained, you can plot the tree with the plot_tree function:
>>> tree.plot_tree(clf)[...]
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 condainstallpython-graphviz.
Alternatively binaries for graphviz can be downloaded from the graphviz project homepage,
and the Python wrapper installed from pypi with pipinstallgraphviz.
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:
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:
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:
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:
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.
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.
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
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)
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
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:
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:
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\).
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.
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.
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:
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:
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:
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.
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:
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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).
Although the HTTP standard specifies "unauthorized", semantically this response means "unauthenticated".
That is, the client must authenticate itself to get the requested response.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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).
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.
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 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.
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.
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.
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.
The method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the request.
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.
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.
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).
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.
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 modeprint('layer norm:',ln(X),'\nbatch norm:',bn(X))
Now we can implement the AddNorm class using a residual connection
followed by layer normalization. Dropout is also applied for
regularization.
classAddNorm(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)defforward(self,X,Y):returnself.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.
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.
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.
classTransformerEncoder(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_hiddensself.embedding=nn.Embedding(vocab_size,num_hiddens)self.pos_encoding=d2l.PositionalEncoding(num_hiddens,dropout)self.blks=nn.Sequential()foriinrange(num_blks):self.blks.add_module("block"+str(i),TransformerEncoderBlock(num_hiddens,ffn_num_hiddens,num_heads,dropout,use_bias))defforward(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 upX=self.pos_encoding(self.embedding(X)*math.sqrt(self.num_hiddens))self.attention_weights=[None]*len(self.blks)fori,blkinenumerate(self.blks):X=blk(X,valid_lens)self.attention_weights[i]=blk.attention.attention.attention_weightsreturnX
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).
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.
classTransformerDecoderBlock(nn.Module):# The i-th block in the Transformer decoderdef__init__(self,num_hiddens,ffn_num_hiddens,num_heads,dropout,i):super().__init__()self.i=iself.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)defforward(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 stepifstate[2][self.i]isNone:key_values=Xelse:key_values=torch.cat((state[2][self.i],X),dim=1)state[2][self.i]=key_valuesifself.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-attentionX2=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)returnself.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.
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.
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.
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)foren,fr,pinzip(engs,fras,preds):translation=[]fortokenindata.tgt_vocab.to_tokens(p):iftoken=='<eos>':breaktranslation.append(token)print(f'{en} => {translation}, bleu,'f'{d2l.bleu(" ".join(translation),fr,k=2):.3f}')
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).
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.
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.
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.
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
Train a deeper Transformer in the experiments. How does it affect the
training speed and the translation performance?
Is it a good idea to replace scaled dot product attention with
additive attention in the Transformer? Why?
For language modeling, should we use the Transformer encoder,
decoder, or both? How would you design this method?
What challenges can Transformers face if input sequences are very
long? Why?
How would you improve the computational and memory efficiency of
Transformers? Hint: you may refer to the survey paper by
Tay et al. (2020).