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.
When discussing data structures, it is important to understand the
difference between a data structure's interface and its implementation.
An interface describes what a data structure does, while an implementation
describes how the data structure does it.
An interface,
sometimes also called an abstract data
type, defines the set of operations supported by a data structure and
the semantics, or meaning, of those operations. An interface tells us
nothing about how the data structure implements these operations; it only
provides a list of supported operations along with specifications about
what types of arguments each operation accepts and the value returned
by each operation.
A data structure implementation, on the other hand, includes the
internal representation of the data structure as well as the definitions
of the algorithms that implement the operations supported by the data
structure. Thus, there can be many implementations of a single interface.
For example, in Chapter 2, we will see implementations of the
List interface using arrays and in Chapter 3 we will
see implementations of the List interface using pointer-based data
structures. Each implements the same interface, List,
but in different ways.
The Queue interface represents a collection of elements to which we
can add elements and remove the next element. More precisely, the operations
supported by the Queue interface are
: add the value
to the Queue
: remove the next (previously added) value,
, from the Queue and return
Notice that the
operation takes no argument. The Queue's
queueing discipline decides which element should be removed.
There are many possible queueing disciplines, the most common of which
include FIFO, priority, and LIFO.
A FIFO (first-in-first-out) Queue,
which is illustrated in
Figure 1.1, removes items in the same order they were added, much
in the same way a queue (or line-up) works when checking out at a cash
register in a grocery store. This is the most common kind of Queue
so the qualifier FIFO is often omitted. In other texts, the
and
operations on a FIFO Queue are often called
and
, respectively.
Figure 1.1:
A FIFO Queue.
A priority Queue,
illustrated in Figure 1.2, always
removes the smallest element from the Queue, breaking ties arbitrarily.
This is similar to the way in which patients are triaged in a hospital
emergency room. As patients arrive they are evaluated and then placed in
a waiting room. When a doctor becomes available he or she first treats
the patient with the most life-threatening condition. The
operation on a priority Queue is usually called
in
other texts.
Figure 1.2:
A priority Queue.
A very common queueing discipline is the LIFO (last-in-first-out)
discipline, illustrated in Figure 1.3. In a LIFO Queue,
the most recently added element is the next one removed. This is best
visualized in terms of a stack of plates; plates are placed on the top of
the stack and also removed from the top of the stack. This structure is
so common that it gets its own name: Stack. Often, when discussing a
Stack, the names of
and
are changed to
and
; this is to avoid confusing the LIFO and FIFO queueing
disciplines.
Figure 1.3:
A stack.
A Deque
is a generalization of both the FIFO Queue and LIFO Queue (Stack).
A Deque represents a sequence of elements, with a front and a back.
Elements can be added at the front of the sequence or the back of the
sequence. The names of the Deque operations are self-explanatory:
,
,
, and
. It is
worth noting that a Stack can be implemented using only
and
while a FIFO Queue can be implemented using
and
.
This book will talk very little about the FIFO Queue, Stack, or
Deque interfaces. This is because these interfaces are subsumed by the
List interface. A List,
illustrated in Figure 1.4, represents a
sequence,
, of values. The List interface
includes the following operations:
: return
, the length of the list
: return the value
: set the value of
equal to
: add
at position
, displacing
;
Set
, for all
, increment
, and set
remove the value
, displacing
;
Set
, for all
and decrement
Notice that these operations are easily sufficient to implement the
Deque interface:
Figure 1.4:
A List represents a sequence indexed by
. In this List a call to
would return
the value .
Although we will normally not discuss the Stack, Deque and FIFO
Queue interfaces in subsequent chapters, the terms Stack and Deque
are sometimes used in the names of data structures that implement the
List interface. When this happens, it highlights the fact that
these data structures can be used to implement the Stack or Deque
interface very efficiently. For example, the ArrayDeque class is an
implementation of the List interface that implements all the Deque
operations in constant time per operation.
The USet
interface represents an unordered set of unique elements, which
mimics a mathematical set. A USet contains
distinct
elements; no element appears more than once; the elements are in no
specific order. A USet supports the following operations:
: return the number,
, of elements in the set
: add the element
to the set if not already present;
Add
to the set provided that there
is no element
in the set such that
equals
. Return
if
was added to the set and
otherwise.
: remove
from the set;
Find an element
in the set such that
equals
and remove
. Return
, or
if no such element exists.
: find
in the set if it exists;
Find an element
in the set such that
equals
. Return
, or
if no such element exists.
These definitions are a bit fussy about distinguishing
, the element
we are removing or finding, from
, the element we may remove or find.
This is because
and
might actually be distinct objects that
are nevertheless treated as equal.
Such a distinction is useful because it allows for the creation of
dictionaries or maps that map keys onto values.
To create a dictionary/map, one forms compound objects called Pairs,
each of which contains a key and a value. Two Pairs
are treated as equal if their keys are equal. If we store some pair
in a USet and then later call the
method using
the pair
the result will be
. In other
words, it is possible to recover the value,
, given only the key,
.
1.2.4 The SSet Interface: Sorted Sets
The SSet interface represents a sorted set of elements. An SSet
stores elements from some total order, so that any two elements
and
can be compared. In code examples, this will be done with a
method called
in which
An SSet supports the
,
, and
methods with
exactly the same semantics as in the USet interface. The difference
between a USet and an SSet is in the
method:
: locate
in the sorted set;
Find the smallest element
in the set such that
.
Return
or
if no such element exists.
This version of the
operation is sometimes referred to
as a successor search.
It differs in a fundamental way from
since it returns a meaningful result even when there is
no element equal to
in the set.
The distinction between the USet and SSet
operations is
very important and often missed. The extra functionality provided
by an SSet usually comes with a price that includes both a larger
running time and a higher implementation complexity. For example, most
of the SSet implementations discussed in this book all have
operations with running times that are logarithmic in the size of the set.
On the other hand, the implementation of a USet as a ChainedHashTable
in Chapter 5 has a
operation that runs in constant
expected time. When choosing which of these structures to use, one should
always use a USet unless the extra functionality offered by an SSet
is truly needed.
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 this section, we review some mathematical notations and tools
used throughout this book, including logarithms, big-Oh notation, and
probability theory. This review will be brief and is not intended as
an introduction. Readers who feel they are missing this background are
encouraged to read, and do exercises from, the appropriate sections of
the very good (and free) textbook on mathematics for computer science
[50].
The expression denotes the number raised to the power of .
If is a positive integer, then this is just the value of
multiplied by itself times:
When is a negative integer,
. When , .
When is not an integer, we can still define exponentiation in terms
of the exponential function (see below), which is itself defined in
terms of the exponential series, but this is best left to a calculus text.
In this book, the expression denotes the base- logarithm
of . That is, the unique value that satisfies
Most of the logarithms in this book are base 2 (binary logarithms).
For these, we omit the base, so that is shorthand for
.
An informal, but useful, way to think about logarithms is to think
of as the number of times we have to divide by
before the result is less than or equal to 1. For example, when one
does binary search, each comparison reduces the number of possible
answers by a factor of 2. This is repeated until there is at most one
possible answer. Therefore, the number of comparison done by binary
search when there are initially at most possible answers is at
most
.
Another logarithm that comes up several times in this book is the
natural logarithm. Here we use the notation to denote
, where -- Euler's constant -- is given by
The natural logarithm comes up frequently because it is the value
of a particularly common integral:
Two of the most common manipulations we do with logarithms are removing
them from an exponent:
and changing the base of a logarithm:
For example, we can use these two manipulations to compare the natural and binary logarithms
1.3.2 Factorials
In one or two places in this book, the factorial function is used.
For a non-negative integer , the notation (pronounced `` factorial'') is defined to mean
Factorials appear because counts the number of distinct
permutations, i.e., orderings, of distinct elements.
For the special case , is defined as 1.
The quantity can be approximated using Stirling's Approximation:
where
Stirling's Approximation also approximates :
(In fact, Stirling's Approximation is most easily proven by approximating
by the integral
.)
Related to the factorial function are the binomial coefficients.
For a non-negative integer and an integer
,
the notation
denotes:
The binomial coefficient
(pronounced `` choose '')
counts the number of subsets of an element set that have size ,
i.e., the number of ways of choosing distinct integers from the
set
.
When analyzing data structures in this book, we want to talk about
the running times of various operations. The exact running times will,
of course, vary from computer to computer and even from run to run on an
individual computer. When we talk about the running time of an operation
we are referring to the number of computer instructions performed during
the operation. Even for simple code, this quantity can be difficult to
compute exactly. Therefore, instead of analyzing running times exactly,
we will use the so-called big-Oh notation: For a function ,
denotes a set of functions,
Thinking graphically, this set consists of the functions where
starts to dominate when is sufficiently large.
We generally use asymptotic notation to simplify functions. For example,
in place of
we can write
.
This is proven as follows:
This demonstrates that the function
is in
the set
using the constants and .
A number of useful shortcuts can be applied when using asymptotic
notation. First:
for any . Second: For any constants ,
These inclusion relations can be multiplied by any positive value,
and they still hold. For example, multiplying by yields:
Continuing in a long and distinguished tradition, we will abuse this
notation by writing things like
when what we really
mean is
. We will also make statements like ``the
running time of this operation is '' when this statement should
be ``the running time of this operation is a member of.''
These shortcuts are mainly to avoid awkward language and to make it
easier to use asymptotic notation within strings of equations.
A particularly strange example of this occurs when we write statements like
Again, this would be more correctly written as
The expression also brings up another issue. Since there is
no variable in this expression, it may not be clear which variable is
getting arbitrarily large. Without context, there is no way to tell.
In the example above, since the only variable in the rest of the equation
is , we can assume that this should be read as
, where .
Big-Oh notation is not new or unique to computer science. It was
used by the number theorist Paul Bachmann as early as 1894, and is
immensely useful for describing the running times of computer algorithms.
Consider the following piece of code:
One execution of this method involves
assignment (
),
comparisons (
),
increments (
),
array offset calculations (
), and
indirect assignments (
).
So we could write this running time as
where , , , , and are constants that depend on the
machine running the code and represent the time to perform assignments,
comparisons, increment operations, array offset calculations, and indirect
assignments, respectively. However, if this expression represents the
running time of two lines of code, then clearly this kind of analysis
will not be tractable to complicated code or algorithms. Using big-Oh
notation, the running time can be simplified to
Not only is this more compact, but it also gives nearly as much
information. The fact that the running time depends on the constants ,
, , , and in the above example means that, in general, it
will not be possible to compare two running times to know which is faster
without knowing the values of these constants. Even if we make the
effort to determine these constants (say, through timing tests), then
our conclusion will only be valid for the machine we run our tests on.
Big-Oh notation allows us to reason at a much higher level, making
it possible to analyze more complicated functions. If two algorithms
have the same big-Oh running time, then we won't know which is faster,
and there may not be a clear winner. One may be faster on one machine,
and the other may be faster on a different machine. However, if the
two algorithms have demonstrably different big-Oh running times, then
we can be certain that the one with the smaller running time will be
faster for large enough values of
.
An example of how big-Oh notation allows us to compare two different
functions is shown in Figure 1.5, which compares the rate
of growth of
versus
. It might be
that is the running time of a complicated linear time algorithm
while is the running time of a considerably simpler algorithm
based on the divide-and-conquer paradigm. This illustrates that,
although
is greater than for small values of
,
the opposite is true for large values of
. Eventually
wins out, by an increasingly wide margin. Analysis using big-Oh notation
told us that this would happen, since
.
Figure 1.5:
Plots of
versus
.
In a few cases, we will use asymptotic notation on functions with more
than one variable. There seems to be no standard for this, but for our
purposes, the following definition is sufficient:
This definition captures the situation we really care about: when the
arguments
make take on large values. This definition
also agrees with the univariate definition of when
is an increasing function of . The reader should be warned that,
although this works for our purposes, other texts may treat multivariate
functions and asymptotic notation differently.
1.3.4 Randomization and Probability
Some of the data structures presented in this book are randomized;
they make random choices that are independent of the data being stored
in them or the operations being performed on them. For this reason,
performing the same set of operations more than once using these
structures could result in different running times. When analyzing these
data structures we are interested in their average or expected
running times.
Formally, the running time of an operation on a randomized data structure
is a random variable, and we want to study its expected value.
For
a discrete random variable taking on values in some countable
universe , the expected value of , denoted by
, is given
by the formula
Here
denotes the probability that the event
occurs. In all of the examples in this book, these
probabilities are only with respect to the random choices made by the
randomized data structure; there is no assumption that the data stored
in the structure, nor the sequence of operations performed on the
data structure, is random.
One of the most important properties of expected values is linearity
of expectation.
For any two random variables and ,
More generally, for any random variables
,
Linearity of expectation allows us to break down complicated random variables (like the left hand sides of the above equations) into sums of simpler random variables (the right hand sides).
A useful trick, that we will use repeatedly, is defining indicator
random variables.
These binary variables are useful when we want to
count something and are best illustrated by an example. Suppose we toss
a fair coin times and we want to know the expected number of times
the coin turns up as heads.
Intuitively, we know the answer is ,
but if we try to prove it using the definition of expected value, we get
This requires that we know enough to calculate that
, and that we know the binomial identities
and
.
Using indicator variables and linearity of expectation makes things
much easier. For each
, define the indicator
random variable
Then
Now,
, so
This is a bit more long-winded, but doesn't require that we know any
magical identities or compute any non-trivial probabilities. Even better,
it agrees with the intuition that we expect half the coins to turn up as
heads precisely because each individual coin turns up as heads with
a probability of .
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.
6.2 BinarySearchTree: An Unbalanced Binary Search Tree
A BinarySearchTree is a special kind of binary tree in which each node,
,
also stores a data value,
, from some total order. The data values in
a binary search tree obey the binary search tree property:
For
a node,
, every data value stored in the subtree rooted at
is less than
and every data value stored in the subtree rooted at
is greater than
. An example of a BinarySearchTree is shown in Figure 6.5.
The binary search tree property is extremely useful because it allows
us to quickly locate a value,
, in a binary search tree. To do this we start
searching for
at the root,
. When examining a node,
, there
are three cases:
If
, then the search proceeds to
;
If
, then the search proceeds to
;
If
, then we have found the node
containing
.
The search terminates when Case 3 occurs or when
. In the
former case, we found
. In the latter case, we conclude that
is not in the binary search tree.
Two examples of searches in a binary search tree are shown in
Figure 6.6. As the second example shows, even if we don't
find
in the tree, we still gain some valuable information. If we
look at the last node,
, at which Case 1 occurred, we see that
is the smallest value in the tree that is greater than
. Similarly,
the last node at which Case 2 occurred contains the largest value in the
tree that is less than
. Therefore, by keeping track of the last
node,
, at which Case 1 occurs, a BinarySearchTree can implement
the
operation that returns the smallest value stored in the
tree that is greater than or equal to
:
Figure 6.6:
An example of (a) a successful search (for ) and (b) an unsuccessful search (for ) in a binary search tree.
To add a new value,
, to a BinarySearchTree, we first search for
. If we find it, then there is no need to insert it. Otherwise,
we store
at a leaf child of the last node,
, encountered during the
search for
. Whether the new node is the left or right child of
depends on the result of comparing
and
.
An example is shown in Figure 6.7. The most time-consuming
part of this process is the initial search for
, which takes an
amount of time proportional to the height of the newly added node
.
In the worst case, this is equal to the height of the BinarySearchTree.
Figure 6.7:
Inserting the value into a binary search tree.
Deleting a value stored in a node,
, of a BinarySearchTree is a
little more difficult. If
is a leaf, then we can just detach
from its parent. Even better: If
has only one child, then we can
splice
from the tree by having
adopt
's child (see
Figure 6.8):
Figure 6.8:
Removing a leaf () or a node with only one child () is easy.
Things get tricky, though, when
has two children. In this case,
the simplest thing to do is to find a node,
, that has less than
two children and such that
can replace
. To maintain
the binary search tree property, the value
should be close to the
value of
. For example, choosing
such that
is the smallest
value greater than
will work. Finding the node
is easy; it is
the smallest value in the subtree rooted at
. This node can
be easily removed because it has no left child (see Figure 6.9).
Figure 6.9:
Deleting a value () from a node,
, with two children is done by replacing
's value with the smallest value in the right subtree of
.
The
,
, and
operations in a
BinarySearchTree each involve following a path from the root of the
tree to some node in the tree. Without knowing more about the shape of
the tree it is difficult to say much about the length of this path,
except that it is less than
, the number of nodes in the tree.
The following (unimpressive) theorem summarizes the performance of the
BinarySearchTree data structure:
Theorem 6..1BinarySearchTree implements the SSet interface and
supports the operations
,
,
and
in
time per operation.
Theorem 6.1 compares poorly with Theorem 4.1, which shows
that the SkiplistSSet structure can implement the SSet interface
with
expected time per operation. The problem with the
BinarySearchTree structure is that it can become unbalanced.
Instead of looking like the tree in Figure 6.5 it can look like a long
chain of
nodes, all but the last having exactly one child.
There are a number of ways of avoiding unbalanced binary search
trees, all of which lead to data structures that have
time operations. In Chapter 7 we show how
expected time operations can be achieved with randomization.
In Chapter 8 we show how
amortized
time operations can be achieved with partial rebuilding operations.
In Chapter 9 we show how
worst-case
time operations can be achieved by simulating a tree that is not binary:
one in which nodes can have up to four children.
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.
9.3 Summary
The following theorem summarizes the performance of the RedBlackTree data structure:
Theorem 9..1A RedBlackTree implements the SSet interface and
supports the operations
,
, and
in
worst-case time per operation.
Not included in the above theorem is the following extra bonus:
Theorem 9..2Beginning with an empty RedBlackTree, any sequence of and
operations results in a total of
time spent during all calls
and
.
We only sketch a proof of Theorem 9.2. By comparing
and
with the algorithms for adding or
removing a leaf in a 2-4 tree, we can convince ourselves that this
property is inherited from a 2-4 tree. In particular, if we can show
that the total time spent splitting, merging, and borrowing in a 2-4
tree is , then this implies Theorem 9.2.
The proof of this theorem for 2-4 trees uses the potential
method
of amortized analysis.9.2 Define the potential of an
internal node
in a 2-4 tree as
and the potential of a 2-4 tree as the sum of the potentials of its nodes.
When a split occurs, it is because a node with four children becomes
two nodes, with two and three children. This means that the overall
potential drops by . When a merge occurs, two nodes that used
to have two children are replaced by one node with three children. The
result is a drop in potential of . Therefore, for every split
or merge, the potential decreases by two.
Next notice that, if we ignore splitting and merging of nodes, there are
only a constant number of nodes whose number of children is changed by
the addition or removal of a leaf. When adding a node, one node has
its number of children increase by one, increasing the potential by
at most three. During the removal of a leaf, one node has its number
of children decrease by one, increasing the potential by at most one,
and two nodes may be involved in a borrowing operation, increasing their
total potential by at most one.
To summarize, each merge and split causes the potential to drop by
at least two. Ignoring merging and splitting, each addition or removal
causes the potential to rise by at most three, and the potential is always
non-negative. Therefore, the number of splits and merges caused by
additions or removals on an initially empty tree is at most .
Theorem 9.2 is a consequence of this analysis and the
correspondence between 2-4 trees and red-black trees.
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 running times of the depth-first-search and breadth-first-search
algorithms are somewhat overstated by the Theorems 12.3 and
12.4. Define
as the number of vertices,
,
of , for which there exists a path from
to
. Define
as the number of edges that have these vertices as their sources.
Then the following theorem is a more precise statement of the running
times of the breadth-first-search and depth-first-search algorithms.
(This more refined statement of the running time is useful in some of
the applications of these algorithms outlined in the exercises.)
Theorem 12..5When given as input a Graph,
, that is implemented using the
AdjacencyLists data structure, the
,
and
algorithms each run in
time.
Breadth-first search seems to have been discovered independently by
Moore [52] and Lee [49] in the contexts of maze exploration
and circuit routing, respectively.
Adjacency-list representations of graphs were presented by
Hopcroft and Tarjan [40] as an alternative to the (then more
common) adjacency-matrix representation. This representation, as well as
depth-first-search, played a major part in the celebrated Hopcroft-Tarjan
planarity testing algorithm
that can determine, in
time, if
a graph can be drawn, in the plane, and in such a way that no pair of
edges cross each other [41].
In the following exercises, an undirected graph is one in which, for
every
and
, the edge
is present if and only if the
edge
is present.
Exercise 12..1
Draw an adjacency list representation and an adjacency matrix
representation of the graph in Figure 12.7.
Figure 12.7:
An example graph.
Exercise 12..2The incidence matrix representation of a graph,
, is an
matrix, , where
Draw the incident matrix representation of the graph in
Figure 12.7.
Design, analyze and implement an incidence matrix representation
of a graph. Be sure to analyze the space, the cost of
,
,
,
,
and
.
Exercise 12..3
Illustrate an execution of the
and
on the graph, ,
in Figure 12.7.
Exercise 12..4Let be an undirected graph. We say is connected if,
for every pair of vertices
and
in , there is a path from
to
(since is undirected, there is also a path from
to
). Show how to test if is connected in
time.
Exercise 12..5Let be an undirected graph. A connected-component labelling
of partitions the vertices of into maximal sets, each of which
forms a connected subgraph. Show how to compute a connected component
labelling of in
time.
Exercise 12..6Let be an undirected graph. A spanning forest of is a
collection of trees, one per component, whose edges are edges of
and whose vertices contain all vertices of . Show how to compute
a spanning forest of of in
time.
Exercise 12..7We say that a graph is strongly-connected if, for every
pair of vertices
and
in , there is a path from
to
. Show how to test if is strongly-connected in
time.
Exercise 12..8
Given a graph and some special vertex
, show how
to compute the length of the shortest path from
to
for every
vertex
.
Exercise 12..9
Give a (simple) example where the
code visits the nodes of a
graph in an order that is different from that of the
code.
Write a version of
that always visits nodes in exactly
the same order as
. (Hint: Just start tracing the execution
of each algorithm on some graph where
is the source of more than
1 edge.)
Exercise 12..10A universal sink in a graph is a vertex that is the target
of
edges and the source of no edges.12.1 Design and implement an algorithm that tests if a graph , represented
as an AdjacencyMatrix, has a universal sink. Your algorithm should
run in
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.
Using the Fetch API
The Fetch API provides a JavaScript interface for making HTTP requests and processing the responses.
With the Fetch API, you make a request by calling fetch(), which is available as a global function in both window and worker contexts. You pass it a Request object or a string containing the URL to fetch, along with an optional argument to configure the request.
The fetch() function returns a Promise which is fulfilled with a Response object representing the server's response. You can then check the request status and extract the body of the response in various formats, including text and JSON, by calling the appropriate method on the response.
Here's a minimal function that uses fetch() to retrieve some JSON data from a server:
js
async function getData() {
const url = "https://example.org/products.json";
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Response status: ${response.status}`);
}
const result = await response.json();
console.log(result);
} catch (error) {
console.error(error.message);
}
}
We declare a string containing the URL and then call fetch(), passing the URL with no extra options.
The fetch() function will reject the promise on some errors, but not if the server responds with an error status like 404: so we also check the response status and throw if it is not OK.
Otherwise, we fetch the response body content as JSON by calling the json() method of Response, and log one of its values. Note that like fetch() itself, json() is asynchronous, as are all the other methods to access the response body content.
In the rest of this page we'll look in more detail at the different stages of this process.
The request body is the payload of the request: it's the thing the client is sending to the server. You cannot include a body with GET requests, but it's useful for requests that send content to the server, such as POST or PUT requests. For example, if you want to upload a file to the server, you might make a POST request and include the file as the request body.
To set a request body, pass it as the body option:
Other objects are converted to strings using their toString() method. For example, you can use a URLSearchParams object to encode form data (see setting headers for more information):
Note that just like response bodies, request bodies are streams, and making the request reads the stream, so if a request contains a body, you can't make it twice:
js
const request = new Request("https://example.org/post", {
method: "POST",
body: JSON.stringify({ username: "example" }),
});
const response1 = await fetch(request);
console.log(response1.status);
// Will throw: "Body has already been consumed."
const response2 = await fetch(request);
console.log(response2.status);
Instead, you would need to create a clone of the request before sending it:
Request headers give the server information about the request: for example, in a POST request, the Content-Type header tells the server the format of the request's body.
To set request headers, assign them to the headers option.
You can pass an object literal here containing header-name: header-value properties:
Alternatively, you can construct a Headers object, add headers to that object using Headers.append(), then assign the Headers object to the headers option:
Compared to using plain objects, the Headers object provides some additional input sanitization. For example, it normalizes header names to lowercase, strips leading and trailing whitespace from header values, and prevents certain headers from being set. Many headers are set automatically by the browser and can't be set by a script: these are called Forbidden request headers. If the mode option is set to no-cors, then the set of permitted headers is further restricted.
GET requests don't have a body, but you can still send data to the server by appending it to the URL as a query string. This is a common way to send form data to the server. You can do this by using URLSearchParams to encode the data, and then appending it to the URL:
js
const params = new URLSearchParams();
params.append("username", "example");
// GET request sent to https://example.org/login?username=example
const response = await fetch(`https://example.org/login?${params}`);
Whether a request can be made cross-origin or not is determined by the value of the RequestInit.mode option. This may take one of three values: cors, same-origin, or no-cors.
For fetch requests the default value of mode is cors, meaning that if the request is cross-origin then it will use the Cross-Origin Resource Sharing (CORS) mechanism. This means that:
if the request is a simple request, then the request will always be sent, but the server must respond with the correct Access-Control-Allow-Origin header or the browser will not share the response with the caller.
if the request is not a simple request, then the browser will send a preflighted request to check that the server understands CORS and allows the request, and the real request will not be sent unless the server responds to the preflighted request with the appropriate CORS headers.
Setting mode to same-origin disallows cross-origin requests completely.
Setting mode to no-cors disables CORS for cross-origin requests. This restricts the headers that may be set, and restricts methods to GET, HEAD, and POST. The response is opaque, meaning that its headers and body are not available to JavaScript. Most of the time a website should not use no-cors: the main application of it is for certain service worker use cases.
See the reference documentation for RequestInit.mode for more details.
In the context of the Fetch API, a credential is an extra piece of data sent along with the request that the server may use to authenticate the user. All the following items are considered to be credentials:
By default, credentials are only included in same-origin requests. To customize this behavior, as well as to control whether the browser respects any Set-Cookie response headers, set the credentials option, which can take one of the following three values:
omit: never send credentials in the request or include credentials in the response.
same-origin (the default): only send and include credentials for same-origin requests.
include: always include credentials, even cross-origin.
Note that if a cookie's SameSite attribute is set to Strict or Lax, then the cookie will not be sent cross-site, even if credentials is set to include.
Including credentials in cross-origin requests can make a site vulnerable to CSRF attacks, so even if credentials is set to include, the server must also agree to their inclusion by including the Access-Control-Allow-Credentials header in its response. Additionally, in this situation the server must explicitly specify the client's origin in the Access-Control-Allow-Origin response header (that is, * is not allowed).
This means that if credentials is set to include and the request is cross-origin, then:
If the request is a simple request, then the request will be sent with credentials, but the server must set the Access-Control-Allow-Credentials and Access-Control-Allow-Origin response headers, or the browser will return a network error to the caller. If the server does set the correct headers, then the response, including credentials, will be delivered to the caller.
If the request is not a simple request, then the browser will send a preflighted request without credentials, and the server must set the Access-Control-Allow-Credentials and Access-Control-Allow-Origin response headers, or the browser will return a network error to the caller. If the server does set the correct headers, then the browser will follow up with the real request, including credentials, and will deliver the real response, including credentials, to the caller.
The Request() constructor takes the same arguments as fetch() itself. This means that instead of passing options into fetch(), you can pass the same options to the Request() constructor, and then pass that object to fetch().
For example, we can make a POST request by passing options into fetch() using code like this:
If the request is aborted after the fetch() call has been fulfilled but before the response body has been read, then attempting to read the response body will reject with an AbortError exception.
js
async function get() {
const controller = new AbortController();
const request = new Request("https://example.org/get", {
signal: controller.signal,
});
const response = await fetch(request);
controller.abort();
// The next line will throw `AbortError`
const text = await response.text();
console.log(text);
}
As soon as the browser has received the response status and headers from the server (and potentially before the response body itself has been received), the promise returned by fetch() is fulfilled with a Response object.
The promise returned by fetch() will reject on some errors, such as a network error or a bad scheme. However, if the server responds with an error like 404, then fetch() fulfills with a Response, so we have to check the status before we can read the response body.
The Response.status property tells us the numerical status code, and the Response.ok property returns true if the status is in the 200 range.
A common pattern is to check the value of ok and throw if it is false:
Just like the request, the response has a headers property which is a Headers object, and this contains any response headers that are exposed to scripts, subject to the exclusions made based on the response type.
A common use case for this is to check the content type before trying to read the body:
js
async function fetchJSON(request) {
try {
const response = await fetch(request);
const contentType = response.headers.get("content-type");
if (!contentType || !contentType.includes("application/json")) {
throw new TypeError("Oops, we haven't got JSON!");
}
// Otherwise, we can read the body as JSON
} catch (error) {
console.error("Error:", error);
}
}
The method will throw an exception if the response body is not in the appropriate format: for example, if you call json() on a response that can't be parsed as JSON.
Request and response bodies are actually ReadableStream objects, and whenever you read them, you're streaming the content. This is good for memory efficiency, because the browser doesn't have to buffer the entire response in memory before the caller retrieves it using a method like json().
This also means that the caller can process the content incrementally as it is received.
For example, consider a GET request that fetches a large text file and processes it in some way, or displays it to the user:
js
const url = "https://www.example.org/a-large-file.txt";
async function fetchText(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Response status: ${response.status}`);
}
const text = await response.text();
console.log(text);
} catch (e) {
console.error(e);
}
}
If we use Response.text(), as above, we must wait until the whole file has been received before we can process any of it.
If we stream the response instead, we can process chunks of the body as they are received from the network:
js
const url = "https://www.example.org/a-large-file.txt";
async function fetchTextAsStream(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Response status: ${response.status}`);
}
const stream = response.body.pipeThrough(new TextDecoderStream());
for await (const value of stream) {
console.log(value);
}
} catch (e) {
console.error(e);
}
}
In this example, we iterate asynchronously over the stream, processing each chunk as it arrives.
Note that when you access the body directly like this, you get the raw bytes of the response and must transform it yourself. In this case we call ReadableStream.pipeThrough() to pipe the response through a TextDecoderStream, which decodes the UTF-8-encoded body data as text.
In the example below, we fetch a text resource and process it line by line, using a regular expression to look for line endings. For simplicity, we assume the text is UTF-8, and don't handle fetch errors:
js
async function* makeTextFileLineIterator(fileURL) {
const response = await fetch(fileURL);
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
let { value: chunk = "", done: readerDone } = await reader.read();
const newline = /\r?\n/g;
let startIndex = 0;
while (true) {
const result = newline.exec(chunk);
if (!result) {
if (readerDone) break;
const remainder = chunk.slice(startIndex);
({ value: chunk, done: readerDone } = await reader.read());
chunk = remainder + (chunk || "");
startIndex = newline.lastIndex = 0;
continue;
}
yield chunk.substring(startIndex, result.index);
startIndex = newline.lastIndex;
}
if (startIndex < chunk.length) {
// Last line didn't end in a newline char
yield chunk.substring(startIndex);
}
}
async function run(urlOfFile) {
for await (const line of makeTextFileLineIterator(urlOfFile)) {
processLine(line);
}
}
function processLine(line) {
console.log(line);
}
run("https://www.example.org/a-large-file.txt");
This is a common pattern when implementing an offline cache with service workers. The service worker wants to return the response to the app, but also to cache the response. So it clones the response, returns the original, and caches the clone:
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 results of two queries can be combined using the set operations union, intersection, and difference. The syntax is
query1 UNION [ALL] query2query1 INTERSECT [ALL] query2query1 EXCEPT [ALL] query2
where query1 and query2 are queries that can use any of the features discussed up to this point.
UNION effectively appends the result of query2 to the result of query1 (although there is no guarantee that this is the order in which the rows are actually returned). Furthermore, it eliminates duplicate rows from its result, in the same way as DISTINCT, unless UNION ALL is used.
INTERSECT returns all rows that are both in the result of query1 and in the result of query2. Duplicate rows are eliminated unless INTERSECT ALL is used.
EXCEPT returns all rows that are in the result of query1 but not in the result of query2. (This is sometimes called the difference between two queries.) Again, duplicates are eliminated unless EXCEPT ALL is used.
In order to calculate the union, intersection, or difference of two queries, the two queries must be “union compatible”, which means that they return the same number of columns and the corresponding columns have compatible data types, as described in Section 10.5.
Set operations can be combined, for example
query1 UNION query2 EXCEPT query3
which is equivalent to
(query1 UNION query2) EXCEPT query3
As shown here, you can use parentheses to control the order of evaluation. Without parentheses, UNION and EXCEPT associate left-to-right, but INTERSECT binds more tightly than those two operators. Thus
query1 UNION query2 INTERSECT query3
means
query1 UNION (query2 INTERSECT query3)
You can also surround an individual query with parentheses. This is important if the query needs to use any of the clauses discussed in following sections, such as LIMIT. Without parentheses, you'll get a syntax error, or else the clause will be understood as applying to the output of the set operation rather than one of its inputs. For example,
SELECT a FROM b UNION SELECT x FROM y LIMIT 10
is accepted, but it means
(SELECT a FROM b UNION SELECT x FROM y) LIMIT 10
not
SELECT a FROM b UNION (SELECT x FROM y LIMIT 10)
13.2. Transaction Isolation #
Assigned source reading · The PostgreSQL Global Development Group and The Regents of the University of California
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 SQL standard defines four levels of transaction isolation. The most strict is Serializable, which is defined by the standard in a paragraph which says that any concurrent execution of a set of Serializable transactions is guaranteed to produce the same effect as running them one at a time in some order. The other three levels are defined in terms of phenomena, resulting from interaction between concurrent transactions, which must not occur at each level. The standard notes that due to the definition of Serializable, none of these phenomena are possible at that level. (This is hardly surprising -- if the effect of the transactions must be consistent with having been run one at a time, how could you see any phenomena caused by interactions?)
The phenomena which are prohibited at various levels are:
dirty read
A transaction reads data written by a concurrent uncommitted transaction.
nonrepeatable read
A transaction re-reads data it has previously read and finds that data has been modified by another transaction (that committed since the initial read).
phantom read
A transaction re-executes a query returning a set of rows that satisfy a search condition and finds that the set of rows satisfying the condition has changed due to another recently-committed transaction.
serialization anomaly
The result of successfully committing a group of transactions is inconsistent with all possible orderings of running those transactions one at a time.
The SQL standard and PostgreSQL-implemented transaction isolation levels are described in Table 13.1.
Table 13.1. Transaction Isolation Levels
Isolation Level
Dirty Read
Nonrepeatable Read
Phantom Read
Serialization Anomaly
Read uncommitted
Allowed, but not in PG
Possible
Possible
Possible
Read committed
Not possible
Possible
Possible
Possible
Repeatable read
Not possible
Not possible
Allowed, but not in PG
Possible
Serializable
Not possible
Not possible
Not possible
Not possible
In PostgreSQL, you can request any of the four standard transaction isolation levels, but internally only three distinct isolation levels are implemented, i.e., PostgreSQL's Read Uncommitted mode behaves like Read Committed. This is because it is the only sensible way to map the standard isolation levels to PostgreSQL's multiversion concurrency control architecture.
The table also shows that PostgreSQL's Repeatable Read implementation does not allow phantom reads. This is acceptable under the SQL standard because the standard specifies which anomalies must not occur at certain isolation levels; higher guarantees are acceptable. The behavior of the available isolation levels is detailed in the following subsections.
To set the transaction isolation level of a transaction, use the command SET TRANSACTION.
Important
Some PostgreSQL data types and functions have special rules regarding transactional behavior. In particular, changes made to a sequence (and therefore the counter of a column declared using serial) are immediately visible to all other transactions and are not rolled back if the transaction that made the changes aborts. See Section 9.17 and Section 8.1.4.
Read Committed is the default isolation level in PostgreSQL. When a transaction uses this isolation level, a SELECT query (without a FOR UPDATE/SHARE clause) sees only data committed before the query began; it never sees either uncommitted data or changes committed by concurrent transactions during the query's execution. In effect, a SELECT query sees a snapshot of the database as of the instant the query begins to run. However, SELECT does see the effects of previous updates executed within its own transaction, even though they are not yet committed. Also note that two successive SELECT commands can see different data, even though they are within a single transaction, if other transactions commit changes after the first SELECT starts and before the second SELECT starts.
UPDATE, DELETE, SELECT FOR UPDATE, and SELECT FOR SHARE commands behave the same as SELECT in terms of searching for target rows: they will only find target rows that were committed as of the command start time. However, such a target row might have already been updated (or deleted or locked) by another concurrent transaction by the time it is found. In this case, the would-be updater will wait for the first updating transaction to commit or roll back (if it is still in progress). If the first updater rolls back, then its effects are negated and the second updater can proceed with updating the originally found row. If the first updater commits, the second updater will ignore the row if the first updater deleted it, otherwise it will attempt to apply its operation to the updated version of the row. The search condition of the command (the WHERE clause) is re-evaluated to see if the updated version of the row still matches the search condition. If so, the second updater proceeds with its operation using the updated version of the row. In the case of SELECT FOR UPDATE and SELECT FOR SHARE, this means it is the updated version of the row that is locked and returned to the client.
INSERT with an ON CONFLICT DO UPDATE clause behaves similarly. In Read Committed mode, each row proposed for insertion will either insert or update. Unless there are unrelated errors, one of those two outcomes is guaranteed. If a conflict originates in another transaction whose effects are not yet visible to the INSERT, the UPDATE clause will affect that row, even though possibly no version of that row is conventionally visible to the command.
INSERT with an ON CONFLICT DO NOTHING clause may have insertion not proceed for a row due to the outcome of another transaction whose effects are not visible to the INSERT snapshot. Again, this is only the case in Read Committed mode.
MERGE allows the user to specify various combinations of INSERT, UPDATE and DELETE subcommands. A MERGE command with both INSERT and UPDATE subcommands looks similar to INSERT with an ON CONFLICT DO UPDATE clause but does not guarantee that either INSERT or UPDATE will occur. If MERGE attempts an UPDATE or DELETE and the row is concurrently updated but the join condition still passes for the current target and the current source tuple, then MERGE will behave the same as the UPDATE or DELETE commands and perform its action on the updated version of the row. However, because MERGE can specify several actions and they can be conditional, the conditions for each action are re-evaluated on the updated version of the row, starting from the first action, even if the action that had originally matched appears later in the list of actions. On the other hand, if the row is concurrently updated so that the join condition fails, then MERGE will evaluate the command's NOT MATCHED BY SOURCE and NOT MATCHED [BY TARGET] actions next, and execute the first one of each kind that succeeds. If the row is concurrently deleted, then MERGE will evaluate the command's NOT MATCHED [BY TARGET] actions, and execute the first one that succeeds. If MERGE attempts an INSERT and a unique index is present and a duplicate row is concurrently inserted, then a uniqueness violation error is raised; MERGE does not attempt to avoid such errors by restarting evaluation of MATCHED conditions.
Because of the above rules, it is possible for an updating command to see an inconsistent snapshot: it can see the effects of concurrent updating commands on the same rows it is trying to update, but it does not see effects of those commands on other rows in the database. This behavior makes Read Committed mode unsuitable for commands that involve complex search conditions; however, it is just right for simpler cases. For example, consider transferring $100 from one account to another:
BEGIN;
UPDATE accounts SET balance = balance + 100.00 WHERE acctnum = 12345;
UPDATE accounts SET balance = balance - 100.00 WHERE acctnum = 7534;
COMMIT;
If another transaction concurrently tries to change the balance of account 7534, we clearly want the second statement to start with the updated version of the account's row. Because each command is affecting only a predetermined row, letting it see the updated version of the row does not create any troublesome inconsistency.
More complex usage can produce undesirable results in Read Committed mode. For example, consider a DELETE command operating on data that is being both added and removed from its restriction criteria by another command, e.g., assume website is a two-row table with website.hits equaling 9 and 10:
BEGIN;
UPDATE website SET hits = hits + 1;
-- run from another session: DELETE FROM website WHERE hits = 10;
COMMIT;
The DELETE will have no effect even though there is a website.hits = 10 row before and after the UPDATE. This occurs because the pre-update row value 9 is skipped, and when the UPDATE completes and DELETE obtains a lock, the new row value is no longer 10 but 11, which no longer matches the criteria.
Because Read Committed mode starts each command with a new snapshot that includes all transactions committed up to that instant, subsequent commands in the same transaction will see the effects of the committed concurrent transaction in any case. The point at issue above is whether or not a single command sees an absolutely consistent view of the database.
The partial transaction isolation provided by Read Committed mode is adequate for many applications, and this mode is fast and simple to use; however, it is not sufficient for all cases. Applications that do complex queries and updates might require a more rigorously consistent view of the database than Read Committed mode provides.
The Repeatable Read isolation level only sees data committed before the transaction began; it never sees either uncommitted data or changes committed by concurrent transactions during the transaction's execution. (However, each query does see the effects of previous updates executed within its own transaction, even though they are not yet committed.) This is a stronger guarantee than is required by the SQL standard for this isolation level, and prevents all of the phenomena described in Table 13.1 except for serialization anomalies. As mentioned above, this is specifically allowed by the standard, which only describes the minimum protections each isolation level must provide.
This level is different from Read Committed in that a query in a repeatable read transaction sees a snapshot as of the start of the first non-transaction-control statement in the transaction, not as of the start of the current statement within the transaction. Thus, successive SELECT commands within a single transaction see the same data, i.e., they do not see changes made by other transactions that committed after their own transaction started.
Applications using this level must be prepared to retry transactions due to serialization failures.
UPDATE, DELETE, MERGE, SELECT FOR UPDATE, and SELECT FOR SHARE commands behave the same as SELECT in terms of searching for target rows: they will only find target rows that were committed as of the transaction start time. However, such a target row might have already been updated (or deleted or locked) by another concurrent transaction by the time it is found. In this case, the repeatable read transaction will wait for the first updating transaction to commit or roll back (if it is still in progress). If the first updater rolls back, then its effects are negated and the repeatable read transaction can proceed with updating the originally found row. But if the first updater commits (and actually updated or deleted the row, not just locked it) then the repeatable read transaction will be rolled back with the message
ERROR: could not serialize access due to concurrent update
because a repeatable read transaction cannot modify or lock rows changed by other transactions after the repeatable read transaction began.
When an application receives this error message, it should abort the current transaction and retry the whole transaction from the beginning. The second time through, the transaction will see the previously-committed change as part of its initial view of the database, so there is no logical conflict in using the new version of the row as the starting point for the new transaction's update.
Note that only updating transactions might need to be retried; read-only transactions will never have serialization conflicts.
The Repeatable Read mode provides a rigorous guarantee that each transaction sees a completely stable view of the database. However, this view will not necessarily always be consistent with some serial (one at a time) execution of concurrent transactions of the same level. For example, even a read-only transaction at this level may see a control record updated to show that a batch has been completed but not see one of the detail records which is logically part of the batch because it read an earlier revision of the control record. Attempts to enforce business rules by transactions running at this isolation level are not likely to work correctly without careful use of explicit locks to block conflicting transactions.
The Repeatable Read isolation level is implemented using a technique known in academic database literature and in some other database products as Snapshot Isolation. Differences in behavior and performance may be observed when compared with systems that use a traditional locking technique that reduces concurrency. Some other systems may even offer Repeatable Read and Snapshot Isolation as distinct isolation levels with different behavior. The permitted phenomena that distinguish the two techniques were not formalized by database researchers until after the SQL standard was developed, and are outside the scope of this manual. For a full treatment, please see [berenson95].
Note
Prior to PostgreSQL version 9.1, a request for the Serializable transaction isolation level provided exactly the same behavior described here. To retain the legacy Serializable behavior, Repeatable Read should now be requested.
The Serializable isolation level provides the strictest transaction isolation. This level emulates serial transaction execution for all committed transactions; as if transactions had been executed one after another, serially, rather than concurrently. However, like the Repeatable Read level, applications using this level must be prepared to retry transactions due to serialization failures. In fact, this isolation level works exactly the same as Repeatable Read except that it also monitors for conditions which could make execution of a concurrent set of serializable transactions behave in a manner inconsistent with all possible serial (one at a time) executions of those transactions. This monitoring does not introduce any blocking beyond that present in repeatable read, but there is some overhead to the monitoring, and detection of the conditions which could cause a serialization anomaly will trigger a serialization failure.
As an example, consider a table mytab, initially containing:
class | value
-------+-------
1 | 10
1 | 20
2 | 100
2 | 200
Suppose that serializable transaction A computes:
SELECT SUM(value) FROM mytab WHERE class = 1;
and then inserts the result (30) as the value in a new row with class= 2. Concurrently, serializable transaction B computes:
SELECT SUM(value) FROM mytab WHERE class = 2;
and obtains the result 300, which it inserts in a new row with class= 1. Then both transactions try to commit. If either transaction were running at the Repeatable Read isolation level, both would be allowed to commit; but since there is no serial order of execution consistent with the result, using Serializable transactions will allow one transaction to commit and will roll the other back with this message:
ERROR: could not serialize access due to read/write dependencies among transactions
This is because if A had executed before B, B would have computed the sum 330, not 300, and similarly the other order would have resulted in a different sum computed by A.
When relying on Serializable transactions to prevent anomalies, it is important that any data read from a permanent user table not be considered valid until the transaction which read it has successfully committed. This is true even for read-only transactions, except that data read within a deferrable read-only transaction is known to be valid as soon as it is read, because such a transaction waits until it can acquire a snapshot guaranteed to be free from such problems before starting to read any data. In all other cases applications must not depend on results read during a transaction that later aborted; instead, they should retry the transaction until it succeeds.
To guarantee true serializability PostgreSQL uses predicate locking, which means that it keeps locks which allow it to determine when a write would have had an impact on the result of a previous read from a concurrent transaction, had it run first. In PostgreSQL these locks do not cause any blocking and therefore can not play any part in causing a deadlock. They are used to identify and flag dependencies among concurrent Serializable transactions which in certain combinations can lead to serialization anomalies. In contrast, a Read Committed or Repeatable Read transaction which wants to ensure data consistency may need to take out a lock on an entire table, which could block other users attempting to use that table, or it may use SELECT FOR UPDATE or SELECT FOR SHARE which not only can block other transactions but cause disk access.
Predicate locks in PostgreSQL, like in most other database systems, are based on data actually accessed by a transaction. These will show up in the pg_locks system view with a mode of SIReadLock. The particular locks acquired during execution of a query will depend on the plan used by the query, and multiple finer-grained locks (e.g., tuple locks) may be combined into fewer coarser-grained locks (e.g., page locks) during the course of the transaction to prevent exhaustion of the memory used to track the locks. A READ ONLY transaction may be able to release its SIRead locks before completion, if it detects that no conflicts can still occur which could lead to a serialization anomaly. In fact, READ ONLY transactions will often be able to establish that fact at startup and avoid taking any predicate locks. If you explicitly request a SERIALIZABLE READ ONLY DEFERRABLE transaction, it will block until it can establish this fact. (This is the only case where Serializable transactions block but Repeatable Read transactions don't.) On the other hand, SIRead locks often need to be kept past transaction commit, until overlapping read write transactions complete.
Consistent use of Serializable transactions can simplify development. The guarantee that any set of successfully committed concurrent Serializable transactions will have the same effect as if they were run one at a time means that if you can demonstrate that a single transaction, as written, will do the right thing when run by itself, you can have confidence that it will do the right thing in any mix of Serializable transactions, even without any information about what those other transactions might do, or it will not successfully commit. It is important that an environment which uses this technique have a generalized way of handling serialization failures (which always return with an SQLSTATE value of '40001'), because it will be very hard to predict exactly which transactions might contribute to the read/write dependencies and need to be rolled back to prevent serialization anomalies. The monitoring of read/write dependencies has a cost, as does the restart of transactions which are terminated with a serialization failure, but balanced against the cost and blocking involved in use of explicit locks and SELECT FOR UPDATE or SELECT FOR SHARE, Serializable transactions are the best performance choice for some environments.
While PostgreSQL's Serializable transaction isolation level only allows concurrent transactions to commit if it can prove there is a serial order of execution that would produce the same effect, it doesn't always prevent errors from being raised that would not occur in true serial execution. In particular, it is possible to see unique constraint violations caused by conflicts with overlapping Serializable transactions even after explicitly checking that the key isn't present before attempting to insert it. This can be avoided by making sure that all Serializable transactions that insert potentially conflicting keys explicitly check if they can do so first. For example, imagine an application that asks the user for a new key and then checks that it doesn't exist already by trying to select it first, or generates a new key by selecting the maximum existing key and adding one. If some Serializable transactions insert new keys directly without following this protocol, unique constraints violations might be reported even in cases where they could not occur in a serial execution of the concurrent transactions.
For optimal performance when relying on Serializable transactions for concurrency control, these issues should be considered:
Declare transactions as READ ONLY when possible.
Control the number of active connections, using a connection pool if needed. This is always an important performance consideration, but it can be particularly important in a busy system using Serializable transactions.
Don't put more into a single transaction than needed for integrity purposes.
Don't leave connections dangling “idle in transaction” longer than necessary. The configuration parameter idle_in_transaction_session_timeout may be used to automatically disconnect lingering sessions.
Eliminate explicit locks, SELECT FOR UPDATE, and SELECT FOR SHARE where no longer needed due to the protections automatically provided by Serializable transactions.
When the system is forced to combine multiple page-level predicate locks into a single relation-level predicate lock because the predicate lock table is short of memory, an increase in the rate of serialization failures may occur. You can avoid this by increasing max_pred_locks_per_transaction, max_pred_locks_per_relation, and/or max_pred_locks_per_page.
A sequential scan will always necessitate a relation-level predicate lock. This can result in an increased rate of serialization failures. It may be helpful to encourage the use of index scans by reducing random_page_cost and/or increasing cpu_tuple_cost. Be sure to weigh any decrease in transaction rollbacks and restarts against any overall change in query execution time.
The Serializable isolation level is implemented using a technique known in academic database literature as Serializable Snapshot Isolation, which builds on Snapshot Isolation by adding checks for serialization anomalies. Some differences in behavior and performance may be observed when compared with other systems that use a traditional locking technique. Please see [ports12] for detailed information.
2.3. Linear Algebra Open the notebook in SageMaker Studio Lab
Assigned source reading · Aston Zhang, Zachary C. Lipton, Mu Li and Alexander J. Smola
Dive into Deep Learning — the authors and contributors; text CC BY-SA 4.0; accompanying code under its separately stated license.
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.3. Linear Algebra
Open the notebook in SageMaker Studio Lab
By now, we can load datasets into tensors and manipulate these tensors
with basic mathematical operations. To start building sophisticated
models, we will also need a few tools from linear algebra. This section
offers a gentle introduction to the most essential concepts, starting
from scalar arithmetic and ramping up to matrix multiplication.
importtorch
2.3.1. Scalars
Most everyday mathematics consists of manipulating numbers one at a
time. Formally, we call these values scalars. For example, the
temperature in Palo Alto is a balmy \(72\) degrees Fahrenheit. If
you wanted to convert the temperature to Celsius you would evaluate the
expression \(c = \frac{5}{9}(f - 32)\), setting \(f\) to
\(72\). In this equation, the values \(5\), \(9\), and
\(32\) are constant scalars. The variables \(c\) and \(f\)
in general represent unknown scalars.
We denote scalars by ordinary lower-cased letters (e.g., \(x\),
\(y\), and \(z\)) and the space of all (continuous)
real-valued scalars by \(\mathbb{R}\). For expedience, we will
skip past rigorous definitions of spaces: just remember that the
expression \(x \in \mathbb{R}\) is a formal way to say that
\(x\) is a real-valued scalar. The symbol \(\in\) (pronounced
“in”) denotes membership in a set. For example,
\(x, y \in \{0, 1\}\) indicates that \(x\) and \(y\) are
variables that can only take values \(0\) or \(1\).
Scalars are implemented as tensors that contain only one element. Below,
we assign two scalars and perform the familiar addition, multiplication,
division, and exponentiation operations.
For current purposes, you can think of a vector as a fixed-length array
of scalars. As with their code counterparts, we call these scalars the
elements of the vector (synonyms include entries and components).
When vectors represent examples from real-world datasets, their values
hold some real-world significance. For example, if we were training a
model to predict the risk of a loan defaulting, we might associate each
applicant with a vector whose components correspond to quantities like
their income, length of employment, or number of previous defaults. If
we were studying the risk of heart attack, each vector might represent a
patient and its components might correspond to their most recent vital
signs, cholesterol levels, minutes of exercise per day, etc. We denote
vectors by bold lowercase letters, (e.g., \(\mathbf{x}\),
\(\mathbf{y}\), and \(\mathbf{z}\)).
Vectors are implemented as \(1^{\textrm{st}}\)-order tensors. In
general, such tensors can have arbitrary lengths, subject to memory
limitations. Caution: in Python, as in most programming languages,
vector indices start at \(0\), also known as zero-based indexing,
whereas in linear algebra subscripts begin at \(1\) (one-based
indexing).
x=torch.arange(3)x
tensor([0,1,2])
We can refer to an element of a vector by using a subscript. For
example, \(x_2\) denotes the second element of \(\mathbf{x}\).
Since \(x_2\) is a scalar, we do not bold it. By default, we
visualize vectors by stacking their elements vertically.
Here \(x_1, \ldots, x_n\) are elements of the vector. Later on, we
will distinguish between such column vectors and row vectors whose
elements are stacked horizontally. Recall that we access a tensor’s
elements via indexing.
x[2]
tensor(2)
To indicate that a vector contains \(n\) elements, we write
\(\mathbf{x} \in \mathbb{R}^n\). Formally, we call \(n\) the
dimensionality of the vector. In code, this corresponds to the
tensor’s length, accessible via Python’s built-in len function.
len(x)
3
We can also access the length via the shape attribute. The shape is
a tuple that indicates a tensor’s length along each axis. Tensors with
just one axis have shapes with just one element.
x.shape
torch.Size([3])
Oftentimes, the word “dimension” gets overloaded to mean both the number
of axes and the length along a particular axis. To avoid this confusion,
we use order to refer to the number of axes and dimensionality
exclusively to refer to the number of components.
2.3.3. Matrices
Just as scalars are \(0^{\textrm{th}}\)-order tensors and vectors
are \(1^{\textrm{st}}\)-order tensors, matrices are
\(2^{\textrm{nd}}\)-order tensors. We denote matrices by bold
capital letters (e.g., \(\mathbf{X}\), \(\mathbf{Y}\), and
\(\mathbf{Z}\)), and represent them in code by tensors with two
axes. The expression \(\mathbf{A} \in \mathbb{R}^{m \times n}\)
indicates that a matrix \(\mathbf{A}\) contains \(m \times n\)
real-valued scalars, arranged as \(m\) rows and \(n\) columns.
When \(m = n\), we say that a matrix is square. Visually, we can
illustrate any matrix as a table. To refer to an individual element, we
subscript both the row and column indices, e.g., \(a_{ij}\) is the
value that belongs to \(\mathbf{A}\)’s \(i^{\textrm{th}}\) row
and \(j^{\textrm{th}}\) column:
In code, we represent a matrix
\(\mathbf{A} \in \mathbb{R}^{m \times n}\) by a
\(2^{\textrm{nd}}\)-order tensor with shape (\(m\), \(n\)).
We can convert any appropriately sized \(m \times n\) tensor into an
\(m \times n\) matrix by passing the desired shape to reshape:
A=torch.arange(6).reshape(3,2)A
tensor([[0,1],[2,3],[4,5]])
Sometimes we want to flip the axes. When we exchange a matrix’s rows and
columns, the result is called its transpose. Formally, we signify a
matrix \(\mathbf{A}\)’s transpose by \(\mathbf{A}^\top\) and
if \(\mathbf{B} = \mathbf{A}^\top\), then \(b_{ij} = a_{ji}\)
for all \(i\) and \(j\). Thus, the transpose of an
\(m \times n\) matrix is an \(n \times m\) matrix:
In code, we can access any matrix’s transpose as follows:
A.T
tensor([[0,2,4],[1,3,5]])
Symmetric matrices are the subset of square matrices that are equal to
their own transposes: \(\mathbf{A} = \mathbf{A}^\top\). The
following matrix is symmetric:
Matrices are useful for representing datasets. Typically, rows
correspond to individual records and columns correspond to distinct
attributes.
2.3.4. Tensors
While you can go far in your machine learning journey with only scalars,
vectors, and matrices, eventually you may need to work with higher-order
tensors. Tensors give us a generic way of describing extensions to
\(n^{\textrm{th}}\)-order arrays. We call software objects of the
tensor class “tensors” precisely because they too can have arbitrary
numbers of axes. While it may be confusing to use the word tensor for
both the mathematical object and its realization in code, our meaning
should usually be clear from context. We denote general tensors by
capital letters with a special font face (e.g., \(\mathsf{X}\),
\(\mathsf{Y}\), and \(\mathsf{Z}\)) and their indexing mechanism
(e.g., \(x_{ijk}\) and \([\mathsf{X}]_{1, 2i-1, 3}\)) follows
naturally from that of matrices.
Tensors will become more important when we start working with images.
Each image arrives as a \(3^{\textrm{rd}}\)-order tensor with axes
corresponding to the height, width, and channel. At each spatial
location, the intensities of each color (red, green, and blue) are
stacked along the channel. Furthermore, a collection of images is
represented in code by a \(4^{\textrm{th}}\)-order tensor, where
distinct images are indexed along the first axis. Higher-order tensors
are constructed, as were vectors and matrices, by growing the number of
shape components.
Scalars, vectors, matrices, and higher-order tensors all have some handy
properties. For example, elementwise operations produce outputs that
have the same shape as their operands.
A=torch.arange(6,dtype=torch.float32).reshape(2,3)B=A.clone()# Assign a copy of A to B by allocating new memoryA,A+B
The elementwise product of two matrices is called their Hadamard
product (denoted \(\odot\)). We can spell out the entries of the
Hadamard product of two matrices
\(\mathbf{A}, \mathbf{B} \in \mathbb{R}^{m \times n}\):
Adding or multiplying a scalar and a tensor produces a result with the
same shape as the original tensor. Here, each element of the tensor is
added to (or multiplied by) the scalar.
Often, we wish to calculate the sum of a tensor’s elements. To express
the sum of the elements in a vector \(\mathbf{x}\) of length
\(n\), we write \(\sum_{i=1}^n x_i\). There is a simple function
for it:
x=torch.arange(3,dtype=torch.float32)x,x.sum()
(tensor([0.,1.,2.]),tensor(3.))
To express sums over the elements of tensors of arbitrary shape, we
simply sum over all its axes. For example, the sum of the elements of an
\(m \times n\) matrix \(\mathbf{A}\) could be written
\(\sum_{i=1}^{m} \sum_{j=1}^{n} a_{ij}\).
A.shape,A.sum()
(torch.Size([2,3]),tensor(15.))
By default, invoking the sum function reduces a tensor along all of
its axes, eventually producing a scalar. Our libraries also allow us to
specify the axes along which the tensor should be reduced. To sum over
all elements along the rows (axis 0), we specify axis=0 in sum.
Since the input matrix reduces along axis 0 to generate the output
vector, this axis is missing from the shape of the output.
A.shape,A.sum(axis=0).shape
(torch.Size([2,3]),torch.Size([3]))
Specifying axis=1 will reduce the column dimension (axis 1) by
summing up elements of all the columns.
A.shape,A.sum(axis=1).shape
(torch.Size([2,3]),torch.Size([2]))
Reducing a matrix along both rows and columns via summation is
equivalent to summing up all the elements of the matrix.
A.sum(axis=[0,1])==A.sum()# Same as A.sum()
tensor(True)
A related quantity is the mean, also called the average. We
calculate the mean by dividing the sum by the total number of elements.
Because computing the mean is so common, it gets a dedicated library
function that works analogously to sum.
A.mean(),A.sum()/A.numel()
(tensor(2.5000),tensor(2.5000))
Likewise, the function for calculating the mean can also reduce a tensor
along specific axes.
Sometimes it can be useful to keep the number of axes unchanged when
invoking the function for calculating the sum or mean. This matters when
we want to use the broadcast mechanism.
For instance, since sum_A keeps its two axes after summing each row,
we can divide A by sum_A with broadcasting to create a matrix
where each row sums up to \(1\).
If we want to calculate the cumulative sum of elements of A along
some axis, say axis=0 (row by row), we can call the cumsum
function. By design, this function does not reduce the input tensor
along any axis.
A.cumsum(axis=0)
tensor([[0.,1.,2.],[3.,5.,7.]])
2.3.8. Dot Products
So far, we have only performed elementwise operations, sums, and
averages. And if this was all we could do, linear algebra would not
deserve its own section. Fortunately, this is where things get more
interesting. One of the most fundamental operations is the dot product.
Given two vectors \(\mathbf{x}, \mathbf{y} \in \mathbb{R}^d\), their
dot product\(\mathbf{x}^\top \mathbf{y}\) (also known as inner
product, \(\langle \mathbf{x}, \mathbf{y} \rangle\)) is a sum over
the products of the elements at the same position:
\(\mathbf{x}^\top \mathbf{y} = \sum_{i=1}^{d} x_i y_i\).
Equivalently, we can calculate the dot product of two vectors by
performing an elementwise multiplication followed by a sum:
torch.sum(x*y)
tensor(3.)
Dot products are useful in a wide range of contexts. For example, given
some set of values, denoted by a vector
\(\mathbf{x} \in \mathbb{R}^n\), and a set of weights, denoted by
\(\mathbf{w} \in \mathbb{R}^n\), the weighted sum of the values in
\(\mathbf{x}\) according to the weights \(\mathbf{w}\) could be
expressed as the dot product \(\mathbf{x}^\top \mathbf{w}\). When
the weights are nonnegative and sum to \(1\), i.e.,
\(\left(\sum_{i=1}^{n} {w_i} = 1\right)\), the dot product expresses
a weighted average. After normalizing two vectors to have unit length,
the dot products express the cosine of the angle between them. Later in
this section, we will formally introduce this notion of length.
2.3.9. Matrix–Vector Products
Now that we know how to calculate dot products, we can begin to
understand the product between an \(m \times n\) matrix
\(\mathbf{A}\) and an \(n\)-dimensional vector
\(\mathbf{x}\). To start off, we visualize our matrix in terms of
its row vectors
where each \(\mathbf{a}^\top_{i} \in \mathbb{R}^n\) is a row vector
representing the \(i^\textrm{th}\) row of the matrix
\(\mathbf{A}\).
The matrix–vector product \(\mathbf{A}\mathbf{x}\) is simply a
column vector of length \(m\), whose \(i^\textrm{th}\) element
is the dot product \(\mathbf{a}^\top_i \mathbf{x}\):
We can think of multiplication with a matrix
\(\mathbf{A}\in \mathbb{R}^{m \times n}\) as a transformation that
projects vectors from \(\mathbb{R}^{n}\) to \(\mathbb{R}^{m}\).
These transformations are remarkably useful. For example, we can
represent rotations as multiplications by certain square matrices.
Matrix–vector products also describe the key calculation involved in
computing the outputs of each layer in a neural network given the
outputs from the previous layer.
To express a matrix–vector product in code, we use the mv function.
Note that the column dimension of A (its length along axis 1) must
be the same as the dimension of x (its length). Python has a
convenience operator @ that can execute both matrix–vector and
matrix–matrix products (depending on its arguments). Thus we can write
A@x.
Let \(\mathbf{a}^\top_{i} \in \mathbb{R}^k\) denote the row vector
representing the \(i^\textrm{th}\) row of the matrix
\(\mathbf{A}\) and let \(\mathbf{b}_{j} \in \mathbb{R}^k\)
denote the column vector from the \(j^\textrm{th}\) column of the
matrix \(\mathbf{B}\):
To form the matrix product
\(\mathbf{C} \in \mathbb{R}^{n \times m}\), we simply compute each
element \(c_{ij}\) as the dot product between the
\(i^{\textrm{th}}\) row of \(\mathbf{A}\) and the
\(j^{\textrm{th}}\) column of \(\mathbf{B}\), i.e.,
\(\mathbf{a}^\top_i \mathbf{b}_j\):
We can think of the matrix–matrix multiplication \(\mathbf{AB}\) as
performing \(m\) matrix–vector products or \(m \times n\) dot
products and stitching the results together to form an
\(n \times m\) matrix. In the following snippet, we perform matrix
multiplication on A and B. Here, A is a matrix with two rows
and three columns, and B is a matrix with three rows and four
columns. After multiplication, we obtain a matrix with two rows and four
columns.
The term matrix–matrix multiplication is often simplified to matrix
multiplication, and should not be confused with the Hadamard product.
2.3.11. Norms
Some of the most useful operators in linear algebra are norms.
Informally, the norm of a vector tells us how big it is. For instance,
the \(\ell_2\) norm measures the (Euclidean) length of a vector.
Here, we are employing a notion of size that concerns the magnitude of
a vector’s components (not its dimensionality).
A norm is a function \(\| \cdot \|\) that maps a vector to a scalar
and satisfies the following three properties:
Given any vector \(\mathbf{x}\), if we scale (all elements of)
the vector by a scalar \(\alpha \in \mathbb{R}\), its norm scales
accordingly:
The norm of a vector is nonnegative and it only vanishes if the
vector is zero:
(2.3.12)\[\|\mathbf{x}\| > 0 \textrm{ for all } \mathbf{x} \neq 0.\]
Many functions are valid norms and different norms encode different
notions of size. The Euclidean norm that we all learned in elementary
school geometry when calculating the hypotenuse of a right triangle is
the square root of the sum of squares of a vector’s elements. Formally,
this is called the \(\ell_2\)norm and expressed as
The \(\ell_1\) norm is also common and the associated measure is
called the Manhattan distance. By definition, the \(\ell_1\) norm
sums the absolute values of a vector’s elements:
Compared to the \(\ell_2\) norm, it is less sensitive to outliers.
To compute the \(\ell_1\) norm, we compose the absolute value with
the sum operation.
torch.abs(u).sum()
tensor(7.)
Both the \(\ell_2\) and \(\ell_1\) norms are special cases of
the more general \(\ell_p\)norms:
In the case of matrices, matters are more complicated. After all,
matrices can be viewed both as collections of individual entries and
as objects that operate on vectors and transform them into other
vectors. For instance, we can ask by how much longer the matrix–vector
product \(\mathbf{X} \mathbf{v}\) could be relative to
\(\mathbf{v}\). This line of thought leads to what is called the
spectral norm. For now, we introduce the Frobenius norm, which is
much easier to compute and defined as the square root of the sum of the
squares of a matrix’s elements:
The Frobenius norm behaves as if it were an \(\ell_2\) norm of a
matrix-shaped vector. Invoking the following function will calculate the
Frobenius norm of a matrix.
torch.norm(torch.ones((4,9)))
tensor(6.)
While we do not want to get too far ahead of ourselves, we already can
plant some intuition about why these concepts are useful. In deep
learning, we are often trying to solve optimization problems: maximize
the probability assigned to observed data; maximize the revenue
associated with a recommender model; minimize the distance between
predictions and the ground truth observations; minimize the distance
between representations of photos of the same person while maximizing
the distance between representations of photos of different people.
These distances, which constitute the objectives of deep learning
algorithms, are often expressed as norms.
2.3.12. Discussion
In this section, we have reviewed all the linear algebra that you will
need to understand a significant chunk of modern deep learning. There is
a lot more to linear algebra, though, and much of it is useful for
machine learning. For example, matrices can be decomposed into factors,
and these decompositions can reveal low-dimensional structure in
real-world datasets. There are entire subfields of machine learning that
focus on using matrix decompositions and their generalizations to
high-order tensors to discover structure in datasets and solve
prediction problems. But this book focuses on deep learning. And we
believe you will be more inclined to learn more mathematics once you
have gotten your hands dirty applying machine learning to real datasets.
So while we reserve the right to introduce more mathematics later on, we
wrap up this section here.
If you are eager to learn more linear algebra, there are many excellent
books and online resources. For a more advanced crash course, consider
checking out Strang (1993), Kolter (2008), and
Petersen and Pedersen (2008).
To recap:
Scalars, vectors, matrices, and tensors are the basic mathematical
objects used in linear algebra and have zero, one, two, and an
arbitrary number of axes, respectively.
Tensors can be sliced or reduced along specified axes via indexing,
or operations such as sum and mean, respectively.
Elementwise products are called Hadamard products. By contrast, dot
products, matrix–vector products, and matrix–matrix products are not
elementwise operations and in general return objects having shapes
that are different from the the operands.
Compared to Hadamard products, matrix–matrix products take
considerably longer to compute (cubic rather than quadratic time).
Norms capture various notions of the magnitude of a vector (or
matrix), and are commonly applied to the difference of two vectors to
measure their distance apart.
Common vector norms include the \(\ell_1\) and \(\ell_2\)
norms, and common matrix norms include the spectral and Frobenius
norms.
2.3.13. Exercises
Prove that the transpose of the transpose of a matrix is the matrix
itself: \((\mathbf{A}^\top)^\top = \mathbf{A}\).
Given two matrices \(\mathbf{A}\) and \(\mathbf{B}\), show
that sum and transposition commute:
\(\mathbf{A}^\top + \mathbf{B}^\top = (\mathbf{A} + \mathbf{B})^\top\).
Given any square matrix \(\mathbf{A}\), is
\(\mathbf{A} + \mathbf{A}^\top\) always symmetric? Can you prove
the result by using only the results of the previous two exercises?
We defined the tensor X of shape (2, 3, 4) in this section. What
is the output of len(X)? Write your answer without implementing
any code, then check your answer using code.
For a tensor X of arbitrary shape, does len(X) always
correspond to the length of a certain axis of X? What is that
axis?
Run A/A.sum(axis=1) and see what happens. Can you analyze the
results?
When traveling between two points in downtown Manhattan, what is the
distance that you need to cover in terms of the coordinates, i.e.,
in terms of avenues and streets? Can you travel diagonally?
Consider a tensor of shape (2, 3, 4). What are the shapes of the
summation outputs along axes 0, 1, and 2?
Feed a tensor with three or more axes to the linalg.norm
function and observe its output. What does this function compute for
tensors of arbitrary shape?
Consider three large matrices, say
\(\mathbf{A} \in \mathbb{R}^{2^{10} \times 2^{16}}\),
\(\mathbf{B} \in \mathbb{R}^{2^{16} \times 2^{5}}\) and
\(\mathbf{C} \in \mathbb{R}^{2^{5} \times 2^{14}}\), initialized
with Gaussian random variables. You want to compute the product
\(\mathbf{A} \mathbf{B} \mathbf{C}\). Is there any difference in
memory footprint and speed, depending on whether you compute
\((\mathbf{A} \mathbf{B}) \mathbf{C}\) or
\(\mathbf{A} (\mathbf{B} \mathbf{C})\). Why?
Consider three large matrices, say
\(\mathbf{A} \in \mathbb{R}^{2^{10} \times 2^{16}}\),
\(\mathbf{B} \in \mathbb{R}^{2^{16} \times 2^{5}}\) and
\(\mathbf{C} \in \mathbb{R}^{2^{5} \times 2^{16}}\). Is there
any difference in speed depending on whether you compute
\(\mathbf{A} \mathbf{B}\) or \(\mathbf{A} \mathbf{C}^\top\)?
Why? What changes if you initialize
\(\mathbf{C} = \mathbf{B}^\top\) without cloning memory? Why?
Consider three matrices, say
\(\mathbf{A}, \mathbf{B}, \mathbf{C} \in \mathbb{R}^{100 \times 200}\).
Construct a tensor with three axes by stacking
\([\mathbf{A}, \mathbf{B}, \mathbf{C}]\). What is the
dimensionality? Slice out the second coordinate of the third axis to
recover \(\mathbf{B}\). Check that your answer is correct.
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.3. Forward Propagation, Backward Propagation, and Computational Graphs
Open the notebook in SageMaker Studio Lab
So far, we have trained our models with minibatch stochastic gradient
descent. However, when we implemented the algorithm, we only worried
about the calculations involved in forward propagation through the
model. When it came time to calculate the gradients, we just invoked the
backpropagation function provided by the deep learning framework.
The automatic calculation of gradients profoundly simplifies the
implementation of deep learning algorithms. Before automatic
differentiation, even small changes to complicated models required
recalculating complicated derivatives by hand. Surprisingly often,
academic papers had to allocate numerous pages to deriving update rules.
While we must continue to rely on automatic differentiation so we can
focus on the interesting parts, you ought to know how these gradients
are calculated under the hood if you want to go beyond a shallow
understanding of deep learning.
In this section, we take a deep dive into the details of backward
propagation (more commonly called backpropagation). To convey some
insight for both the techniques and their implementations, we rely on
some basic mathematics and computational graphs. To start, we focus our
exposition on a one-hidden-layer MLP with weight decay (\(\ell_2\)
regularization, to be described in subsequent chapters).
5.3.1. Forward Propagation
Forward propagation (or forward pass) refers to the calculation and
storage of intermediate variables (including outputs) for a neural
network in order from the input layer to the output layer. We now work
step-by-step through the mechanics of a neural network with one hidden
layer. This may seem tedious but in the eternal words of funk virtuoso
James Brown, you must “pay the cost to be the boss”.
For the sake of simplicity, let’s assume that the input example is
\(\mathbf{x}\in \mathbb{R}^d\) and that our hidden layer does not
include a bias term. Here the intermediate variable is:
where \(\mathbf{W}^{(1)} \in \mathbb{R}^{h \times d}\) is the weight
parameter of the hidden layer. After running the intermediate variable
\(\mathbf{z}\in \mathbb{R}^h\) through the activation function
\(\phi\) we obtain our hidden activation vector of length \(h\):
(5.3.2)\[\mathbf{h}= \phi (\mathbf{z}).\]
The hidden layer output \(\mathbf{h}\) is also an intermediate
variable. Assuming that the parameters of the output layer possess only
a weight of \(\mathbf{W}^{(2)} \in \mathbb{R}^{q \times h}\), we can
obtain an output layer variable with a vector of length \(q\):
where the Frobenius norm of the matrix is simply the \(\ell_2\) norm
applied after flattening the matrix into a vector. Finally, the model’s
regularized loss on a given data example is:
(5.3.6)\[J = L + s.\]
We refer to \(J\) as the objective function in the following
discussion.
5.3.2. Computational Graph of Forward Propagation
Plotting computational graphs helps us visualize the dependencies of
operators and variables within the calculation. Fig. 5.3.1
contains the graph associated with the simple network described above,
where squares denote variables and circles denote operators. The
lower-left corner signifies the input and the upper-right corner is the
output. Notice that the directions of the arrows (which illustrate data
flow) are primarily rightward and upward.
Fig. 5.3.1 Computational graph of forward propagation.
5.3.3. Backpropagation
Backpropagation refers to the method of calculating the gradient of
neural network parameters. In short, the method traverses the network in
reverse order, from the output to the input layer, according to the
chain rule from calculus. The algorithm stores any intermediate
variables (partial derivatives) required while calculating the gradient
with respect to some parameters. Assume that we have functions
\(\mathsf{Y}=f(\mathsf{X})\) and \(\mathsf{Z}=g(\mathsf{Y})\),
in which the input and the output
\(\mathsf{X}, \mathsf{Y}, \mathsf{Z}\) are tensors of arbitrary
shapes. By using the chain rule, we can compute the derivative of
\(\mathsf{Z}\) with respect to \(\mathsf{X}\) via
Here we use the \(\textrm{prod}\) operator to multiply its arguments
after the necessary operations, such as transposition and swapping input
positions, have been carried out. For vectors, this is straightforward:
it is simply matrix–matrix multiplication. For higher dimensional
tensors, we use the appropriate counterpart. The operator
\(\textrm{prod}\) hides all the notational overhead.
Recall that the parameters of the simple network with one hidden layer,
whose computational graph is in Fig. 5.3.1, are
\(\mathbf{W}^{(1)}\) and \(\mathbf{W}^{(2)}\). The objective of
backpropagation is to calculate the gradients
\(\partial J/\partial \mathbf{W}^{(1)}\) and
\(\partial J/\partial \mathbf{W}^{(2)}\). To accomplish this, we
apply the chain rule and calculate, in turn, the gradient of each
intermediate variable and parameter. The order of calculations are
reversed relative to those performed in forward propagation, since we
need to start with the outcome of the computational graph and work our
way towards the parameters. The first step is to calculate the gradients
of the objective function \(J=L+s\) with respect to the loss term
\(L\) and the regularization term \(s\):
Now we are able to calculate the gradient
\(\partial J/\partial \mathbf{W}^{(2)} \in \mathbb{R}^{q \times h}\)
of the model parameters closest to the output layer. Using the chain
rule yields:
To obtain the gradient with respect to \(\mathbf{W}^{(1)}\) we need
to continue backpropagation along the output layer to the hidden layer.
The gradient with respect to the hidden layer output
\(\partial J/\partial \mathbf{h} \in \mathbb{R}^h\) is given by
Since the activation function \(\phi\) applies elementwise,
calculating the gradient
\(\partial J/\partial \mathbf{z} \in \mathbb{R}^h\) of the
intermediate variable \(\mathbf{z}\) requires that we use the
elementwise multiplication operator, which we denote by \(\odot\):
Finally, we can obtain the gradient
\(\partial J/\partial \mathbf{W}^{(1)} \in \mathbb{R}^{h \times d}\)
of the model parameters closest to the input layer. According to the
chain rule, we get
When training neural networks, forward and backward propagation depend
on each other. In particular, for forward propagation, we traverse the
computational graph in the direction of dependencies and compute all the
variables on its path. These are then used for backpropagation where the
compute order on the graph is reversed.
Take the aforementioned simple network as an illustrative example. On
the one hand, computing the regularization term (5.3.5)
during forward propagation depends on the current values of model
parameters \(\mathbf{W}^{(1)}\) and \(\mathbf{W}^{(2)}\). They
are given by the optimization algorithm according to backpropagation in
the most recent iteration. On the other hand, the gradient calculation
for the parameter (5.3.11) during backpropagation
depends on the current value of the hidden layer output
\(\mathbf{h}\), which is given by forward propagation.
Therefore when training neural networks, once model parameters are
initialized, we alternate forward propagation with backpropagation,
updating model parameters using gradients given by backpropagation. Note
that backpropagation reuses the stored intermediate values from forward
propagation to avoid duplicate calculations. One of the consequences is
that we need to retain the intermediate values until backpropagation is
complete. This is also one of the reasons why training requires
significantly more memory than plain prediction. Besides, the size of
such intermediate values is roughly proportional to the number of
network layers and the batch size. Thus, training deeper networks using
larger batch sizes more easily leads to out-of-memory errors.
5.3.5. Summary
Forward propagation sequentially calculates and stores intermediate
variables within the computational graph defined by the neural network.
It proceeds from the input to the output layer. Backpropagation
sequentially calculates and stores the gradients of intermediate
variables and parameters within the neural network in the reversed
order. When training deep learning models, forward propagation and
backpropagation are interdependent, and training requires significantly
more memory than prediction.
5.3.6. Exercises
Assume that the inputs \(\mathbf{X}\) to some scalar function
\(f\) are \(n \times m\) matrices. What is the dimensionality
of the gradient of \(f\) with respect to \(\mathbf{X}\)?
Add a bias to the hidden layer of the model described in this section
(you do not need to include bias in the regularization term).
Draw the corresponding computational graph.
Derive the forward and backward propagation equations.
Compute the memory footprint for training and prediction in the model
described in this section.
Assume that you want to compute second derivatives. What happens to
the computational graph? How long do you expect the calculation to
take?
Assume that the computational graph is too large for your GPU.
Can you partition it over more than one GPU?
What are the advantages and disadvantages over training on a
smaller minibatch?
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.17. Neural network models (supervised)
Warning
This implementation is not intended for large-scale applications. In particular,
scikit-learn offers no GPU support. For much faster, GPU-based implementations,
as well as frameworks offering much more flexibility to build deep learning
architectures, see Related Projects.
1.17.1. Multi-layer Perceptron
Multi-layer Perceptron (MLP) is a supervised learning algorithm that learns
a function \(f: R^m \rightarrow R^o\) by training on a dataset,
where \(m\) is the number of dimensions for input and \(o\) is the
number of dimensions for output. Given a set of features \(X = \{x_1, x_2, ..., x_m\}\)
and a target \(y\), it can learn a non-linear function approximator for either
classification or regression. It is different from logistic regression, in that
between the input and the output layer, there can be one or more non-linear
layers, called hidden layers. Figure 1 shows a one hidden layer MLP with scalar
output.
Figure 1 : One hidden layer MLP.
The leftmost layer, known as the input layer, consists of a set of neurons
\(\{x_i | x_1, x_2, ..., x_m\}\) representing the input features. Each
neuron in the hidden layer transforms the values from the previous layer with
a weighted linear summation \(w_1x_1 + w_2x_2 + ... + w_mx_m\), followed
by a non-linear activation function \(g(\cdot):R \rightarrow R\) - like
the hyperbolic tan function. The output layer receives the values from the
last hidden layer and transforms them into output values.
The module contains the public attributes coefs_ and intercepts_.
coefs_ is a list of weight matrices, where weight matrix at index
\(i\) represents the weights between layer \(i\) and layer
\(i+1\). intercepts_ is a list of bias vectors, where the vector
at index \(i\) represents the bias values added to layer \(i+1\).
Advantages and disadvantages of Multi-layer Perceptron
The advantages of Multi-layer Perceptron are:
Capability to learn non-linear models.
Capability to learn models in real-time (on-line learning)
using partial_fit.
The disadvantages of Multi-layer Perceptron (MLP) include:
MLP with hidden layers has a non-convex loss function where there exists
more than one local minimum. Therefore, different random weight
initializations can lead to different validation accuracy.
MLP requires tuning a number of hyperparameters such as the number of
hidden neurons, layers, and iterations.
MLP is sensitive to feature scaling.
Please see Tips on Practical Use section that addresses
some of these disadvantages.
MLP trains on two arrays: array X of size (n_samples, n_features), which holds
the training samples represented as floating point feature vectors; and array
y of size (n_samples,), which holds the target values (class labels) for the
training samples:
Currently, MLPClassifier supports only the
Cross-Entropy loss function, which allows probability estimates by running the
predict_proba method.
MLP trains using Backpropagation. More precisely, it trains using some form of
gradient descent and the gradients are calculated using Backpropagation. For
classification, it minimizes the Cross-Entropy loss function, giving a vector
of probability estimates \(P(y|x)\) per sample \(x\):
MLPClassifier supports multi-class classification by
applying Softmax
as the output function.
Further, the model supports multi-label classification
in which a sample can belong to more than one class. For each class, the raw
output passes through the logistic function. Values larger or equal to 0.5
are rounded to 1, otherwise to 0. For a predicted output of a sample, the
indices where the value is 1 represent the assigned classes of that sample:
Class MLPRegressor implements a multi-layer perceptron (MLP) that
trains using backpropagation with no activation function in the output layer,
which can also be seen as using the identity function as activation function.
Therefore, it uses the square error as the loss function, and the output is a
set of continuous values.
MLPRegressor also supports multi-output regression, in
which a sample can have more than one target.
1.17.4. Regularization
Both MLPRegressor and MLPClassifier use parameter alpha
for regularization (L2 regularization) term which helps in avoiding overfitting
by penalizing weights with large magnitudes. Following plot displays varying
decision function with value of alpha.
MLP trains using Stochastic Gradient Descent,
Adam, or
L-BFGS.
Stochastic Gradient Descent (SGD) updates parameters using the gradient of the
loss function with respect to a parameter that needs adaptation, i.e.
where \(\eta\) is the learning rate which controls the step-size in
the parameter space search. \(Loss\) is the loss function used
for the network.
More details can be found in the documentation of
SGD
Adam is similar to SGD in a sense that it is a stochastic optimizer, but it can
automatically adjust the amount to update parameters based on adaptive estimates
of lower-order moments.
With SGD or Adam, training supports online and mini-batch learning.
L-BFGS is a solver that approximates the Hessian matrix which represents the
second-order partial derivative of a function. Further it approximates the
inverse of the Hessian matrix to perform parameter updates. The implementation
uses the Scipy version of L-BFGS.
If the selected solver is ‘L-BFGS’, training does not support online nor
mini-batch learning.
1.17.6. Complexity
Suppose there are \(n\) training samples, \(m\) features, \(k\)
hidden layers, each containing \(h\) neurons - for simplicity, and \(o\)
output neurons. The time complexity of backpropagation is
\(O(i \cdot n \cdot (m \cdot h + (k - 1) \cdot h \cdot h + h \cdot o))\), where \(i\) is the number
of iterations. Since backpropagation has a high time complexity, it is advisable
to start with smaller number of hidden neurons and few hidden layers for
training.
Mathematical formulation
Given a set of training examples \(\{(x_1, y_1), (x_2, y_2), \ldots, (x_n, y_n)\}\)
where \(x_i \in \mathbf{R}^n\) and \(y_i \in \{0, 1\}\), a one hidden
layer one hidden neuron MLP learns the function \(f(x) = W_2 g(W_1^T x + b_1) + b_2\)
where \(W_1 \in \mathbf{R}^m\) and \(W_2, b_1, b_2 \in \mathbf{R}\) are
model parameters. \(W_1, W_2\) represent the weights of the input layer and
hidden layer, respectively; and \(b_1, b_2\) represent the bias added to
the hidden layer and the output layer, respectively.
\(g(\cdot) : R \rightarrow R\) is the activation function, set by default as
the hyperbolic tan. It is given as,
\[g(z)= \frac{e^z-e^{-z}}{e^z+e^{-z}}\]
For binary classification, \(f(x)\) passes through the logistic function
\(g(z)=1/(1+e^{-z})\) to obtain output values between zero and one. A
threshold, set to 0.5, would assign samples of outputs larger or equal 0.5
to the positive class, and the rest to the negative class.
If there are more than two classes, \(f(x)\) itself would be a vector of
size (n_classes,). Instead of passing through logistic function, it passes
through the softmax function, which is written as,
where \(z_i\) represents the \(i\) th element of the input to softmax,
which corresponds to class \(i\), and \(K\) is the number of classes.
The result is a vector containing the probabilities that sample \(x\)
belongs to each class. The output is the class with the highest probability.
In regression, the output remains as \(f(x)\); therefore, output activation
function is just the identity function.
MLP uses different loss functions depending on the problem type. The loss
function for classification is Average Cross-Entropy, which in binary case is
given as,
where \(\alpha ||W||_2^2\) is an L2-regularization term (aka penalty)
that penalizes complex models; and \(\alpha > 0\) is a non-negative
hyperparameter that controls the magnitude of the penalty.
For regression, MLP uses the Mean Square Error loss function; written as,
Starting from initial random weights, multi-layer perceptron (MLP) minimizes
the loss function by repeatedly updating these weights. After computing the
loss, a backward pass propagates it from the output layer to the previous
layers, providing each weight parameter with an update value meant to decrease
the loss.
In gradient descent, the gradient \(\nabla Loss_{W}\) of the loss with respect
to the weights is computed and deducted from \(W\).
More formally, this is expressed as,
where \(i\) is the iteration step, and \(\epsilon\) is the learning rate
with a value larger than 0.
The algorithm stops when it reaches a preset maximum number of iterations; or
when the improvement in loss is below a certain, small number.
1.17.7. Tips on Practical Use
Multi-layer Perceptron is sensitive to feature scaling, so it
is highly recommended to scale your data. For example, scale each
attribute on the input vector X to [0, 1] or [-1, +1], or standardize
it to have mean 0 and variance 1. Note that you must apply the same
scaling to the test set for meaningful results.
You can use StandardScaler for standardization.
>>> fromsklearn.preprocessingimportStandardScaler>>> scaler=StandardScaler()>>> # Don't cheat - fit only on training data>>> scaler.fit(X_train)>>> X_train=scaler.transform(X_train)>>> # apply same transformation to test data>>> X_test=scaler.transform(X_test)
Finding a reasonable regularization parameter \(\alpha\) is best done
using GridSearchCV, usually in the range
10.0**-np.arange(1,7).
Empirically, we observed that L-BFGS converges faster and
with better solutions on small datasets. For relatively large
datasets, however, Adam is very robust. It usually converges
quickly and gives pretty good performance. SGD with momentum or
nesterov’s momentum, on the other hand, can perform better than
those two algorithms if learning rate is correctly tuned.
1.17.8. More control with warm_start
If you want more control over stopping criteria or learning rate in SGD,
or want to do additional monitoring, using warm_start=True and
max_iter=1 and iterating yourself can be helpful:
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.
Page Summary
Prioritize building robust infrastructure and simple models before incorporating complex machine learning algorithms.
Leverage existing heuristics and domain knowledge to enhance model performance and system intuition.
Continuously iterate and refine models through feature engineering and addressing potential pitfalls like training-serving skew.
Align machine learning objectives with measurable product goals and prioritize long-term user satisfaction.
Explore new data sources and features when performance plateaus, considering user relationships and external information.
Best Practices for ML Engineering
Martin Zinkevich
This document is intended to help those with a basic knowledge of machine
learning get the benefit of Google's best practices in machine learning. It
presents a style for machine learning, similar to the Google C++ Style Guide
and other popular guides to practical programming. If you have taken a class
in machine learning, or built or worked on a machine-learned model, then you
have the necessary background to read this document.
Martin Zinkevich introduces 10 of his favorite rules
of machine learning. Read on to learn all 43 rules!
Terminology
The following terms will come up repeatedly in our discussion of effective
machine learning:
Instance: The thing about which you want to make a
prediction. For example, the instance might be a web page that you want to
classify as either "about cats" or "not about cats".
Label: An answer for a prediction task either the answer produced by a
machine learning system, or the right answer supplied in training data. For
example, the label for a web page might be "about cats".
Feature: A property of an instance used in a prediction task. For
example, a web page might have a feature "contains the word 'cat'".
Feature Column: A set of related features, such as the set of all possible
countries in which users might live. An example may have one or more features
present in a feature column. "Feature column" is Google-specific terminology.
A feature column is referred to as a "namespace"
in the VW system (at Yahoo/Microsoft), or a
field.
Example: An instance (with its features) and a label.
Model: A statistical representation of a prediction task. You train a model on
examples then use the model to make predictions.
Metric: A number that you care about. May or may not be directly optimized.
Objective: A metric that your algorithm is trying to optimize.
Pipeline: The infrastructure surrounding a machine learning algorithm.
Includes gathering the data from the front end, putting it into training data
files, training one or more models, and exporting the models to production.
Click-through Rate The percentage of visitors to a web page who click a
link in an ad.
Overview
To make great products:
do machine learning like the great engineer you are, not like the great
machine learning expert you aren’t.
Most of the problems you will face are, in fact, engineering problems. Even
with all the resources of a great machine learning expert, most of the gains
come from great features, not great machine learning algorithms. So, the basic
approach is:
Make sure your pipeline is solid end to end.
Start with a reasonable objective.
Add common-sense features in a simple way.
Make sure that your pipeline stays solid.
This approach will work well for a
long period of time. Diverge from this approach only when there are no more
simple tricks to get you any farther. Adding complexity slows future releases.
Once you've exhausted the simple tricks, cutting-edge machine learning might
indeed be in your future. See the section on
Phase III
machine learning projects.
This document is arranged as follows:
The first part should help you understand whether
the time is right for building a machine learning system.
The second part is about deploying your
first pipeline.
The third part is about launching and
iterating while adding new features to your pipeline, how to evaluate models
and training-serving skew.
The
final part
is about what to do when you reach a plateau.
Afterwards, there is a list of related work and an
appendix with some
background on the systems commonly used as examples in this document.
Before Machine Learning
Rule #1: Don’t be afraid to launch a product without machine learning.
Machine learning is cool, but it requires data. Theoretically, you can take data
from a different problem and then tweak the model for a new product, but this
will likely underperform basic
heuristics. If you think that
machine learning will give you a 100% boost, then a heuristic will get you 50%
of the way there.
For instance, if you are ranking apps in an app marketplace, you could use the
install rate or number of installs as heuristics. If you are detecting spam,
filter out publishers that have sent spam before. Don’t be afraid to use human
editing either. If you need to rank contacts, rank the most recently used
highest (or even rank alphabetically). If machine learning is not absolutely
required for your product, don't use it until you have data.
Rule #2: First, design and implement metrics.
Before formalizing what your machine learning system will do, track as much as
possible in your current system. Do this for the following reasons:
It is easier to gain permission from the system’s users earlier on.
If you think that something might be a concern in the future, it is
better to get historical data now.
If you design your system with metric instrumentation in mind, things
will go better for
you in the future. Specifically, you don’t want to find yourself grepping
for strings in logs to instrument your metrics!
You will notice what things change and what stays the same. For instance,
suppose you want to directly optimize one-day active users. However,
during your early manipulations of the system, you may notice that
dramatic alterations of the user experience don’t noticeably change this
metric.
Google Plus team measures expands per read,
reshares per read, plusones per
read, comments/read, comments per user, reshares per user, etc. which they use
in computing the goodness of a post at serving time. Also, note that an
experiment framework, in which you can group users into buckets and aggregate
statistics by experiment, is important. See
Rule #12.
By being more liberal about gathering metrics, you can gain a broader picture
of your system. Notice a problem? Add a metric to track it! Excited about some
quantitative change on the last release? Add a metric to track it!
Rule #3: Choose machine learning over a complex heuristic.
A simple heuristic can get your product out the door. A complex heuristic is
unmaintainable. Once you have data and a basic idea of what you are trying to
accomplish, move on to machine learning. As in most software engineering
tasks, you will want to be constantly updating your approach, whether it is a
heuristic or a machine-learned model, and you will find that the
machine-learned model is easier to update and maintain (see
Rule #16).
ML Phase I: Your First Pipeline
Focus on your system infrastructure for your first pipeline. While it is fun
to think about all the imaginative machine learning you are going to do, it
will be hard to figure out what is happening if you don’t first trust your
pipeline.
Rule #4: Keep the first model simple and get the infrastructure right.
The first model provides the biggest boost to your product, so it doesn't need
to be fancy. But you will run into many more infrastructure issues than you
expect. Before anyone can use your fancy new machine learning system, you have
to determine:
How to get examples to your learning algorithm.
A first cut as to what "good" and "bad" mean to your system.
How to integrate your model into your application. You can either apply
the model live, or
precompute the model on examples offline and store the results in a table.
For example, you might want to preclassify web pages and store the results
in a table, but you might want to classify chat messages live.
Choosing simple features makes it easier to ensure that:
The features reach your learning algorithm correctly.
The model learns reasonable weights.
The features reach your model in the server correctly.
Once you have a system that does these three things reliably, you have done
most of the work. Your simple model provides you with baseline metrics and a
baseline behavior that you can use to test more complex models. Some teams aim
for a "neutral" first launch: a first launch that explicitly deprioritizes
machine learning gains, to avoid getting distracted.
Rule #5: Test the infrastructure independently from the machine learning.
Make sure that the infrastructure is testable, and that the learning parts of
the system are encapsulated so that you can test everything around it.
Specifically:
Test getting data into the algorithm. Check that feature columns that
should be populated are populated. Where privacy permits, manually
inspect the input to your training algorithm. If possible, check
statistics in your pipeline in comparison to statistics for the same data
processed elsewhere.
Test getting models out of the training algorithm. Make sure that the
model in your training environment gives the same score as the model
in your serving environment (see
Rule #37).
Machine learning has an element of unpredictability, so make sure that you
have tests for the code for creating examples in training and serving, and
that you can load and use a fixed model during serving. Also, it is important
to understand your data: see
Practical Advice for Analysis of Large, Complex Data Sets.
Rule #6: Be careful about dropped data when copying pipelines.
Often we create a pipeline by copying an existing pipeline (i.e.,
cargo cult programming
), and the old pipeline drops data that we need for the new pipeline.
For example, the pipeline for Google Plus What’s Hot
drops older posts (because it is trying to rank fresh posts). This pipeline was
copied to use for Google Plus Stream, where older posts
are still meaningful, but the pipeline was still dropping old posts. Another
common pattern is to only log data that was seen by the user. Thus, this data is
useless if we want to model why a particular post was not seen by the user,
because all the negative examples have been dropped. A similar issue occurred in
Play. While working on Play Apps Home, a new pipeline was created that also
contained examples from the landing page for Play Games without any feature to
disambiguate where each example came from.
Rule #7: Turn heuristics into features, or handle them externally.
Usually the problems that machine learning is trying to solve are not
completely new. There is an existing system for ranking, or classifying, or
whatever problem you are trying to solve. This means that there are a bunch of
rules and heuristics. These same heuristics can give you a lift when tweaked
with machine learning. Your heuristics should be mined for whatever
information they have, for two reasons. First, the transition to a machine
learned system will be smoother. Second, usually those rules contain a lot of
the intuition about the system you don’t want to throw away. There are four
ways you can use an existing heuristic:
Preprocess using the heuristic. If the feature is incredibly awesome,
then this is an option. For example, if, in a spam filter, the sender
has already been blacklisted, don’t try to relearn what "blacklisted"
means. Block the message. This approach makes the most sense in binary
classification tasks.
Create a feature. Directly creating a feature from the heuristic is great.
For example, if you use a heuristic to compute a relevance score for a query
result, you can include the score as the value of a feature. Later on you
may want to use machine learning techniques to massage the value
(for example, converting the value into one of a finite set of discrete
values, or combining it with other features) but start by using the raw
value produced by the heuristic.
Mine the raw inputs of the heuristic. If there is a heuristic for apps
that combines the number of installs, the number of characters in the
text, and the day of the week, then consider pulling these pieces apart,
and feeding these inputs into the learning separately. Some techniques
that apply to ensembles apply here (see
Rule #40).
Modify the label. This is an option when you feel that the heuristic
captures information not currently contained in the label. For example,
if you are trying to maximize the number of downloads, but you also want
quality content, then maybe the solution is to multiply the label by the
average number of stars the app received. There is a lot of leeway here.
See "Your First Objective".
Do be mindful of the added complexity when using heuristics in an ML
system. Using old heuristics in your new machine learning algorithm can
help to create a smooth transition, but think about whether there is a
simpler way to accomplish the same effect.
Monitoring
In general, practice good alerting hygiene, such as making alerts actionable
and having a dashboard page.
Rule #8: Know the freshness requirements of your system.
How much does performance degrade if you have a model that is a day old? A week
old? A quarter old? This information can help you to understand the priorities
of your monitoring. If you lose significant product
quality if the model is not updated
for a day, it makes sense to have an engineer watching it continuously. Most ad
serving systems have new advertisements to handle every day, and must update
daily. For instance, if the ML model for
Google Play Search is not updated, it can have a
negative impact in under a month. Some models for What’s Hot in
Google Plus have no post identifier in their model so
they can
export these models infrequently. Other models that have post identifiers are
updated much more frequently. Also notice that freshness can change over time,
especially when feature columns are added or removed from your model.
Rule #9: Detect problems before exporting models.
Many machine learning systems have a stage where you export the model to
serving. If there is an issue with an exported model, it is a user-facing
issue.
Do sanity checks right before you export the model. Specifically, make sure
that the model’s performance is reasonable on held out data. Or, if you have
lingering concerns with the data, don’t export a model. Many teams
continuously deploying models check the area under the
ROC curve
(or AUC)
before exporting. Issues about models that haven’t been exported require an
email alert, but issues on a user-facing model may require a page. So better
to wait and be sure before impacting users.
Rule #10: Watch for silent failures.
This is a problem that occurs more for machine learning systems than for other
kinds of systems. Suppose that a particular table that is being joined is no
longer being updated. The machine learning system will adjust, and behavior
will continue to be reasonably good, decaying gradually. Sometimes you find
tables that are months out of date, and a simple refresh improves performance
more than any other launch that quarter! The coverage of a
feature may change due to implementation changes: for example a feature column
could be populated in 90% of the examples, and suddenly drop to 60% of the
examples. Play once had a table that was stale for 6 months, and refreshing
the table alone gave a boost of 2% in install rate. If you track statistics of
the data, as well as manually inspect the data on occasion, you can reduce
these kinds of failures.
Rule #11: Give feature columns owners and documentation.
If the system is large, and there are many feature columns, know who created
or is maintaining each feature column. If you find that the person who
understands a feature column is leaving, make sure that someone has the
information. Although many feature columns have descriptive names, it's good
to have a more detailed description of what the feature is, where it came
from, and how it is expected to help.
Your First Objective
You have many metrics, or measurements about the system that you care about,
but your machine learning algorithm will often require a single objective, a
number that your algorithm is "trying" to optimize. I distinguish here
between objectives and metrics: a metric is any number that your system
reports, which may or may not be important. See also
Rule #2.
Rule #12: Don’t overthink which objective you choose to directly optimize.
You want to make money, make your users happy, and make the world a better
place. There are tons of metrics that you care about, and you should measure
them all (see Rule #2). However,
early in the machine learning process, you will notice them all going up, even
those that you do not directly optimize. For instance, suppose you care about
number of clicks and time spent on the site. If you optimize for number of
clicks, you are likely to see the time spent increase.
So, keep it simple and don’t think too hard about balancing different metrics
when you can still easily increase all the metrics. Don’t take this rule too
far though: do not confuse your objective with the ultimate health of the
system (see
Rule #39).
And, if you find yourself increasing the directly
optimized metric, but deciding not to launch, some objective revision may be
required.
Rule #13: Choose a simple, observable and attributable metric for your first objective.
Often you don't know what the true objective is. You think you do but then as
you stare at the data and side-by-side analysis of your old system and new ML
system, you realize you want to tweak the objective. Further, different team
members often can't agree on the true objective. The ML objective should be
something that is easy to measure and is a proxy for the "true" objective.
In fact, there is often no "true" objective (see
Rule#39).
So
train on the simple ML objective, and consider having a "policy layer" on top
that allows you to add additional logic (hopefully very simple logic) to do
the final ranking.
The easiest thing to model is a user behavior that is directly observed and attributable to an
action of the system:
Was this ranked link clicked?
Was this ranked object downloaded?
Was this ranked object forwarded/replied to/emailed?
Was this ranked object rated?
Was this shown object marked as spam/pornography/offensive?
Avoid modeling indirect effects at first:
Did the user visit the next day?
How long did the user visit the site?
What were the daily active users?
Indirect effects make great metrics, and can be used during A/B testing and during launch
decisions.
Finally, don’t try to get the machine learning to figure out:
Is the user happy using the product?
Is the user satisfied with the experience?
Is the product improving the user’s overall wellbeing?
How will this affect the company’s overall health?
These are all important, but also incredibly hard to measure. Instead, use
proxies: if the user is happy, they will stay on the site longer. If the user
is satisfied, they will visit again tomorrow. Insofar as well-being and
company health is concerned, human judgement is required to connect any
machine learned objective to the nature of the product you are selling and
your business plan.
Rule #14: Starting with an interpretable model makes debugging easier.
Linear regression, logistic regression, and Poisson regression are directly
motivated by a probabilistic model. Each prediction is interpretable as a
probability or an expected value. This makes them easier to debug than models
that use objectives (zero-one loss, various hinge losses, and so on) that try
to directly optimize classification accuracy or ranking performance. For
example, if probabilities in training deviate from probabilities predicted in
side-by-sides or by inspecting the production system, this deviation could
reveal a problem.
For example, in linear, logistic, or Poisson regression, there are subsets of
the data where the average predicted expectation equals the average label (1-
moment calibrated, or just calibrated). This is true assuming that you have no
regularization and that your algorithm has converged, and it is approximately
true in general. If you have a feature which is either 1 or 0 for each example,
then the set of 3 examples where that feature is 1 is calibrated. Also, if you
have a feature that is 1 for every example, then the set of all examples is
calibrated.
With simple models, it is easier to deal with feedback loops (see
Rule #36).
Often, we use these probabilistic predictions to make a decision: e.g. rank
posts in decreasing expected value (i.e. probability of click/download/etc.).
However, remember when it comes time to choose which model to use, the
decision matters more than the likelihood of the data given the model (see
Rule #27).
Rule #15: Separate Spam Filtering and Quality Ranking in a Policy Layer.
Quality ranking is a fine art, but spam filtering is a war. The signals that
you use to determine high quality posts will become obvious to those who use
your system, and they will tweak their posts to have these properties. Thus,
your quality ranking should focus on ranking content that is posted in good
faith. You should not discount the quality ranking learner for ranking spam
highly. Similarly, "racy" content should be handled separately from Quality
Ranking. Spam filtering is a different story. You have to expect that the
features that you need to generate will be constantly changing. Often, there
will be obvious rules that you put into the system (if a post has more than
three spam votes, don’t retrieve it, et cetera). Any learned model will have
to be updated daily, if not faster. The reputation of the creator of the
content will play a great role.
At some level, the output of these two systems will have to be integrated. Keep
in mind, filtering spam in search results should probably be more aggressive
than filtering spam in email messages. Also, it is a standard practice to remove
spam from the training data for the quality classifier.
ML Phase II: Feature Engineering
In the first phase of the lifecycle of a machine learning system, the
important issues are to get the training data into the learning system, get any
metrics of interest instrumented, and create a serving infrastructure. After
you have a working end to end system with unit and system tests instrumented,
Phase II begins.
In the second phase, there is a lot of low-hanging fruit. There are a variety
of obvious features that could be pulled into the system. Thus, the second
phase of machine learning involves pulling in as many features as possible and
combining them in intuitive ways. During this phase, all of the metrics should
still be rising. There will be lots of launches, and it is a great time to
pull in lots of engineers that can join up all the data that you need to
create a truly awesome learning system.
Rule #16: Plan to launch and iterate.
Don’t expect that the model you are working on now will be the last one that
you will launch, or even that you will ever stop launching models. Thus
consider whether the complexity you are adding with this launch will slow down
future launches. Many teams have launched a model per quarter or more for
years. There are three basic reasons to launch new models:
You are coming up with new features.
You are tuning regularization and combining old features in new ways.
You are tuning the objective.
Regardless, giving a model a bit of love can be good: looking over the data
feeding into the example can help find new signals as well as old, broken
ones. So, as you build your model, think about how easy it is to add or remove
or recombine features. Think about how easy it is to create a fresh copy of
the pipeline and verify its correctness. Think about whether it is possible to
have two or three copies running in parallel. Finally, don’t worry about
whether feature 16 of 35 makes it into this version of the pipeline. You’ll
get it next quarter.
Rule #17: Start with directly observed and reported features as opposed to learned features.
This might be a controversial point, but it avoids a lot of pitfalls. First of
all, let’s describe what a learned feature is. A learned feature is a feature
generated either by an external system (such as an unsupervised clustering
system) or by the learner itself (e.g. via a factored model or deep learning).
Both of these can be useful, but they can have a lot of issues, so they should
not be in the first model.
If you use an external system to create a feature, remember that the external
system has its own objective. The external system's objective may be only weakly
correlated with your current objective. If you grab a snapshot of the external
system, then it can become out of date. If you update the features from the
external system, then the meanings may change. If you use an external system to
provide a feature, be aware that this approach requires a great deal of care.
The primary issue with factored models and deep models is that they are
nonconvex. Thus, there is no guarantee that an optimal solution can be
approximated or found, and the local minima found on each iteration can be
different. This variation makes it hard to judge whether the impact of a
change to your system is meaningful or random. By creating a model without
deep features, you can get an excellent baseline performance. After this
baseline is achieved, you can try more esoteric approaches.
Rule #18: Explore with features of content that generalize across contexts.
Often a machine learning system is a small part of a much bigger picture. For
example, if you imagine a post that might be used in What’s Hot, many people
will plus-one, reshare, or comment on a post before it is ever shown in What's
Hot. If you provide those statistics to the learner, it can promote new posts
that it has no data for in the context it is optimizing.
YouTube Watch Next could use number of watches, or co-
watches (counts of how many times one video was watched after another was
watched) from YouTube search. You can also use explicit
user ratings. Finally, if you have a user action that you are using as a label,
seeing that action on the document in a different context can be a great
feature. All of these features allow you to bring new content into the context.
Note that this is not about personalization: figure out if someone likes the
content in this context first, then figure out who likes it more or less.
Rule #19: Use very specific features when you can.
With tons of data, it is simpler to learn millions of simple features than a
few complex features. Identifiers of documents being retrieved and
canonicalized queries do not provide much generalization, but align your
ranking with your labels on head queries. Thus, don’t be afraid of groups of
features where each feature applies to a very small fraction of your data, but
overall coverage is above 90%. You can use regularization to eliminate the
features that apply to too few examples.
Rule #20: Combine and modify existing features to create new features in human-understandable ways.
There are a variety of ways to combine and modify features. Machine learning
systems such as TensorFlow allow you to pre-process your data through
transformations.
The two most standard approaches are "discretizations" and "crosses".
Discretization consists of taking a continuous feature and creating many
discrete features from it. Consider a continuous feature such as age. You can
create a feature which is 1 when age is less than 18, another feature which is
1 when age is between 18 and 35, et cetera. Don’t overthink the boundaries of
these histograms: basic quantiles will give you most of the impact.
Crosses combine two or more feature columns. A feature column, in TensorFlow's
terminology, is a set of homogenous features, (e.g. {male, female}, {US,
Canada, Mexico}, et cetera). A cross is a new feature column with features in,
for example, {male, female} × {US,Canada, Mexico}. This new feature column
will contain the feature (male, Canada). If you are using TensorFlow and you
tell TensorFlow to create this cross for you, this (male, Canada) feature will
be present in examples representing male Canadians. Note that it takes massive
amounts of data to learn models with crosses of three, four, or more base
feature columns.
Crosses that produce very large feature columns may overfit. For instance,
imagine that you are doing some sort of search, and you have a feature column
with words in the query, and you have a feature column with words in the
document. You can combine these with a cross, but you will end up with a lot of
features (see Rule #21).
When working with text there are two alternatives. The most draconian is a
dot product. A dot product in its simplest form simply counts the number of
words in common between the query and the document. This feature can then be
discretized. Another approach is an intersection: thus, we will have a feature
which is present if and only if the word "pony" is in both the document and the
query, and another feature which is present if and only if the word "the" is in
both the document and the query.
Rule #21: The number of feature weights you can learn in a linear model is roughly proportional to the amount of data you have.
There are fascinating statistical learning theory results concerning the
appropriate level of complexity for a model, but this rule is basically all
you need to know. I have had conversations in which people were doubtful that
anything can be learned from one thousand examples, or that you would ever
need more than one million examples, because they get stuck in a certain method
of learning. The key is to scale your learning to the size of your data:
If you are working on a search ranking system, and there are millions
of different words in the documents and the query and you have 1000
labeled examples, then you should use a dot product between document
and query features, TF-IDF,
and a half-dozen other highly human-engineered
features. 1000 examples, a dozen features.
If you have a million examples, then intersect the document and query
feature columns, using regularization and possibly feature selection.
This will give you millions of features, but with regularization you
will have fewer. Ten million examples, maybe a hundred thousand features.
If you have billions or hundreds of billions of examples, you can cross
the feature columns with document and query tokens, using feature selection
and regularization. You will have a billion examples, and 10 million
features. Statistical learning theory rarely gives tight bounds, but gives
great guidance for a starting point.
In the end, use
Rule #28
to decide what features to use.
Rule #22: Clean up features you are no longer using.
Unused features create technical debt. If you find that you are not using a
feature, and that combining it with other features is not working, then drop
it out of your infrastructure. You want to keep your infrastructure clean so
that the most promising features can be tried as fast as possible. If
necessary, someone can always add back your feature.
Keep coverage in mind when considering what features to add or keep. How many
examples are covered by the feature? For example, if you have some
personalization features, but only 8% of your users have any personalization
features, it is not going to be very effective.
At the same time, some features may punch above their weight. For example, if
you have a feature which covers only 1% of the data, but 90% of the examples
that have the feature are positive, then it will be a great feature to add.
Human Analysis of the System
Before going on to the third phase of machine learning, it is important to
focus on something that is not taught in any machine learning class: how to
look at an existing model, and improve it. This is more of an art than a
science, and yet there are several antipatterns that it helps to avoid.
Rule #23: You are not a typical end user.
This is perhaps the easiest way for a team to get bogged down. While there are
a lot of benefits to fishfooding (using a prototype within your team) and
dogfooding (using a prototype within your company), employees should look at
whether the performance is correct. While a change which is obviously bad
should not be used, anything that looks reasonably near production should be
tested further, either by paying laypeople to answer questions on a
crowdsourcing platform, or through a live experiment on real users.
There are two reasons for this. The first is that you are too close to the
code. You may be looking for a particular aspect of the posts, or you are
simply too emotionally involved (e.g. confirmation bias). The second is that
your time is too valuable. Consider the cost of nine engineers sitting in a one
hour meeting, and think of how many contracted human labels that buys on a
crowdsourcing platform.
If you really want to have user feedback, use user experience
methodologies. Create user personas (one description is in Bill Buxton’s
Sketching User Experiences)
early in a process and do usability testing (one
description is in Steve Krug’s
Don’t Make Me Think)
later. User personas
involve creating a hypothetical user. For instance, if your team is all male,
it might help to design a 35-year-old female user persona (complete with user
features), and look at the results it generates rather than 10 results for
25-to-40 year old males. Bringing in actual people to watch their reaction to
your site (locally or remotely) in usability testing can also get you a fresh
perspective.
Rule #24: Measure the delta between models.
One of the easiest and sometimes most useful measurements you can make before
any users have looked at your new model is to calculate just how different the
new results are from production. For instance, if you have a ranking problem,
run both models on a sample of queries through the entire system, and look at
the size of the symmetric difference of the results (weighted by ranking
position). If the difference is very small, then you can tell without running
an experiment that there will be little change. If the difference is very
large, then you want to make sure that the change is good. Looking over
queries where the symmetric difference is high can help you to understand
qualitatively what the change was like. Make sure, however, that the system is
stable. Make sure that a model when compared with itself has a low (ideally
zero) symmetric difference.
Rule #25: When choosing models, utilitarian performance trumps predictive power.
Your model may try to predict click-through rate. However, in the end, the key
question is what you do with that prediction. If you are using it to rank
documents, then the quality of the final ranking matters more than the
prediction itself. If you predict the probability that a document is spam and
then have a cutoff on what is blocked, then the precision of what is allowed
through matters more. Most of the time, these two things should be in
agreement: when they do not agree, it will likely be on a small gain. Thus, if
there is some change that improves log loss but degrades the performance of
the system, look for another feature. When this starts happening more often,
it is time to revisit the objective of your model.
Rule #26: Look for patterns in the measured errors, and create new features.
Suppose that you see a training example that the model got "wrong". In a
classification task, this error could be a false positive or a false negative.
In a ranking task, the error could be a pair where a positive was ranked lower
than a negative. The most important point is that this is an example that the
machine learning system knows it got wrong and would like to fix if given the
opportunity. If you give the model a feature that allows it to fix the error,
the model will try to use it.
On the other hand, if you try to create a feature based upon examples the
system doesn’t see as mistakes, the feature will be ignored. For instance,
suppose that in Play Apps Search, someone searches for "free games". Suppose
one of the top results is a less relevant gag app. So you create a feature for
"gag apps". However, if you are maximizing number of installs, and people
install a gag app when they search for free games, the "gag apps" feature
won’t have the effect you want.
Once you have examples that the model got wrong, look for trends that are
outside your current feature set. For instance, if the system seems to be
demoting longer posts, then add post length. Don’t be too specific about the
features you add. If you are going to add post length, don’t try to guess what
long means, just add a dozen features and the let model figure out what to do
with them (see
Rule #21
). That is the easiest way to get what you want.
Rule #27: Try to quantify observed undesirable behavior.
Some members of your team will start to be frustrated with properties of the
system they don’t like which aren’t captured by the existing loss function. At
this point, they should do whatever it takes to turn their gripes into solid
numbers. For example, if they think that too many "gag apps" are being shown
in Play Search, they could have human raters identify gag apps. (You can
feasibly use humanlabelled data in this case because a relatively small
fraction of the queries account for a large fraction of the traffic.) If your
issues are measurable, then you can start using them as features, objectives,
or metrics. The general rule is "measure first, optimize second".
Rule #28: Be aware that identical short-term behavior does not imply identical long-term behavior.
Imagine that you have a new system that looks at every doc_id and exact_query,
and then calculates the probability of click for every doc for every query.
You find that its behavior is nearly identical to your current system in both
side by sides and A/B testing, so given its simplicity, you launch it.
However, you notice that no new apps are being shown. Why? Well, since your
system only shows a doc based on its own history with that query, there is no
way to learn that a new doc should be shown.
The only way to understand how such a system would work long-term is to have
it train only on data acquired when the model was live. This is very
difficult.
Training-Serving Skew
Training-serving skew is a difference between performance during training and
performance during serving. This skew can be caused by:
A discrepancy between how you handle data in the training and serving pipelines.
A change in the data between when you train and when you serve.
A feedback loop between your model and your algorithm.
We have observed production machine learning systems at Google with training-
serving skew that negatively impacts performance. The best solution is to
explicitly monitor it so that system and data changes don’t introduce skew
unnoticed.
Rule #29: The best way to make sure that you train like you serve is to save the set of features used at serving time, and then pipe those features to a log to use them at training time.
Even if you can’t do this for every example, do it for a small fraction, such
that you can verify the consistency between serving and training (see
Rule #37). Teams that have made this
measurement at Google were sometimes surprised by the results.
YouTube home page
switched to logging features at serving time with significant quality
improvements and a reduction in code complexity, and many teams are switching
their infrastructure as we speak.
Rule #30: Importance-weight sampled data, don’t arbitrarily drop it!
When you have too much data, there is a temptation to take files 1-12, and
ignore files 13-99. This is a mistake. Although data that was
never shown to the user can be dropped, importance weighting is best for the
rest. Importance weighting means that if you decide that you are going to
sample example X with a 30% probability, then give it a weight of 10/3. With
importance weighting, all of the calibration properties discussed in
Rule #14
still hold.
Rule #31: Beware that if you join data from a table at training and serving time, the data in the table may change.
Say you join doc ids with a table containing features for those docs (such as
number of comments or clicks). Between training and serving time, features in
the table may be changed. Your model's prediction for the same document may
then differ between training and serving. The easiest way to avoid this sort
of problem is to log features at serving time (see
Rule #32
). If the table is
changing only slowly, you can also snapshot the table hourly or daily to get
reasonably close data. Note that this still doesn’t completely resolve the
issue.
Rule #32: Re-use code between your training pipeline and your serving pipeline whenever possible.
Batch processing is different than online processing. In online processing,
you must handle each request as it arrives (e.g. you must do a separate lookup
for each query), whereas in batch processing, you can combine tasks (e.g.
making a join). At serving time, you are doing online processing, whereas
training is a batch processing task. However, there are some things that you
can do to re-use code. For example, you can create an object that is
particular to your system where the result of any queries or joins can be
stored in a very human readable way, and errors can be tested easily. Then,
once you have gathered all the information, during serving or training, you
run a common method to bridge between the human-readable object that is
specific to your system, and whatever format the machine learning system
expects. This eliminates a source of training-serving skew. As a
corollary, try not to use two different programming languages between training
and serving. That decision will make it nearly impossible for you to share
code.
Rule #33: If you produce a model based on the data until January 5th, test the model on the data from January 6th and after.
In general, measure performance of a model on the data gathered after the data
you trained the model on, as this better reflects what your system will do in
production. If you produce a model based on the data until January 5th, test
the model on the data from January 6th. You will expect that the performance
will not be as good on the new data, but it shouldn’t be radically worse.
Since there might be daily effects, you might not predict the average click
rate or conversion rate, but the area under the curve, which represents the
likelihood of giving the positive example a score higher than a negative
example, should be reasonably close.
Rule #34: In binary classification for filtering (such as spam detection or determining interesting emails), make small short-term sacrifices in performance for very clean data.
In a filtering task, examples which are marked as negative are not shown to
the user. Suppose you have a filter that blocks 75% of the negative examples
at serving. You might be tempted to draw additional training data from the
instances shown to users. For example, if a user marks an email as spam that
your filter let through, you might want to learn from that.
But this approach introduces sampling bias. You can gather cleaner data if
instead during serving you label 1% of all traffic as "held out", and send all
held out examples to the user. Now your filter is blocking at least 74% of the
negative examples. These held out examples can become your training data.
Note that if your filter is blocking 95% of the negative examples or more, this
approach becomes less viable. Even so, if you wish to measure serving
performance, you can make an even tinier sample (say 0.1% or 0.001%). Ten
thousand examples is enough to estimate performance quite accurately.
Rule #35: Beware of the inherent skew in ranking problems.
When you switch your ranking algorithm radically enough that different results
show up, you have effectively changed the data that your algorithm is going to
see in the future. This kind of skew will show up, and you should design your
model around it. There are multiple different approaches. These approaches are
all ways to favor data that your model has already seen.
Have higher regularization on features that cover more queries as opposed to
those features that are on for only one query. This way, the model will favor
features that are specific to one or a few queries over features that
generalize to all queries. This approach can help prevent very popular
results from leaking into irrelevant queries. Note that this is opposite the
more conventional advice of having more regularization on feature columns
with more unique values.
Only allow features to have positive weights. Thus, any good feature will be
better than a feature that is "unknown".
Don’t have document-only features. This is an extreme version of #1. For
example, even if a given app is a popular download regardless of what the
query was, you don’t want to show it everywhere. Not having document-only
features keeps that simple. The reason you don’t want to show a specific
popular app everywhere has to do with the importance of
making all the desired apps reachable. For instance, if someone searches for
"bird watching app", they might download "angry birds", but that certainly
wasn’t their intent. Showing such an app might improve download rate, but
leave the user’s needs ultimately unsatisfied.
Rule #36: Avoid feedback loops with positional features.
The position of content dramatically affects how likely the user is to interact
with it. If you put an app in the first position it will be clicked more often,
and you will be convinced it is more likely to be clicked. One way to deal with
this is to add positional features, i.e. features about the position of the
content in the page. You train your model with positional features, and it
learns to weight, for example, the feature "1stposition" heavily. Your model
thus gives less weight to other factors for examples with "1stposition=true".
Then at serving you don't give any instances the positional feature, or you give
them all the same default feature, because you are scoring candidates before you
have decided the order in which to display them.
Note that it is important to keep any positional features somewhat separate from
the rest of the model because of this asymmetry between training and testing.
Having the model be the sum of a function of the positional features and a
function of the rest of the features is ideal. For example, don’t cross the
positional features with any document feature.
Rule #37: Measure Training/Serving Skew.
There are several things that can cause skew in the most general sense.
Moreover, you can divide it into several parts:
The difference between the performance on the training data and the holdout
data. In general, this will always exist, and it is not always bad.
The difference between the performance on the holdout data and the "nextday"
data. Again, this will always exist. You should tune your regularization to
maximize the next-day performance. However, large drops in performance
between holdout and next-day data may indicate that some features are
time-sensitive and possibly degrading model performance.
The difference between the performance on the "next-day" data and the live
data. If you apply a model to an example in the training data and the same
example at serving, it should give you exactly the same result (see
Rule #5
).
Thus, a discrepancy here probably indicates an engineering error.
ML Phase III: Slowed Growth, Optimization Refinement, and Complex Models
There will be certain indications that the second phase is reaching a close.
First of all, your monthly gains will start to diminish. You will start to have
tradeoffs between metrics: you will see some rise and others fall in some
experiments. This is where it gets interesting. Since the gains are harder to
achieve, the machine learning has to get more sophisticated. A caveat: this
section has more blue-sky rules than earlier sections. We have seen many teams
go through the happy times of Phase I and Phase II machine learning. Once Phase
III has been reached, teams have to find their own path.
Rule #38: Don’t waste time on new features if unaligned objectives have become the issue.
As your measurements plateau, your team will start to look at issues that are
outside the scope of the objectives of your current machine learning system. As
stated before, if the product goals are not covered by the existing algorithmic
objective, you need to change either your objective or your product goals. For
instance, you may optimize clicks, plus-ones, or downloads, but make launch
decisions based in part on human raters.
Rule #39: Launch decisions are a proxy for long-term product goals.
Alice has an idea about reducing the logistic loss of predicting installs. She
adds a feature. The logistic loss drops. When she does a live experiment, she
sees the install rate increase. However, when she goes to a launch review
meeting, someone points out that the number of daily active users drops by 5%.
The team decides not to launch the model. Alice is disappointed, but now
realizes that launch decisions depend on multiple criteria, only some of which
can be directly optimized using ML.
The truth is that the real world is not dungeons and dragons: there are no "hit
points" identifying the health of your product. The team has to use the
statistics it gathers to try to effectively predict how good the system will be
in the future. They need to care about engagement, 1 day active users (DAU), 30
DAU, revenue, and advertiser’s return on investment. These metrics that are
measureable in A/B tests in themselves are only a proxy for more longterm
goals: satisfying users, increasing users, satisfying partners, and profit,
which even then you could consider proxies for having a useful, high quality
product and a thriving company five years from now.
The only easy launch decisions are when all metrics get better (or at least do
not get worse). If the team has a choice between a sophisticated machine
learning algorithm, and a simple heuristic, if the simple heuristic does a
better job on all these metrics, it should choose the heuristic. Moreover, there
is no explicit ranking of all possible metric values. Specifically, consider the
following two scenarios:
Experiment
Daily Active Users
Revenue/Day
A
1 million
$4 million
B
2 million
$2 million
If the current system is A, then the team would be unlikely to switch to B. If
the current system is B, then the team would be unlikely to switch to A. This
seems in conflict with rational behavior; however, predictions of changing
metrics may or may not pan out, and thus there is a large risk involved with
either change. Each metric covers some risk with which the team is concerned.
Moreover, no metric covers the team’s ultimate concern, "where is my product
going to be five years from now"?
Individuals, on the other hand, tend to favor one objective that they can
directly optimize. Most machine learning tools favor such an environment. An
engineer banging out new features can get a steady stream of launches in such an
environment. There is a type of machine learning, multi-objective learning,
which starts to address this problem. For instance, one can formulate a
constraint satisfaction problem that has lower bounds on each metric, and
optimizes some linear combination of metrics. However, even then, not all
metrics are easily framed as machine learning objectives: if a document is
clicked on or an app is installed, it is because that the content was shown. But
it is far harder to figure out why a user visits your site. How to predict the
future success of a site as a whole is
AI-complete: as hard as computer
vision or natural language processing.
Rule #40: Keep ensembles simple.
Unified models that take in raw features and directly rank content are the
easiest models to debug and understand. However, an ensemble of models (a
"model" which combines the scores of other models) can work better. To keep
things simple, each model should either be an ensemble only taking the input of
other models, or a base model taking many features, but not both. If you have
models on top of other models that are trained separately, then combining them
can result in bad behavior.
Use a simple model for ensembling that takes only the output of your "base"
models as inputs. You also want to enforce properties on these ensemble models.
For example, an increase in the score produced by a base model should not
decrease the score of the ensemble. Also, it is best if the incoming models are
semantically interpretable (for example, calibrated) so that changes of the
underlying models do not confuse the ensemble model. Also, enforce that an
increase in the predicted probability of an underlying classifier does not
decrease the predicted probability of the ensemble.
Rule #41: When performance plateaus, look for qualitatively new sources of information to add rather than refining existing signals.
You’ve added some demographic information about the user. You've added some
information about the words in the document. You have gone through template
exploration, and tuned the regularization. You haven’t seen a launch with more
than a 1% improvement in your key metrics in a few quarters. Now what?
It is time to start building the infrastructure for radically different
features, such as the history of documents that this user has accessed in the
last day, week, or year, or data from a different property. Use
wikidata
entities or something internal to your company (such as Google’s
knowledge graph). Use deep
learning. Start to adjust your expectations on how much return
you expect on investment, and expand your efforts accordingly. As in any
engineering project, you have to weigh the benefit of adding new features
against the cost of increased complexity.
Rule #42: Don’t expect diversity, personalization, or relevance to be as correlated with popularity as you think they are.
Diversity in a set of content can mean many things, with the diversity of the
source of the content being one of the most common. Personalization implies each
user gets their own results. Relevance implies that the results for a particular
query are more appropriate for that query than any other. Thus all three of
these properties are defined as being different from the ordinary.
The problem is that the ordinary tends to be hard to beat.
Note that if your system is measuring clicks, time spent, watches, +1s,
reshares, et cetera, you are measuring the popularity of the content. Teams
sometimes try to learn a personal model with diversity. To personalize, they add
features that would allow the system to personalize (some features representing
the user’s interest) or diversify (features indicating if this document has any
features in common with other documents returned, such as author or content),
and find that those features get less weight (or sometimes a different sign)
than they expect.
This doesn’t mean that diversity, personalization, or relevance aren’t valuable.
As pointed out in the previous rule, you can do postprocessing to increase
diversity or relevance. If you see longer term objectives increase, then you can
declare that diversity/relevance is valuable, aside from popularity. You can
then either continue to use your postprocessing, or directly modify the
objective based upon diversity or relevance.
Rule #43: Your friends tend to be the same across different products. Your interests tend not to be.
Teams at Google have gotten a lot of traction from taking a model predicting the
closeness of a connection in one product, and having it work well on another.
Your friends are who they are. On the other hand, I have watched several teams
struggle with personalization features across product divides. Yes, it seems
like it should work. For now, it doesn’t seem like it does. What has sometimes
worked is using raw data from one property to predict behavior on another. Also,
keep in mind that even knowing that a user has a history on another property can
help. For instance, the presence of user activity on two products may be
indicative in and of itself.
Related Work
There are many documents on machine learning at Google as well as externally.
Thanks to David Westbrook, Peter Brandt, Samuel Ieong, Chenyu Zhao, Li Wei,
Michalis Potamias, Evan Rosen, Barry Rosenberg, Christine Robson, James Pine,
Tal Shaked, Tushar Chandra, Mustafa Ispir, Jeremiah Harmsen, Konstantinos
Katsiapis, Glen Anderson, Dan Duckworth, Shishir Birmiwal, Gal Elidan, Su Lin
Wu, Jaihui Liu, Fernando Pereira, and Hrishikesh Aradhye for many corrections,
suggestions, and helpful examples for this document. Also, thanks to Kristen
Lefevre, Suddha Basu, and Chris Berg who helped with an earlier version. Any
errors, omissions, or (gasp!) unpopular opinions are my own.
Appendix
There are a variety of references to Google products in this document. To
provide more context, I give a short description of the most common examples
below.
YouTube Overview
YouTube is a streaming video service. Both YouTube Watch Next and YouTube Home
Page teams use ML models to rank video recommendations. Watch Next recommends
videos to watch after the currently playing one, while Home Page recommends
videos to users browsing the home page.
Google Play Overview
Google Play has many models solving a variety of problems. Play Search, Play
Home Page Personalized Recommendations, and ‘Users Also Installed’ apps all use
machine learning.
Google Plus Overview
Google Plus used machine learning in a variety of situations: ranking posts in
the "stream" of posts being seen by the user, ranking "What’s Hot" posts (posts
that are very popular now), ranking people you know, et cetera. Google Plus
closed down all personal accounts in 2019, and was replaced by Google Currents
for business accounts on July 6, 2020.
sqlite3 — DB-API 2.0 interface for SQLite databases
Assigned source reading · Python Software Foundation and Python documentation contributors
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.
SQLite is a C library that provides a lightweight disk-based database that
doesn’t require a separate server process and allows accessing the database
using a nonstandard variant of the SQL query language. Some applications can use
SQLite for internal data storage. It’s also possible to prototype an
application using SQLite and then port the code to a larger database such as
PostgreSQL or Oracle.
The sqlite3 module was written by Gerhard Häring. It provides an SQL interface
compliant with the DB-API 2.0 specification described by PEP 249, and
requires the third-party SQLite library.
This is an optional module.
If it is missing from your copy of CPython,
look for documentation from your distributor (that is,
whoever provided Python to you).
If you are the distributor, see Requirements for optional modules.
In this tutorial, you will create a database of Monty Python movies
using basic sqlite3 functionality.
It assumes a fundamental understanding of database concepts,
including cursors and transactions.
First, we need to create a new database and open
a database connection to allow sqlite3 to work with it.
Call sqlite3.connect() to create a connection to
the database tutorial.db in the current working directory,
implicitly creating it if it does not exist:
importsqlite3con=sqlite3.connect("tutorial.db")
The returned Connection object con
represents the connection to the on-disk database.
In order to execute SQL statements and fetch results from SQL queries,
we will need to use a database cursor.
Call con.cursor() to create the Cursor:
cur=con.cursor()
Now that we’ve got a database connection and a cursor,
we can create a database table movie with columns for title,
release year, and review score.
For simplicity, we can just use column names in the table declaration –
thanks to the flexible typing feature of SQLite,
specifying the data types is optional.
Execute the CREATETABLE statement
by calling cur.execute(...):
We can verify that the new table has been created by querying
the sqlite_master table built-in to SQLite,
which should now contain an entry for the movie table definition
(see The Schema Table for details).
Execute that query by calling cur.execute(...),
assign the result to res,
and call res.fetchone() to fetch the resulting row:
>>> res=cur.execute("SELECT name FROM sqlite_master")>>> res.fetchone()('movie',)
We can see that the table has been created,
as the query returns a tuple containing the table’s name.
If we query sqlite_master for a non-existent table spam,
res.fetchone() will return None:
>>> res=cur.execute("SELECT name FROM sqlite_master WHERE name='spam'")>>> res.fetchone()isNoneTrue
Now, add two rows of data supplied as SQL literals
by executing an INSERT statement,
once again by calling cur.execute(...):
cur.execute(""" INSERT INTO movie VALUES ('Monty Python and the Holy Grail', 1975, 8.2), ('And Now for Something Completely Different', 1971, 7.5)""")
The INSERT statement implicitly opens a transaction,
which needs to be committed before changes are saved in the database
(see Transaction control for details).
Call con.commit() on the connection object
to commit the transaction:
con.commit()
We can verify that the data was inserted correctly
by executing a SELECT query.
Use the now-familiar cur.execute(...) to
assign the result to res,
and call res.fetchall() to return all resulting rows:
>>> res=cur.execute("SELECT score FROM movie")>>> res.fetchall()[(8.2,), (7.5,)]
The result is a list of two tuples, one per row,
each containing that row’s score value.
data=[("Monty Python Live at the Hollywood Bowl",1982,7.9),("Monty Python's The Meaning of Life",1983,7.5),("Monty Python's Life of Brian",1979,8.0),]cur.executemany("INSERT INTO movie VALUES(?, ?, ?)",data)con.commit()# Remember to commit the transaction after executing INSERT.
We can verify that the new rows were inserted
by executing a SELECT query,
this time iterating over the results of the query:
>>> forrowincur.execute("SELECT year, title FROM movie ORDER BY year"):... print(row)(1971, 'And Now for Something Completely Different')(1975, 'Monty Python and the Holy Grail')(1979, "Monty Python's Life of Brian")(1982, 'Monty Python Live at the Hollywood Bowl')(1983, "Monty Python's The Meaning of Life")
Each row is a two-item tuple of (year,title),
matching the columns selected in the query.
Finally, verify that the database has been written to disk
by calling con.close()
to close the existing connection, opening a new one,
creating a new cursor, then querying the database:
>>> con.close()>>> new_con=sqlite3.connect("tutorial.db")>>> new_cur=new_con.cursor()>>> res=new_cur.execute("SELECT title, year FROM movie ORDER BY score DESC")>>> title,year=res.fetchone()>>> print(f'The highest scoring Monty Python movie is {title!r}, released in {year}')The highest scoring Monty Python movie is 'Monty Python and the Holy Grail', released in 1975>>> new_con.close()
You’ve now created an SQLite database using the sqlite3 module,
inserted data and retrieved values from it in multiple ways.
timeout (float) – How many seconds the connection should wait before raising
an OperationalError when a table is locked.
If another connection opens a transaction to modify a table,
that table will be locked until the transaction is committed.
Default five seconds.
detect_types (int) – Control whether and how data types not
natively supported by SQLite
are looked up to be converted to Python types,
using the converters registered with register_converter().
Set it to any combination (using |, bitwise or) of
PARSE_DECLTYPES and PARSE_COLNAMES
to enable this.
Column names take precedence over declared types if both flags are set.
By default (0), type detection is disabled.
check_same_thread (bool) – If True (default), ProgrammingError will be raised
if the database connection is used by a thread
other than the one that created it.
If False, the connection may be accessed in multiple threads;
write operations may need to be serialized by the user
to avoid data corruption.
See threadsafety for more information.
factory (Connection) – A custom subclass of Connection to create the connection with,
if not the default Connection class.
cached_statements (int) – The number of statements that sqlite3
should internally cache for this connection, to avoid parsing overhead.
By default, 128 statements.
uri (bool) – If set to True, database is interpreted as a
URI with a file path
and an optional query string.
The scheme part must be "file:",
and the path can be relative or absolute.
The query string allows passing parameters to SQLite,
enabling various How to work with SQLite URIs.
Raises an auditing eventsqlite3.connect with argument database.
Raises an auditing eventsqlite3.connect/handle with argument connection_handle.
Changed in version 3.4: Added the uri parameter.
Changed in version 3.7: database can now also be a path-like object, not only a string.
Changed in version 3.10: Added the sqlite3.connect/handle auditing event.
Changed in version 3.12: Added the autocommit parameter.
Changed in version 3.15: All parameters except database are now keyword-only.
sqlite3.complete_statement(statement)
Return True if the string statement appears to contain
one or more complete SQL statements.
No syntactic verification or parsing of any kind is performed,
other than checking that there are no unclosed string literals
and the statement is terminated by a semicolon.
For example:
>>> sqlite3.complete_statement("SELECT foo FROM bar;")True>>> sqlite3.complete_statement("SELECT foo")False
This function may be useful during command-line input
to determine if the entered text seems to form a complete SQL statement,
or if additional input is needed before calling execute().
Enable or disable callback tracebacks.
By default you will not get any tracebacks in user-defined functions,
aggregates, converters, authorizer callbacks etc. If you want to debug them,
you can call this function with flag set to True. Afterwards, you
will get tracebacks from callbacks on sys.stderr. Use False
to disable the feature again.
Note
Errors in user-defined function callbacks are logged as unraisable exceptions.
Use an unraisablehookhandler for
introspection of the failed callback.
sqlite3.register_adapter(type, adapter, /)
Register an adaptercallable to adapt the Python type type
into an SQLite type.
The adapter is called with a Python object of type type as its sole
argument, and must return a value of a
type that SQLite natively understands.
Register the convertercallable to convert SQLite objects of type
typename into a Python object of a specific type.
The converter is invoked for all SQLite values of type typename;
it is passed a bytes object and should return an object of the
desired Python type.
Consult the parameter detect_types of
connect() for information regarding how type detection works.
Note: typename and the name of the type in your query are matched
case-insensitively.
Pass this flag value to the detect_types parameter of
connect() to look up a converter function using
the declared types for each column.
The types are declared when the database table is created.
sqlite3 will look up a converter function using the first word of the
declared type as the converter dictionary key.
For example:
This flag may be combined with PARSE_COLNAMES using the |
(bitwise or) operator.
Note
Generated fields (for example MAX(p)) are returned as str.
Use PARSE_COLNAMES to enforce types for such queries.
sqlite3.PARSE_COLNAMES
Pass this flag value to the detect_types parameter of
connect() to look up a converter function by
using the type name, parsed from the query column name,
as the converter dictionary key.
The query column name must be wrapped in double quotes (")
and the type name must be wrapped in square brackets ([]).
This constant is only available if Python was compiled with SQLite
3.24.0 or greater.
Added in version 3.15.
sqlite3.threadsafety
Integer constant required by the DB-API 2.0, stating the level of thread
safety the sqlite3 module supports. This attribute is set based on
the default threading mode the
underlying SQLite library is compiled with. The SQLite threading modes are:
Single-thread: In this mode, all mutexes are disabled and SQLite is
unsafe to use in more than a single thread at once.
Multi-thread: In this mode, SQLite can be safely used by multiple
threads provided that no single database connection is used
simultaneously in two or more threads.
Serialized: In serialized mode, SQLite can be safely used by
multiple threads with no restriction.
The mappings from SQLite threading modes to DB-API 2.0 threadsafety levels
are as follows:
Deprecated since version 3.12, removed in version 3.14: The version and version_info constants.
Connection objects
classsqlite3.Connection
Each open SQLite database is represented by a Connection object,
which is created using sqlite3.connect().
Their main purpose is creating Cursor objects,
and Transaction control.
Changed in version 3.13: A ResourceWarning is emitted if close() is not called before
a Connection object is deleted.
An SQLite database connection has the following attributes and methods:
cursor(factory=Cursor)
Create and return a Cursor object.
The cursor method accepts a single optional parameter factory. If
supplied, this must be a callable returning
an instance of Cursor or its subclasses.
The blob size cannot be changed using the Blob class.
Use the SQL function zeroblob to create a blob with a fixed size.
Added in version 3.11.
commit()
Commit any pending transaction to the database.
If autocommit is True, or there is no open transaction,
this method does nothing.
If autocommit is False, a new transaction is implicitly
opened if a pending transaction was committed by this method.
rollback()
Roll back to the start of any pending transaction.
If autocommit is True, or there is no open transaction,
this method does nothing.
If autocommit is False, a new transaction is implicitly
opened if a pending transaction was rolled back by this method.
close()
Close the database connection.
If autocommit is False,
any pending transaction is implicitly rolled back.
If autocommit is True or LEGACY_TRANSACTION_CONTROL,
no implicit transaction control is executed.
Make sure to commit() before closing
to avoid losing pending changes.
execute(sql, parameters=(), /)
Create a new Cursor object and call
execute() on it with the given sql and parameters.
Return the new cursor object.
executemany(sql, parameters, /)
Create a new Cursor object and call
executemany() on it with the given sql and parameters.
Return the new cursor object.
executescript(sql_script, /)
Create a new Cursor object and call
executescript() on it with the given sql_script.
Return the new cursor object.
The number of arguments that the step() method must accept
is controlled by n_arg.
Set to None to remove an existing SQL aggregate function.
Changed in version 3.15: All three parameters are now positional-only.
Example:
classMySum:def__init__(self):self.count=0defstep(self,value):self.count+=valuedeffinalize(self):returnself.countcon=sqlite3.connect(":memory:")con.create_aggregate("mysum",1,MySum)cur=con.execute("CREATE TABLE test(i)")cur.execute("INSERT INTO test(i) VALUES(1)")cur.execute("INSERT INTO test(i) VALUES(2)")cur.execute("SELECT mysum(i) FROM test")print(cur.fetchone()[0])con.close()
The number of arguments that the step() and value() methods
must accept is controlled by num_params.
Set to None to remove an existing SQL aggregate window function.
Raises:
NotSupportedError – If used with a version of SQLite older than 3.25.0,
which does not support aggregate window functions.
Added in version 3.11.
Example:
# Example taken from https://www.sqlite.org/windowfunctions.html#udfwinfuncclassWindowSumInt:def__init__(self):self.count=0defstep(self,value):"""Add a row to the current window."""self.count+=valuedefvalue(self):"""Return the current value of the aggregate."""returnself.countdefinverse(self,value):"""Remove a row from the current window."""self.count-=valuedeffinalize(self):"""Return the final value of the aggregate. Any clean-up actions should be placed here. """returnself.countcon=sqlite3.connect(":memory:")cur=con.execute("CREATE TABLE test(x, y)")values=[("a",4),("b",5),("c",3),("d",8),("e",1),]cur.executemany("INSERT INTO test VALUES(?, ?)",values)con.create_window_function("sumint",1,WindowSumInt)cur.execute(""" SELECT x, sumint(y) OVER ( ORDER BY x ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING ) AS sum_y FROM test ORDER BY x""")print(cur.fetchall())con.close()
create_collation(name, callable, /)
Create a collation named name using the collating function callable.
callable is passed two string arguments,
and it should return an integer:
1 if the first is ordered higher than the second
-1 if the first is ordered lower than the second
0 if they are ordered equal
The following example shows a reverse sorting collation:
defcollate_reverse(string1,string2):ifstring1==string2:return0elifstring1<string2:return1else:return-1con=sqlite3.connect(":memory:")con.create_collation("reverse",collate_reverse)cur=con.execute("CREATE TABLE test(x)")cur.executemany("INSERT INTO test(x) VALUES(?)",[("a",),("b",)])cur.execute("SELECT x FROM test ORDER BY x COLLATE reverse")forrowincur:print(row)con.close()
Remove a collation function by setting callable to None.
Changed in version 3.11: The collation name can contain any Unicode character. Earlier, only
ASCII characters were allowed.
interrupt()
Call this method from a different thread to abort any queries that might
be executing on the connection.
Aborted queries will raise an OperationalError.
set_authorizer(authorizer_callback, /)
Register callableauthorizer_callback to be invoked
for each attempt to access a column of a table in the database.
The callback should return one of SQLITE_OK,
SQLITE_DENY, or SQLITE_IGNORE
to signal how access to the column should be handled
by the underlying SQLite library.
The first argument to the callback signifies what kind of operation is to be
authorized. The second and third argument will be arguments or None
depending on the first argument. The 4th argument is the name of the database
(“main”, “temp”, etc.) if applicable. The 5th argument is the name of the
inner-most trigger or view that is responsible for the access attempt or
None if this access attempt is directly from input SQL code.
Please consult the SQLite documentation about the possible values for the first
argument and the meaning of the second and third argument depending on the first
one. All necessary constants are available in the sqlite3 module.
Passing None as authorizer_callback will disable the authorizer.
Changed in version 3.11: Added support for disabling the authorizer using None.
Changed in version 3.15: The only parameter is now positional-only.
set_progress_handler(progress_handler, /, n)
Register callableprogress_handler to be invoked for every n
instructions of the SQLite virtual machine. This is useful if you want to
get called from SQLite during long-running operations, for example to update
a GUI.
If you want to clear any previously installed progress handler, call the
method with None for progress_handler.
Returning a non-zero value from the handler function will terminate the
currently executing query and cause it to raise a DatabaseError
exception.
Changed in version 3.15: The first parameter is now positional-only.
set_trace_callback(trace_callback, /)
Register callabletrace_callback to be invoked
for each SQL statement that is actually executed by the SQLite backend.
The only argument passed to the callback is the statement (as
str) that is being executed. The return value of the callback is
ignored. Note that the backend does not only run statements passed to the
Cursor.execute() methods. Other sources include the
transaction management of the
sqlite3 module and the execution of triggers defined in the current
database.
Passing None as trace_callback will disable the trace callback.
Note
Exceptions raised in the trace callback are not propagated. As a
development and debugging aid, use
enable_callback_tracebacks() to enable printing
tracebacks from exceptions raised in the trace callback.
Added in version 3.3.
Changed in version 3.15: The first parameter is now positional-only.
enable_load_extension(enabled, /)
Enable the SQLite engine to load SQLite extensions from shared libraries
if enabled is True;
else, disallow loading SQLite extensions.
SQLite extensions can define new functions,
aggregates or whole new virtual table implementations. One well-known
extension is the fulltext-search extension distributed with SQLite.
Note
The sqlite3 module is not built with loadable extension support by
default, because some platforms (notably macOS) have SQLite
libraries which are compiled without this feature.
To get loadable extension support,
you must pass the --enable-loadable-sqlite-extensions option
to configure.
Raises an auditing eventsqlite3.enable_load_extension with arguments connection, enabled.
Added in version 3.2.
Changed in version 3.10: Added the sqlite3.enable_load_extension auditing event.
con.enable_load_extension(True)# Load the fulltext search extensioncon.execute("select load_extension('./fts3.so')")# alternatively you can load the extension using an API call:# con.load_extension("./fts3.so")# disable extension loading againcon.enable_load_extension(False)# example from SQLite wikicon.execute("CREATE VIRTUAL TABLE recipe USING fts3(name, ingredients)")con.executescript(""" INSERT INTO recipe (name, ingredients) VALUES('broccoli stew', 'broccoli peppers cheese tomatoes'); INSERT INTO recipe (name, ingredients) VALUES('pumpkin stew', 'pumpkin onions garlic celery'); INSERT INTO recipe (name, ingredients) VALUES('broccoli pie', 'broccoli cheese onions flour'); INSERT INTO recipe (name, ingredients) VALUES('pumpkin pie', 'pumpkin sugar flour butter'); """)forrowincon.execute("SELECT rowid, name, ingredients FROM recipe WHERE name MATCH 'pie'"):print(row)
load_extension(path, /, *, entrypoint=None)
Load an SQLite extension from a shared library.
Enable extension loading with enable_load_extension() before
calling this method.
entrypoint (str | None) – Entry point name.
If None (the default),
SQLite will come up with an entry point name of its own;
see the SQLite docs Loading an Extension for details.
Raises an auditing eventsqlite3.load_extension with arguments connection, path.
Added in version 3.2.
Changed in version 3.10: Added the sqlite3.load_extension auditing event.
Changed in version 3.12: Added the entrypoint parameter.
iterdump(*, filter=None)
Return an iterator to dump the database as SQL source code.
Useful when saving an in-memory database for later restoration.
Similar to the .dump command in the sqlite3 shell.
Parameters:
filter (str | None) – An optional LIKE pattern for database objects to dump, e.g. prefix_%.
If None (the default), all database objects will be included.
Example:
# Convert file example.db to SQL dump file dump.sqlcon=sqlite3.connect('example.db')withopen('dump.sql','w')asf:forlineincon.iterdump():f.write('%s\n'%line)con.close()
Works even if the database is being accessed by other clients
or concurrently by the same connection.
Parameters:
target (Connection) – The database connection to save the backup to.
pages (int) – The number of pages to copy at a time.
If equal to or less than 0,
the entire database is copied in a single step.
Defaults to -1.
progress (callback | None) – If set to a callable,
it is invoked with three integer arguments for every backup iteration:
the status of the last iteration,
the remaining number of pages still to be copied,
and the total number of pages.
Defaults to None.
name (str) – The name of the database to back up.
Either "main" (the default) for the main database,
"temp" for the temporary database,
or the name of a custom database as attached using the
ATTACHDATABASE SQL statement.
sleep (float) – The number of seconds to sleep between successive attempts
to back up remaining pages.
Example 1, copy an existing database into another:
defprogress(status,remaining,total):print(f'Copied {total-remaining} of {total} pages...')src=sqlite3.connect('example.db')dst=sqlite3.connect('backup.db')withdst:src.backup(dst,pages=1,progress=progress)dst.close()src.close()
Example 2, copy an existing database into a transient copy:
Set a connection runtime limit.
Attempts to increase a limit above its hard upper bound are silently
truncated to the hard upper bound. Regardless of whether or not the limit
was changed, the prior value of the limit is returned.
enable (bool) – True if the configuration option should be enabled (default);
False if it should be disabled.
Added in version 3.12.
serialize(*, name='main')
Serialize a database into a bytes object. For an
ordinary on-disk database file, the serialization is just a copy of the
disk file. For an in-memory database or a “temp” database, the
serialization is the same sequence of bytes which would be written to
disk if that database were backed up to disk.
Parameters:
name (str) – The database name to be serialized.
Defaults to "main".
This method is only available if the underlying SQLite library has the
serialize API.
Added in version 3.11.
deserialize(data, /, *, name='main')
Deserialize a serialized database into a
Connection.
This method causes the database connection to disconnect from database
name, and reopen name as an in-memory database based on the
serialization contained in data.
This method is only available if the underlying SQLite library has the
deserialize API.
Added in version 3.11.
autocommit
This attribute controls PEP 249-compliant transaction behaviour.
autocommit has three allowed values:
False: Select PEP 249-compliant transaction behaviour,
implying that sqlite3 ensures a transaction is always open.
Use commit() and rollback() to close transactions.
If not overridden by the isolation_level parameter of connect(),
the default is "", which is an alias for "DEFERRED".
Note
Using autocommit to control transaction handling is
recommended over using isolation_level.
isolation_level has no effect unless autocommit is
set to LEGACY_TRANSACTION_CONTROL (the default).
row_factory
The initial row_factory
for Cursor objects created from this connection.
Assigning to this attribute does not affect the row_factory
of existing cursors belonging to this connection, only new ones.
Is None by default,
meaning each row is returned as a tuple.
Changed in version 3.15: Deleting the row_factory attribute is no longer allowed.
text_factory
A callable that accepts a bytes parameter
and returns a text representation of it.
The callable is invoked for SQLite values with the TEXT data type.
By default, this attribute is set to str.
If autocommit is
LEGACY_TRANSACTION_CONTROL,
isolation_level is not None,
sql is an INSERT, UPDATE, DELETE, or REPLACE statement,
and there is no open transaction,
a transaction is implicitly opened before executing sql.
ProgrammingError – When sql contains more than one SQL statement
or is not a DML statement,
When named placeholders are used
and the items in parameters are sequences instead of dicts.
Example:
rows=[("row1",),("row2",),]# cur is an sqlite3.Cursor objectcur.executemany("INSERT INTO data VALUES(?)",rows)
Note
Any resulting rows are discarded,
including DML statements with RETURNING clauses.
Execute the SQL statements in sql_script.
If the autocommit is
LEGACY_TRANSACTION_CONTROL
and there is a pending transaction,
an implicit COMMIT statement is executed first.
No other implicit transaction control is performed;
any transaction control must be added to sql_script.
# cur is an sqlite3.Cursor objectcur.executescript(""" BEGIN; CREATE TABLE person(firstname, lastname, age); CREATE TABLE book(title, author, published); CREATE TABLE publisher(name, address); COMMIT;""")
fetchone()
If row_factory is None,
return the next row query result set as a tuple.
Else, pass it to the row factory and return its result.
Return None if no more data is available.
fetchmany(size=cursor.arraysize)
Return the next set of rows of a query result as a list.
Return an empty list if no more rows are available.
The number of rows to fetch per call is specified by the size parameter.
If size is not given, arraysize determines the number of rows
to be fetched.
If fewer than size rows are available,
as many rows as are available are returned.
Note there are performance considerations involved with the size parameter.
For optimal performance, it is usually best to use the arraysize attribute.
If the size parameter is used, then it is best for it to retain the same
value from one fetchmany() call to the next.
Changed in version 3.15: Negative size values are rejected by raising ValueError.
fetchall()
Return all (remaining) rows of a query result as a list.
Return an empty list if no rows are available.
Note that the arraysize attribute can affect the performance of
this operation.
close()
Close the cursor now (rather than whenever __del__ is called).
The cursor will be unusable from this point forward; a ProgrammingError
exception will be raised if any operation is attempted with the cursor.
setinputsizes(sizes, /)
Required by the DB-API. Does nothing in sqlite3.
setoutputsize(size, column=None, /)
Required by the DB-API. Does nothing in sqlite3.
arraysize
Read/write attribute that controls the number of rows returned by fetchmany().
The default value is 1 which means a single row would be fetched per call.
Changed in version 3.15: Negative values are rejected by raising ValueError.
connection
Read-only attribute that provides the SQLite database Connection
belonging to the cursor. A Cursor object created by
calling con.cursor() will have a
connection attribute that refers to con:
Read-only attribute that provides the column names of the last query. To
remain compatible with the Python DB API, it returns a 7-tuple for each
column where the last six items of each tuple are None.
It is set for SELECT statements without any matching rows as well.
lastrowid
Read-only attribute that provides the row id of the last inserted row. It
is only updated after successful INSERT or REPLACE statements
using the execute() method. For other statements, after
executemany() or executescript(), or if the insertion failed,
the value of lastrowid is left unchanged. The initial value of
lastrowid is None.
Note
Inserts into WITHOUTROWID tables are not recorded.
Changed in version 3.6: Added support for the REPLACE statement.
rowcount
Read-only attribute that provides the number of modified rows for
INSERT, UPDATE, DELETE, and REPLACE statements;
is -1 for other statements,
including CTE queries.
It is only updated by the execute() and executemany() methods,
after the statement has run to completion.
This means that any resulting rows must be fetched in order for
rowcount to be updated.
row_factory
Control how a row fetched from this Cursor is represented.
If None, a row is represented as a tuple.
Can be set to the included sqlite3.Row;
or a callable that accepts two arguments,
a Cursor object and the tuple of row values,
and returns a custom object representing an SQLite row.
Defaults to what Connection.row_factory was set to
when the Cursor was created.
Assigning to this attribute does not affect
Connection.row_factory of the parent connection.
Changed in version 3.15: Deleting the row_factory attribute is no longer allowed.
Row objects
classsqlite3.Row
A Row instance serves as a highly optimized
row_factory for Connection objects.
It supports iteration, equality testing, len(),
and mapping access by column name and index.
Two Row objects compare equal
if they have identical column names and values.
Return a list of column names as strings.
Immediately after a query,
it is the first member of each tuple in Cursor.description.
Changed in version 3.5: Added support of slicing.
Blob objects
classsqlite3.Blob
Added in version 3.11.
A Blob instance is a file-like object
that can read and write data in an SQLite BLOB.
Call len(blob) to get the size (number of bytes) of the blob.
Use indices and slices for direct access to the blob data.
Use the Blob as a context manager to ensure that the blob
handle is closed after use.
con=sqlite3.connect(":memory:")con.execute("CREATE TABLE test(blob_col blob)")con.execute("INSERT INTO test(blob_col) VALUES(zeroblob(13))")# Write to our blob, using two write operations:withcon.blobopen("test","blob_col",1)asblob:blob.write(b"hello, ")blob.write(b"world.")# Modify the first and last bytes of our blobblob[0]=ord("H")blob[-1]=ord("!")# Read the contents of our blobwithcon.blobopen("test","blob_col",1)asblob:greeting=blob.read()print(greeting)# outputs "b'Hello, world!'"con.close()
close()
Close the blob.
The blob will be unusable from this point onward. An
Error (or subclass) exception will be raised if any
further operation is attempted with the blob.
read(length=-1, /)
Read length bytes of data from the blob at the current offset position.
If the end of the blob is reached, the data up to
EOF will be returned. When length is not
specified, or is negative, read() will read until the end of
the blob.
write(data, /)
Write data to the blob at the current offset. This function cannot
change the blob length. Writing beyond the end of the blob will raise
ValueError.
tell()
Return the current access position of the blob.
seek(offset, origin=os.SEEK_SET, /)
Set the current access position of the blob to offset. The origin
argument defaults to os.SEEK_SET (absolute blob positioning).
Other values for origin are os.SEEK_CUR (seek relative to the
current position) and os.SEEK_END (seek relative to the blob’s
end).
The exception hierarchy is defined by the DB-API 2.0 (PEP 249).
exceptionsqlite3.Warning
This exception is not currently raised by the sqlite3 module,
but may be raised by applications using sqlite3,
for example if a user-defined function truncates data while inserting.
Warning is a subclass of Exception.
exceptionsqlite3.Error
The base class of the other exceptions in this module.
Use this to catch all errors with one single except statement.
Error is a subclass of Exception.
If the exception originated from within the SQLite library,
the following two attributes are added to the exception:
The symbolic name of the numeric error code
from the SQLite API
Added in version 3.11.
exceptionsqlite3.InterfaceError
Exception raised for misuse of the low-level SQLite C API.
In other words, if this exception is raised, it probably indicates a bug in the
sqlite3 module.
InterfaceError is a subclass of Error.
exceptionsqlite3.DatabaseError
Exception raised for errors that are related to the database.
This serves as the base exception for several types of database errors.
It is only raised implicitly through the specialised subclasses.
DatabaseError is a subclass of Error.
exceptionsqlite3.DataError
Exception raised for errors caused by problems with the processed data,
like numeric values out of range, and strings which are too long.
DataError is a subclass of DatabaseError.
exceptionsqlite3.OperationalError
Exception raised for errors that are related to the database’s operation,
and not necessarily under the control of the programmer.
For example, the database path is not found,
or a transaction could not be processed.
OperationalError is a subclass of DatabaseError.
exceptionsqlite3.IntegrityError
Exception raised when the relational integrity of the database is affected,
e.g. a foreign key check fails. It is a subclass of DatabaseError.
exceptionsqlite3.InternalError
Exception raised when SQLite encounters an internal error.
If this is raised, it may indicate that there is a problem with the runtime
SQLite library.
InternalError is a subclass of DatabaseError.
exceptionsqlite3.ProgrammingError
Exception raised for sqlite3 API programming errors,
for example supplying the wrong number of bindings to a query,
or trying to operate on a closed Connection.
ProgrammingError is a subclass of DatabaseError.
exceptionsqlite3.NotSupportedError
Exception raised in case a method or database API is not supported by the
underlying SQLite library. For example, setting deterministic to
True in create_function(), if the underlying SQLite library
does not support deterministic functions.
NotSupportedError is a subclass of DatabaseError.
SQLite and Python types
SQLite natively supports the following types: NULL, INTEGER,
REAL, TEXT, BLOB.
The following Python types can thus be sent to SQLite without any problem:
The type system of the sqlite3 module is extensible in two ways: you can
store additional Python types in an SQLite database via
object adapters,
and you can let the sqlite3 module convert SQLite types to
Python types via converters.
Default adapters and converters (deprecated)
Note
The default adapters and converters are deprecated as of Python 3.12.
Instead, use the Adapter and converter recipes
and tailor them to your needs.
The deprecated default adapters and converters consist of:
A converter for declared “timestamp” types to
datetime.datetime objects.
Fractional parts will be truncated to 6 digits (microsecond precision).
Note
The default “timestamp” converter ignores UTC offsets in the database and
always returns a naive datetime.datetime object. To preserve UTC
offsets in timestamps, either leave converters disabled, or register an
offset-aware converter with register_converter().
Deprecated since version 3.12.
Command-line interface
The sqlite3 module can be invoked as a script,
using the interpreter’s -m switch,
in order to provide a simple SQLite shell.
The argument signature is as follows:
python-msqlite3[-h][-v][filename][sql]
Type .quit or CTRL-D to exit the shell.
-h,--help
Print CLI help.
-v,--version
Print underlying SQLite library version.
Added in version 3.12.
How-to guides
How to use placeholders to bind values in SQL queries
SQL operations usually need to use values from Python variables. However,
beware of using Python’s string operations to assemble queries, as they
are vulnerable to SQL injection attacks. For example, an attacker can simply
close the single quote and inject ORTRUE to select all rows:
>>> # Never do this -- insecure!>>> symbol=input()' OR TRUE; -->>> sql="SELECT * FROM stocks WHERE symbol = '%s'"%symbol>>> print(sql)SELECT * FROM stocks WHERE symbol = '' OR TRUE; --'>>> cur.execute(sql)
Instead, use the DB-API’s parameter substitution. To insert a variable into a
query string, use a placeholder in the string, and substitute the actual values
into the query by providing them as a tuple of values to the second
argument of the cursor’s execute() method.
An SQL statement may use one of two kinds of placeholders:
question marks (qmark style) or named placeholders (named style).
For the qmark style, parameters must be a
sequence whose length must match the number of placeholders,
or a ProgrammingError is raised.
For the named style, parameters must be
an instance of a dict (or a subclass),
which must contain keys for all named parameters;
any extra items are ignored.
Here’s an example of both styles:
con=sqlite3.connect(":memory:")cur=con.execute("CREATE TABLE lang(name, first_appeared)")# This is the named style used with executemany():data=({"name":"C","year":1972},{"name":"Fortran","year":1957},{"name":"Python","year":1991},{"name":"Go","year":2009},)cur.executemany("INSERT INTO lang VALUES(:name, :year)",data)# This is the qmark style used in a SELECT query:params=(1972,)cur.execute("SELECT * FROM lang WHERE first_appeared = ?",params)print(cur.fetchall())con.close()
Note
PEP 249 numeric placeholders are not supported.
If used, they will be interpreted as named placeholders.
How to adapt custom Python types to SQLite values
SQLite supports only a limited set of data types natively.
To store custom Python types in SQLite databases, adapt them to one of the
Python types SQLite natively understands.
There are two ways to adapt Python objects to SQLite types:
letting your object adapt itself, or using an adapter callable.
The latter will take precedence above the former.
For a library that exports a custom type,
it may make sense to enable that type to adapt itself.
As an application developer, it may make more sense to take direct control by
registering custom adapter functions.
How to write adaptable objects
Suppose we have a Point class that represents a pair of coordinates,
x and y, in a Cartesian coordinate system.
The coordinate pair will be stored as a text string in the database,
using a semicolon to separate the coordinates.
This can be implemented by adding a __conform__(self,protocol)
method which returns the adapted value.
The object passed to protocol will be of type PrepareProtocol.
The other possibility is to create a function that converts the Python object
to an SQLite-compatible type.
This function can then be registered using register_adapter().
How to convert SQLite values to custom Python types
Writing an adapter lets you convert from custom Python types to SQLite
values.
To be able to convert from SQLite values to custom Python types,
we use converters.
Let’s go back to the Point class. We stored the x and y coordinates
separated via semicolons as strings in SQLite.
First, we’ll define a converter function that accepts the string as a parameter
and constructs a Point object from it.
Note
Converter functions are always passed a bytes object,
no matter the underlying SQLite data type.
We now need to tell sqlite3 when it should convert a given SQLite value.
This is done when connecting to a database, using the detect_types parameter
of connect(). There are three options:
Both: set detect_types to
sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES.
Column names take precedence over declared types.
The following example illustrates the implicit and explicit approaches:
classPoint:def__init__(self,x,y):self.x,self.y=x,ydef__repr__(self):returnf"Point({self.x}, {self.y})"defadapt_point(point):returnf"{point.x};{point.y}"defconvert_point(s):x,y=list(map(float,s.split(b";")))returnPoint(x,y)# Register the adapter and convertersqlite3.register_adapter(Point,adapt_point)sqlite3.register_converter("point",convert_point)# 1) Parse using declared typesp=Point(4.0,-3.2)con=sqlite3.connect(":memory:",detect_types=sqlite3.PARSE_DECLTYPES)cur=con.execute("CREATE TABLE test(p point)")cur.execute("INSERT INTO test(p) VALUES(?)",(p,))cur.execute("SELECT p FROM test")print("with declared types:",cur.fetchone()[0])cur.close()con.close()# 2) Parse using column namescon=sqlite3.connect(":memory:",detect_types=sqlite3.PARSE_COLNAMES)cur=con.execute("CREATE TABLE test(p)")cur.execute("INSERT INTO test(p) VALUES(?)",(p,))cur.execute('SELECT p AS "p [point]" FROM test')print("with column names:",cur.fetchone()[0])cur.close()con.close()
Adapter and converter recipes
This section shows recipes for common adapters and converters.
importdatetimeasdtimportsqlite3defadapt_date_iso(val):"""Adapt datetime.date to ISO 8601 date."""returnval.isoformat()defadapt_datetime_iso(val):"""Adapt datetime.datetime to timezone-naive ISO 8601 date."""returnval.replace(tzinfo=None).isoformat()defadapt_datetime_epoch(val):"""Adapt datetime.datetime to Unix timestamp."""returnint(val.timestamp())sqlite3.register_adapter(dt.date,adapt_date_iso)sqlite3.register_adapter(dt.datetime,adapt_datetime_iso)sqlite3.register_adapter(dt.datetime,adapt_datetime_epoch)defconvert_date(val):"""Convert ISO 8601 date to datetime.date object."""returndt.date.fromisoformat(val.decode())defconvert_datetime(val):"""Convert ISO 8601 datetime to datetime.datetime object."""returndt.datetime.fromisoformat(val.decode())defconvert_timestamp(val):"""Convert Unix epoch timestamp to datetime.datetime object."""returndt.datetime.fromtimestamp(int(val))sqlite3.register_converter("date",convert_date)sqlite3.register_converter("datetime",convert_datetime)sqlite3.register_converter("timestamp",convert_timestamp)
How to use connection shortcut methods
Using the execute(),
executemany(), and executescript()
methods of the Connection class, your code can
be written more concisely because you don’t have to create the (often
superfluous) Cursor objects explicitly. Instead, the Cursor
objects are created implicitly and these shortcut methods return the cursor
objects. This way, you can execute a SELECT statement and iterate over it
directly using only a single call on the Connection object.
# Create and fill the table.con=sqlite3.connect(":memory:")con.execute("CREATE TABLE lang(name, first_appeared)")data=[("C++",1985),("Objective-C",1984),]con.executemany("INSERT INTO lang(name, first_appeared) VALUES(?, ?)",data)# Print the table contentsforrowincon.execute("SELECT name, first_appeared FROM lang"):print(row)print("I just deleted",con.execute("DELETE FROM lang").rowcount,"rows")# close() is not a shortcut method and it's not called automatically;# the connection object should be closed manuallycon.close()
How to use the connection context manager
A Connection object can be used as a context manager that
automatically commits or rolls back open transactions when leaving the body of
the context manager.
If the body of the with statement finishes without exceptions,
the transaction is committed.
If this commit fails,
or if the body of the with statement raises an uncaught exception,
the transaction is rolled back.
If autocommit is False,
a new transaction is implicitly opened after committing or rolling back.
If there is no open transaction upon leaving the body of the with statement,
or if autocommit is True,
the context manager does nothing.
Note
The context manager neither implicitly opens a new transaction
nor closes the connection. If you need a closing context manager, consider
using contextlib.closing().
con=sqlite3.connect(":memory:")con.execute("CREATE TABLE lang(id INTEGER PRIMARY KEY, name VARCHAR UNIQUE)")# Successful, con.commit() is called automatically afterwardswithcon:con.execute("INSERT INTO lang(name) VALUES(?)",("Python",))# con.rollback() is called after the with block finishes with an exception,# the exception is still raised and must be caughttry:withcon:con.execute("INSERT INTO lang(name) VALUES(?)",("Python",))exceptsqlite3.IntegrityError:print("couldn't add Python twice")# Connection object used as context manager only commits or rollbacks transactions,# so the connection object should be closed manuallycon.close()
How to work with SQLite URIs
Some useful URI tricks include:
Open a database in read-only mode:
>>> con=sqlite3.connect("file:tutorial.db?mode=ro",uri=True)>>> con.execute("CREATE TABLE readonly(data)")Traceback (most recent call last):OperationalError: attempt to write a readonly database>>> con.close()
Do not implicitly create a new database file if it does not already exist;
will raise OperationalError if unable to create a new file:
>>> con=sqlite3.connect("file:nosuchdb.db?mode=rw",uri=True)Traceback (most recent call last):OperationalError: unable to open database file
Create a shared named in-memory database:
db="file:mem1?mode=memory&cache=shared"con1=sqlite3.connect(db,uri=True)con2=sqlite3.connect(db,uri=True)withcon1:con1.execute("CREATE TABLE shared(data)")con1.execute("INSERT INTO shared VALUES(28)")res=con2.execute("SELECT data FROM shared")assertres.fetchone()==(28,)con1.close()con2.close()
More information about this feature, including a list of parameters,
can be found in the SQLite URI documentation.
How to create and use row factories
By default, sqlite3 represents each row as a tuple.
If a tuple does not suit your needs,
you can use the sqlite3.Row class
or a custom row_factory.
While row_factory exists as an attribute both on the
Cursor and the Connection,
it is recommended to set Connection.row_factory,
so all cursors created from the connection will use the same row factory.
Row provides indexed and case-insensitive named access to columns,
with minimal memory overhead and performance impact over a tuple.
To use Row as a row factory,
assign it to the row_factory attribute:
>>> res=con.execute("SELECT 'Earth' AS name, 6378 AS radius")>>> row=res.fetchone()>>> row.keys()['name', 'radius']>>> row[0]# Access by index.'Earth'>>> row["name"]# Access by name.'Earth'>>> row["RADIUS"]# Column names are case-insensitive.6378>>> con.close()
Note
The FROM clause can be omitted in the SELECT statement, as in the
above example. In such cases, SQLite returns a single row with columns
defined by expressions, e.g. literals, with the given aliases
exprASalias.
You can create a custom row_factory
that returns each row as a dict, with column names mapped to values:
Using it, queries now return a dict instead of a tuple:
>>> con=sqlite3.connect(":memory:")>>> con.row_factory=dict_factory>>> forrowincon.execute("SELECT 1 AS a, 2 AS b"):... print(row){'a': 1, 'b': 2}>>> con.close()
>>> con=sqlite3.connect(":memory:")>>> con.row_factory=namedtuple_factory>>> cur=con.execute("SELECT 1 AS a, 2 AS b")>>> row=cur.fetchone()>>> rowRow(a=1, b=2)>>> row[0]# Indexed access.1>>> row.b# Attribute access.2>>> con.close()
With some adjustments, the above recipe can be adapted to use a
dataclass, or any other custom class,
instead of a namedtuple.
How to handle non-UTF-8 text encodings
By default, sqlite3 uses str to adapt SQLite values
with the TEXT data type.
This works well for UTF-8 encoded text, but it might fail for other encodings
and invalid UTF-8.
You can use a custom text_factory to handle such cases.
Because of SQLite’s flexible typing, it is not uncommon to encounter table
columns with the TEXT data type containing non-UTF-8 encodings,
or even arbitrary data.
To demonstrate, let’s assume we have a database with ISO-8859-2 (Latin-2)
encoded text, for example a table of Czech-English dictionary entries.
Assuming we now have a Connection instance con
connected to this database,
we can decode the Latin-2 encoded text using this text_factory:
The recommended way of controlling transaction behaviour is through
the Connection.autocommit attribute,
which should preferably be set using the autocommit parameter
of connect().
It is suggested to set autocommit to False,
which implies PEP 249-compliant transaction control.
This means:
sqlite3 ensures that a transaction is always open,
so connect(), Connection.commit(), and Connection.rollback()
will implicitly open a new transaction
(immediately after closing the pending one, for the latter two).
sqlite3 uses BEGINDEFERRED statements when opening transactions.
Transactions should be committed explicitly using commit().
Transactions should be rolled back explicitly using rollback().
An implicit rollback is performed if the database is
close()-ed with pending changes.
If the connection attribute isolation_level
is not None,
new transactions are implicitly opened before
execute() and executemany() executes
INSERT, UPDATE, DELETE, or REPLACE statements;
for other statements, no implicit transaction handling is performed.
Use the commit() and rollback() methods
to respectively commit and roll back pending transactions.
You can choose the underlying SQLite transaction behaviour —
that is, whether and what type of BEGIN statements sqlite3
implicitly executes –
via the isolation_level attribute.
If isolation_level is set to None,
no transactions are implicitly opened at all.
This leaves the underlying SQLite library in autocommit mode,
but also allows the user to perform their own transaction handling
using explicit SQL statements.
The underlying SQLite library autocommit mode can be queried using the
in_transaction attribute.
The executescript() method implicitly commits
any pending transaction before execution of the given SQL script,
regardless of the value of isolation_level.
Changed in version 3.6: sqlite3 used to implicitly commit an open transaction before DDL
statements. This is no longer the case.
Changed in version 3.12: The recommended way of controlling transactions is now via the
autocommit attribute.