Complete Assigned Readings

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

10. Brief tour of the standard library

Assigned source reading · Python Software Foundation and Python documentation contributors

Copyright © 2001 Python Software Foundation; All Rights Reserved

Original source · Python Software Foundation License Version 2 · Retrieved October 25, 2026.

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

Full license and notices
PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
¶
1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and
   the Individual or Organization ("Licensee") accessing and otherwise using this
   software ("Python") in source or binary form and its associated documentation.

2. Subject to the terms and conditions of this License Agreement, PSF hereby
   grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
   analyze, test, perform and/or display publicly, prepare derivative works,
   distribute, and otherwise use Python alone or in any derivative
   version, provided, however, that PSF's License Agreement and PSF's notice of
   copyright, i.e., "Copyright © 2001 Python Software Foundation; All Rights
   Reserved" are retained in Python alone or in any derivative version
   prepared by Licensee.

3. In the event Licensee prepares a derivative work that is based on or
   incorporates Python or any part thereof, and wants to make the
   derivative work available to others as provided herein, then Licensee hereby
   agrees to include in any such work a brief summary of the changes made to Python.

4. PSF is making Python available to Licensee on an "AS IS" basis.
   PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.  BY WAY OF
   EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
   WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE
   USE OF PYTHON WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
   FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
   MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, OR ANY DERIVATIVE
   THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.

6. This License Agreement will automatically terminate upon a material breach of
   its terms and conditions.

7. Nothing in this License Agreement shall be deemed to create any relationship
   of agency, partnership, or joint venture between PSF and Licensee.  This License
   Agreement does not grant permission to use PSF trademarks or trade name in a
   trademark sense to endorse or promote products or services of Licensee, or any
   third party.

8. By copying, installing or otherwise using Python, Licensee agrees
   to be bound by the terms and conditions of this License Agreement.

10. Brief tour of the standard library

10.1. Operating system interface

The os module provides dozens of functions for interacting with the operating system:

>>> import os
>>> os.getcwd()      # Return the current working directory
'C:\\Python315'
>>> os.chdir('/server/accesslogs')   # Change current working directory
>>> os.system('mkdir today')   # Run the command mkdir in the system shell
0

Be sure to use the import os style instead of from os import *. This will keep os.open() from shadowing the built-in open() function which operates much differently.

The built-in dir() and help() functions are useful as interactive aids for working with large modules like os:

>>> import os
>>> dir(os)
<returns a list of all module functions>
>>> help(os)
<returns an extensive manual page created from the module's docstrings>

For daily file and directory management tasks, the shutil module provides a higher-level interface that is easier to use:

>>> import shutil
>>> shutil.copyfile('data.db', 'archive.db')
'archive.db'
>>> shutil.move('/build/executables', 'installdir')
'installdir'

10.2. File wildcards

The glob module provides a function for making file lists from directory wildcard searches:

>>> import glob
>>> glob.glob('*.py')
['primes.py', 'random.py', 'quote.py']

10.3. Command-line arguments

Common utility scripts often need to process command-line arguments. These arguments are stored in the sys module’s argv attribute as a list. For instance, let’s take the following demo.py file:

# File demo.py
import sys
print(sys.argv)

Here is the output from running python demo.py one two three at the command line:

['demo.py', 'one', 'two', 'three']

The argparse module provides a more sophisticated mechanism to process command-line arguments. The following script extracts one or more filenames and an optional number of lines to be displayed:

import argparse

parser = argparse.ArgumentParser(
    prog='top',
    description='Show top lines from each file')
parser.add_argument('filenames', nargs='+')
parser.add_argument('-l', '--lines', type=int, default=10)
args = parser.parse_args()
print(args)

When run at the command line with python top.py --lines=5 alpha.txt beta.txt, the script sets args.lines to 5 and args.filenames to ['alpha.txt', 'beta.txt'].

10.4. Error output redirection and program termination

The sys module also has attributes for stdin, stdout, and stderr. The latter is useful for emitting warnings and error messages to make them visible even when stdout has been redirected:

>>> sys.stderr.write('Warning, log file not found starting a new one\n')
Warning, log file not found starting a new one

The most direct way to terminate a script is to use sys.exit().

10.5. String pattern matching

The re module provides regular expression tools for advanced string processing. For complex matching and manipulation, regular expressions offer succinct, optimized solutions:

>>> import re
>>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
['foot', 'fell', 'fastest']
>>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
'cat in the hat'

When only simple capabilities are needed, string methods are preferred because they are easier to read and debug:

>>> 'tea for too'.replace('too', 'two')
'tea for two'

10.6. Mathematics

The math module gives access to the underlying C library functions for floating-point math:

>>> import math
>>> math.cos(math.pi / 4)
0.70710678118654757
>>> math.log(1024, 2)
10.0

The random module provides tools for making random selections:

>>> import random
>>> random.choice(['apple', 'pear', 'banana'])
'apple'
>>> random.sample(range(100), 10)   # sampling without replacement
[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
>>> random.random()    # random float from the interval [0.0, 1.0)
0.17970987693706186
>>> random.randrange(6)    # random integer chosen from range(6)
4

The statistics module calculates basic statistical properties (the mean, median, variance, etc.) of numeric data:

>>> import statistics
>>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
>>> statistics.mean(data)
1.6071428571428572
>>> statistics.median(data)
1.25
>>> statistics.variance(data)
1.3720238095238095

The SciPy project <https://scipy.org> has many other modules for numerical computations.

10.7. Internet access

There are a number of modules for accessing the internet and processing internet protocols. Two of the simplest are urllib.request for retrieving data from URLs and smtplib for sending mail:

>>> from urllib.request import urlopen
>>> with urlopen('https://docs.python.org/3/') as response:
...     for line in response:
...         line = line.decode()             # Convert bytes to a str
...         if 'updated' in line:
...             print(line.rstrip())         # Remove trailing newline
...
      Last updated on Nov 11, 2025 (20:11 UTC).

>>> import smtplib
>>> server = smtplib.SMTP('localhost')
>>> server.sendmail('soothsayer@example.org', 'jcaesar@example.org',
... """To: jcaesar@example.org
... From: soothsayer@example.org
...
... Beware the Ides of March.
... """)
>>> server.quit()

(Note that the second example needs a mailserver running on localhost.)

10.8. Dates and times

The datetime module supplies classes for manipulating dates and times in both simple and complex ways. While date and time arithmetic is supported, the focus of the implementation is on efficient member extraction for output formatting and manipulation. The module also supports objects that are timezone aware.

>>> # dates are easily constructed and formatted
>>> import datetime as dt
>>> now = dt.date.today()
>>> now
datetime.date(2003, 12, 2)
>>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
'12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'

>>> # dates support calendar arithmetic
>>> birthday = dt.date(1964, 7, 31)
>>> age = now - birthday
>>> age.days
14368

10.9. Data compression

Common data archiving and compression formats are directly supported by modules including: zlib, gzip, bz2, lzma, zipfile and tarfile.

>>> import zlib
>>> s = b'witch which has which witches wrist watch'
>>> len(s)
41
>>> t = zlib.compress(s)
>>> len(t)
37
>>> zlib.decompress(t)
b'witch which has which witches wrist watch'
>>> zlib.crc32(s)
226805979

10.10. Performance measurement

Some Python users develop a deep interest in knowing the relative performance of different approaches to the same problem. Python provides a measurement tool that answers those questions immediately.

For example, it may be tempting to use the tuple packing and unpacking feature instead of the traditional approach to swapping arguments. The timeit module quickly demonstrates a modest performance advantage:

>>> from timeit import Timer
>>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
0.57535828626024577
>>> Timer('a,b = b,a', 'a=1; b=2').timeit()
0.54962537085770791

In contrast to timeit’s fine level of granularity, the profile and pstats modules provide tools for identifying time critical sections in larger blocks of code.

10.11. Quality control

One approach for developing high quality software is to write tests for each function as it is developed and to run those tests frequently during the development process.

The doctest module provides a tool for scanning a module and validating tests embedded in a program’s docstrings. Test construction is as simple as cutting-and-pasting a typical call along with its results into the docstring. This improves the documentation by providing the user with an example and it allows the doctest module to make sure the code remains true to the documentation:

def average(values):
    """Computes the arithmetic mean of a list of numbers.

    >>> print(average([20, 30, 70]))
    40.0
    """
    return sum(values) / len(values)

import doctest
doctest.testmod()   # automatically validate the embedded tests

The unittest module is not as effortless as the doctest module, but it allows a more comprehensive set of tests to be maintained in a separate file:

import unittest

class TestStatisticalFunctions(unittest.TestCase):

    def test_average(self):
        self.assertEqual(average([20, 30, 70]), 40.0)
        self.assertEqual(round(average([1, 5, 7]), 1), 4.3)
        with self.assertRaises(ZeroDivisionError):
            average([])
        with self.assertRaises(TypeError):
            average(20, 30, 70)

unittest.main()  # Calling from the command line invokes all tests

10.12. Batteries included

Python has a “batteries included” philosophy. This is best seen through the sophisticated and robust capabilities of its larger packages. For example:

  • The xmlrpc.client and xmlrpc.server modules make implementing remote procedure calls into an almost trivial task. Despite the modules’ names, no direct knowledge or handling of XML is needed.

  • The email package is a library for managing email messages, including MIME and other RFC 5322-based message documents. Unlike smtplib and poplib which actually send and receive messages, the email package has a complete toolset for building or decoding complex message structures (including attachments) and for implementing internet encoding and header protocols.

  • The json package provides robust support for parsing this popular data interchange format. The csv module supports direct reading and writing of files in Comma-Separated Value format, commonly supported by databases and spreadsheets. XML processing is supported by the xml.etree.ElementTree, xml.dom and xml.sax packages. Together, these modules and packages greatly simplify data interchange between Python applications and other tools.

  • The sqlite3 module is a wrapper for the SQLite database library, providing a persistent database that can be updated and accessed using slightly nonstandard SQL syntax.

  • Internationalization is supported by a number of modules including gettext, locale, and the codecs package.

2 . 4 ArrayDeque: Fast Deque Operations Using an Array

Assigned source reading · Pat Morin

Pat Morin — Open Data Structures, pseudocode edition 0.1G

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

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

Subsections


2.4 ArrayDeque: Fast Deque Operations Using an Array

The ArrayQueue from the previous section is a data structure for representing a sequence that allows us to efficiently add to one end of the sequence and remove from the other end. The ArrayDeque data structure allows for efficient addition and removal at both ends. This structure implements the List interface by using the same circular array technique used to represent an ArrayQueue.


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

The $ \ensuremath{\mathrm{get}(\ensuremath{\mathit{i}})}$ and $ \ensuremath{\mathrm{set}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ operations on an ArrayDeque are straightforward. They get or set the array element $ \ensuremath{\ensuremath{a}[}{\ensuremath{\ensuremath{(\ensuremath{\mathit{j}}+...
...nsuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{a}})}}}\ensuremath{]}$.


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

The implementation of $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ is a little more interesting. As usual, we first check if $ \ensuremath{\ensuremath{\mathit{a}}}$ is full and, if necessary, call $ \ensuremath{\mathrm{resize}()}$ to resize $ \ensuremath{\ensuremath{\mathit{a}}}$. Remember that we want this operation to be fast when $ \ensuremath{\ensuremath{\mathit{i}}}$ is small (close to 0) or when $ \ensuremath{\ensuremath{\mathit{i}}}$ is large (close to $ \ensuremath{\ensuremath{\mathit{n}}}$). Therefore, we check if $ \ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}<\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}/2$. If so, we shift the elements $ \ensuremath{\ensuremath{\ensuremath{\mathit{a}}[0]}},\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{i}}-1]}}$ left by one position. Otherwise ( $ \ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}\ge\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}/2$), we shift the elements $ \ensuremath{\ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{i}}]}},\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{n}}-1]}}$ right by one position. See Figure 2.3 for an illustration of $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ operations on an ArrayDeque.

Figure 2.3: A sequence of $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$ operations on an ArrayDeque. Arrows denote elements being copied.
\includegraphics[scale=0.90909]{figs-python/arraydeque}


\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{add}(\ensure...
... \gets \ensuremath{\ensuremath{\mathit{n}} + 1}}\\
\end{flushleft}\end{leftbar}

By doing the shifting in this way, we guarantee that $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ never has to shift more than $ \min\{ \ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}, \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}} \}$ elements. Thus, the running time of the $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ operation (ignoring the cost of a $ \ensuremath{\mathrm{resize}()}$ operation) is $ O(1+\min\{\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}},\ensuremath{\ensur...
...{\ensuremath{\mathit{n}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}\})$.

The implementation of the $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$ operation is similar. It either shifts elements $ \ensuremath{\ensuremath{\ensuremath{\mathit{a}}[0]}},\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{i}}-1]}}$ right by one position or shifts the elements $ \ensuremath{\ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{i}}+1]}},\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{n}}-1]}}$ left by one position depending on whether $ \ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}<\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}/2$. Again, this means that $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$ never spends more than $ O(1+\min\{\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}},\ensuremath{\ensur...
...{\ensuremath{\mathit{n}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}\})$ time to shift elements.


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

2.4.1 Summary

The following theorem summarizes the performance of the ArrayDeque data structure:

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

opendatastructures.org

5 . 4 Discussion and Exercises

Assigned source reading · Pat Morin

Pat Morin — Open Data Structures, pseudocode edition 0.1G

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

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

5.4 Discussion and Exercises

Hash tables and hash codes represent an enormous and active field of research that is just touched upon in this chapter. The online Bibliography on Hashing [10] contains nearly 2000 entries.

A variety of different hash table implementations exist. The one described in Section 5.1 is known as hashing with chaining (each array entry contains a chain (List) of elements). Hashing with chaining dates back to an internal IBM memorandum authored by H. P. Luhn and dated January 1953. This memorandum also seems to be one of the earliest references to linked lists.

An alternative to hashing with chaining is that used by open addressing schemes, where all data is stored directly in an array. These schemes include the LinearHashTable structure of Section 5.2. This idea was also proposed, independently, by a group at IBM in the 1950s. Open addressing schemes must deal with the problem of collision resolution: the case where two values hash to the same array location. Different strategies exist for collision resolution; these provide different performance guarantees and often require more sophisticated hash functions than the ones described here.

Yet another category of hash table implementations are the so-called perfect hashing methods. These are methods in which $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$ operations take $ O(1)$ time in the worst-case. For static data sets, this can be accomplished by finding perfect hash functions for the data; these are functions that map each piece of data to a unique array location. For data that changes over time, perfect hashing methods include FKS two-level hash tables [31,24] and cuckoo hashing [55].

The hash functions presented in this chapter are probably among the most practical methods currently known that can be proven to work well for any set of data. Other provably good methods date back to the pioneering work of Carter and Wegman who introduced the notion of universal hashing and described several hash functions for different scenarios [14]. Tabulation hashing, described in Section 5.2.3, is due to Carter and Wegman [14], but its analysis, when applied to linear probing (and several other hash table schemes) is due to P{\v{a\/}}\kern.05emtra{\c{s\/}}cu and Thorup [58].

The idea of multiplicative hashing is very old and seems to be part of the hashing folklore [48, Section 6.4]. However, the idea of choosing the multiplier $ \ensuremath{\ensuremath{\mathit{z}}}$ to be a random odd number, and the analysis in Section 5.1.1 is due to Dietzfelbinger et al. [23]. This version of multiplicative hashing is one of the simplest, but its collision probability of $ 2/2^{\ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}}$ is a factor of two larger than what one could expect with a random function from $ 2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}\to
2^{\ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}}$. The multiply-add hashing method uses the function

$\displaystyle h(\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}) = ((\ensurem...
...ensuremath{\ensuremath{2w}}-\ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}}
$

where $ \ensuremath{\ensuremath{\mathit{z}}}$ and $ \ensuremath{\ensuremath{\mathit{b}}}$ are each randomly chosen from $ \{0,\ldots,2^{\ensuremath{\ensuremath{2w}}}-1\}$. Multiply-add hashing has a collision probability of only $ 1/2^{\ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}}$ [21], but requires $ 2\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}$-bit precision arithmetic.

There are a number of methods of obtaining hash codes from fixed-length sequences of $ \ensuremath{\ensuremath{\mathit{w}}}$-bit integers. One particularly fast method [11] is the function

\begin{displaymath}\begin{array}{l}
h(\ensuremath{\ensuremath{\ensuremath{\math...
...2\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}
\end{array}\end{displaymath}

where $ r$ is even and $ \ensuremath{\ensuremath{\ensuremath{\mathit{a}}}}_0,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{a}}}}_{r-1}$ are randomly chosen from $ \{0,\ldots,2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}\}$. This yields a $ 2\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}$-bit hash code that has collision probability $ 1/2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}$. This can be reduced to a $ \ensuremath{\ensuremath{\mathit{w}}}$-bit hash code using multiplicative (or multiply-add) hashing. This method is fast because it requires only $ r/2$ $ 2\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}$-bit multiplications whereas the method described in Section 5.3.2 requires $ r$ multiplications. (The $ \bmod$ operations occur implicitly by using $ \ensuremath{\ensuremath{\mathit{w}}}$ and $ 2\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}$-bit arithmetic for the additions and multiplications, respectively.)

The method from Section 5.3.3 of using polynomials over prime fields to hash variable-length arrays and strings is due to Dietzfelbinger et al. [22]. Due to its use of the $ \bmod$ operator which relies on a costly machine instruction, it is, unfortunately, not very fast. Some variants of this method choose the prime $ \ensuremath{\ensuremath{\mathit{p}}}$ to be one of the form $ 2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}-1$, in which case the $ \bmod$ operator can be replaced with addition ($ +$) and bitwise-and ($ \wedge $) operations [47, Section 3.6]. Another option is to apply one of the fast methods for fixed-length strings to blocks of length $ c$ for some constant $ c>1$ and then apply the prime field method to the resulting sequence of $ \lceil r/c\rceil$ hash codes.

Exercise 5..1   A certain university assigns each of its students student numbers the first time they register for any course. These numbers are sequential integers that started at 0 many years ago and are now in the millions. Suppose we have a class of one hundred first year students and we want to assign them hash codes based on their student numbers. Does it make more sense to use the first two digits or the last two digits of their student number? Justify your answer.

Exercise 5..2   Consider the hashing scheme in Section 5.1.1, and suppose $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}=2^{\ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}}$ and $ \ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}\le \ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}/2$.
  1. Show that, for any choice of the muliplier, $ \ensuremath{\ensuremath{\mathit{z}}}$, there exists $ \ensuremath{\ensuremath{\mathit{n}}}$ values that all have the same hash code. (Hint: This is easy, and doesn't require any number theory.)
  2. Given the multiplier, $ \ensuremath{\ensuremath{\mathit{z}}}$, describe $ \ensuremath{\ensuremath{\mathit{n}}}$ values that all have the same hash code. (Hint: This is harder, and requires some basic number theory.)

Exercise 5..3   Prove that the bound $ 2/2^{\ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}}$ in Lemma 5.1 is the best possible bound by showing that, if $ x=2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}-2}$ and $ \ensuremath{\ensuremath{\ensuremath{\mathit{y}}}}=3\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}$, then $ \Pr\{\ensuremath{\ensuremath{\mathrm{hash}(\ensuremath{\mathit{x}})}}=\ensurem...
...remath{\mathit{y}})}}\}=2/2^{\ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}}$. (Hint look at the binary representations of $ \ensuremath{\ensuremath{\ensuremath{\mathit{zx}}}}$ and $ \ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}3\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}$ and use the fact that $ \ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}3\ensuremath{\ensuremath{\ens...
...x\ensuremath{+\ensuremath{2}}z\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}$.)

Exercise 5..4   Reprove Lemma 5.4 using the full version of Stirling's Approximation given in Section 1.3.2.

Exercise 5..5   Consider the following simplified version of the code for adding an element $ \ensuremath{\ensuremath{\mathit{x}}}$ to a LinearHashTable, which simply stores $ \ensuremath{\ensuremath{\mathit{x}}}$ in the first $ \ensuremath{\ensuremath{\mathit{nil}}}$ array entry it finds. Explain why this could be very slow by giving an example of a sequence of $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$, $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$, and $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$ operations that would take on the order of $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}^2$ time to execute.
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{add\_slow}(\...
...return}} \ensuremath{\ensuremath{\mathit{true}}}\\
\end{flushleft}\end{leftbar}

Exercise 5..6   Early versions of the Java $ \ensuremath{\mathrm{hash\_code}()}$ method for the String class worked by not using all of the characters found in long strings. For example, for a sixteen character string, the hash code was computed using only the eight even-indexed characters. Explain why this was a very bad idea by giving an example of large set of strings that all have the same hash code.

Exercise 5..7   Suppose you have an object made up of two $ \ensuremath{\ensuremath{\mathit{w}}}$-bit integers, $ \ensuremath{\ensuremath{\mathit{x}}}$ and $ \ensuremath{\ensuremath{\mathit{y}}}$. Show why $ \ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}\oplus\ensuremath{\ensuremath{\ensuremath{\mathit{y}}}}$ does not make a good hash code for your object. Give an example of a large set of objects that would all have hash code 0.

Exercise 5..8   Suppose you have an object made up of two $ \ensuremath{\ensuremath{\mathit{w}}}$-bit integers, $ \ensuremath{\ensuremath{\mathit{x}}}$ and $ \ensuremath{\ensuremath{\mathit{y}}}$. Show why $ \ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}+\ensuremath{\ensuremath{\ensuremath{\mathit{y}}}}$ does not make a good hash code for your object. Give an example of a large set of objects that would all have the same hash code.

Exercise 5..9   Suppose you have an object made up of two $ \ensuremath{\ensuremath{\mathit{w}}}$-bit integers, $ \ensuremath{\ensuremath{\mathit{x}}}$ and $ \ensuremath{\ensuremath{\mathit{y}}}$. Suppose that the hash code for your object is defined by some deterministic function $ h(\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}},\ensuremath{\ensuremath{\ensuremath{\mathit{y}}}})$ that produces a single $ \ensuremath{\ensuremath{\mathit{w}}}$-bit integer. Prove that there exists a large set of objects that have the same hash code.

Exercise 5..10   Let $ p=2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}-1$ for some positive integer $ \ensuremath{\ensuremath{\mathit{w}}}$. Explain why, for a positive integer $ x$

$\displaystyle (x\bmod 2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}) + ...
... x \bmod (2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}-1) \enspace .
$

(This gives an algorithm for computing $ x \bmod (2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}-1)$ by repeatedly setting until $ \ensuremath{\ensuremath{\ensuremath{\mathit{x}}}} \le 2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}-1$.)

Exercise 5..11   Find some commonly used hash table implementation such as the ( or the HashTable or LinearHashTable implementations in this book, and design a program that stores integers in this data structure so that there are integers, $ \ensuremath{\ensuremath{\mathit{x}}}$, such that $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$ takes linear time. That is, find a set of $ \ensuremath{\ensuremath{\mathit{n}}}$ integers for which there are $ c\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$ elements that hash to the same table location.

Depending on how good the implementation is, you may be able to do this just by inspecting the code for the implementation, or you may have to write some code that does trial insertions and searches, timing how long it takes to add and find particular values. (This can be, and has been, used to launch denial of service attacks on web servers [17].)

opendatastructures.org

7 . 2 Treap: A Randomized Binary Search Tree

Assigned source reading · Pat Morin

Pat Morin — Open Data Structures, pseudocode edition 0.1G

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

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

Subsections


7.2 Treap: A Randomized Binary Search Tree

The problem with random binary search trees is, of course, that they are not dynamic. They don't support the $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ or $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ operations needed to implement the SSet interface. In this section we describe a data structure called a Treap that uses Lemma 7.1 to implement the SSet interface.7.2

A node in a Treap is like a node in a BinarySearchTree in that it has a data value, $ \ensuremath{\ensuremath{\mathit{x}}}$, but it also contains a unique numerical priority, $ \ensuremath{\ensuremath{\mathit{p}}}$, that is assigned at random: In addition to being a binary search tree, the nodes in a Treap also obey the heap property:

In other words, each node has a priority smaller than that of its two children. An example is shown in Figure 7.5.

Figure 7.5: An example of a Treap containing the integers $ 0,\ldots,9$. Each node, $ \ensuremath{\ensuremath{\mathit{u}}}$, is illustrated as a box containing $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{x}}}},\ensuremath{\ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{p}}}}$.
\includegraphics[width=\textwidth ]{figs-python/treap}

The heap and binary search tree conditions together ensure that, once the key ( $ \ensuremath{\ensuremath{\mathit{x}}}$) and priority ( $ \ensuremath{\ensuremath{\mathit{p}}}$) for each node are defined, the shape of the Treap is completely determined. The heap property tells us that the node with minimum priority has to be the root, $ \ensuremath{\ensuremath{\mathit{r}}}$, of the Treap. The binary search tree property tells us that all nodes with keys smaller than $ \ensuremath{\ensuremath{\mathit{r}}.\ensuremath{\mathit{x}}}$ are stored in the subtree rooted at $ \ensuremath{\ensuremath{\mathit{r}}.\ensuremath{\mathit{left}}}$ and all nodes with keys larger than $ \ensuremath{\ensuremath{\mathit{r}}.\ensuremath{\mathit{x}}}$ are stored in the subtree rooted at $ \ensuremath{\ensuremath{\mathit{r}}.\ensuremath{\mathit{right}}}$.

The important point about the priority values in a Treap is that they are unique and assigned at random. Because of this, there are two equivalent ways we can think about a Treap. As defined above, a Treap obeys the heap and binary search tree properties. Alternatively, we can think of a Treap as a BinarySearchTree whose nodes were added in increasing order of priority. For example, the Treap in Figure 7.5 can be obtained by adding the sequence of $ (\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}},\ensuremath{\ensuremath{\ensuremath{\mathit{p}}}})$ values

$\displaystyle \langle
(3,1), (1,6), (0,9), (5,11), (4,14), (9,17), (7,22), (6,42), (8,49), (2,99)
\rangle
$

into a BinarySearchTree.

Since the priorities are chosen randomly, this is equivalent to taking a random permutation of the keys--in this case the permutation is

$\displaystyle \langle 3, 1, 0, 5, 9, 4, 7, 6, 8, 2 \rangle
$

--and adding these to a BinarySearchTree. But this means that the shape of a treap is identical to that of a random binary search tree. In particular, if we replace each key $ \ensuremath{\ensuremath{\mathit{x}}}$ by its rank,7.3 then Lemma 7.1 applies. Restating Lemma 7.1 in terms of Treaps, we have:

Lemma 7..2   In a Treap that stores a set $ S$ of $ \ensuremath{\ensuremath{\mathit{n}}}$ keys, the following statements hold:
  1. For any $ \ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}\in S$, the expected length of the search path for $ \ensuremath{\ensuremath{\mathit{x}}}$ is $ H_{r(\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}})+1} + H_{\ensuremath{\e...
...math{\mathit{n}}}}-r(\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}})} - O(1)$.
  2. For any $ \ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}\not\in S$, the expected length of the search path for $ \ensuremath{\ensuremath{\mathit{x}}}$ is $ H_{r(\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}})} + H_{\ensuremath{\ens...
...\ensuremath{\mathit{n}}}}-r(\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}})}$.
Here, $ r(\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}})$ denotes the rank of $ \ensuremath{\ensuremath{\mathit{x}}}$ in the set $ S\cup\{\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}\}$.

Again, we emphasize that the expectation in Lemma 7.2 is taken over the random choices of the priorities for each node. It does not require any assumptions about the randomness in the keys.

Lemma 7.2 tells us that Treaps can implement the $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$ operation efficiently. However, the real benefit of a Treap is that it can support the $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{delete}(\ensuremath{\mathit{x}})}$ operations. To do this, it needs to perform rotations in order to maintain the heap property. Refer to Figure 7.6. A rotation in a binary search tree is a local modification that takes a parent $ \ensuremath{\ensuremath{\mathit{u}}}$ of a node $ \ensuremath{\ensuremath{\mathit{w}}}$ and makes $ \ensuremath{\ensuremath{\mathit{w}}}$ the parent of $ \ensuremath{\ensuremath{\mathit{u}}}$, while preserving the binary search tree property. Rotations come in two flavours: left or right depending on whether $ \ensuremath{\ensuremath{\mathit{w}}}$ is a right or left child of $ \ensuremath{\ensuremath{\mathit{u}}}$, respectively.

Figure 7.6: Left and right rotations in a binary search tree.
\includegraphics[width=\textwidth ]{figs-python/rotation}

The code that implements this has to handle these two possibilities and be careful of a boundary case (when $ \ensuremath{\ensuremath{\mathit{u}}}$ is the root), so the actual code is a little longer than Figure 7.6 would lead a reader to believe:
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{rotate\_left...
...{r}}.\ensuremath{parent} \gets \ensuremath{nil}}\\
\end{flushleft}\end{leftbar}
In terms of the Treap data structure, the most important property of a rotation is that the depth of $ \ensuremath{\ensuremath{\mathit{w}}}$ decreases by one while the depth of $ \ensuremath{\ensuremath{\mathit{u}}}$ increases by one.

Using rotations, we can implement the $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ operation as follows: We create a new node, $ \ensuremath{\ensuremath{\mathit{u}}}$, assign $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{x}\gets \ensuremath{x}}$, and pick a random value for $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{p}}}$. Next we add $ \ensuremath{\ensuremath{\mathit{u}}}$ using the usual $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ algorithm for a BinarySearchTree, so that $ \ensuremath{\ensuremath{\mathit{u}}}$ is now a leaf of the Treap. At this point, our Treap satisfies the binary search tree property, but not necessarily the heap property. In particular, it may be the case that $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{parent}}.\ensuremath{\mathit{p}} > \ensuremath{\mathit{u}}.\ensuremath{\mathit{p}}}$. If this is the case, then we perform a rotation at node $ \ensuremath{\ensuremath{\mathit{w}}}$= $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{parent}}}$ so that $ \ensuremath{\ensuremath{\mathit{u}}}$ becomes the parent of $ \ensuremath{\ensuremath{\mathit{w}}}$. If $ \ensuremath{\ensuremath{\mathit{u}}}$ continues to violate the heap property, we will have to repeat this, decreasing $ \ensuremath{\ensuremath{\mathit{u}}}$'s depth by one every time, until $ \ensuremath{\ensuremath{\mathit{u}}}$ either becomes the root or $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{parent}}.\...
...}}} < \ensuremath{\ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{p}}}}$.
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{add}(\ensure...
...th{\ensuremath{\mathit{r}} \gets \ensuremath{u}}\\
\end{flushleft}\end{leftbar}
An example of an $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ operation is shown in Figure 7.7.

Figure 7.7: Adding the value 1.5 into the Treap from Figure 7.5.
\includegraphics[width=\textwidth ]{figs-python/treap-insert-a}
\includegraphics[width=\textwidth ]{figs-python/treap-insert-b}
\includegraphics[width=\textwidth ]{figs-python/treap-insert-c}

The running time of the $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ operation is given by the time it takes to follow the search path for $ \ensuremath{\ensuremath{\mathit{x}}}$ plus the number of rotations performed to move the newly-added node, $ \ensuremath{\ensuremath{\mathit{u}}}$, up to its correct location in the Treap. By Lemma 7.2, the expected length of the search path is at most $ 2\ln \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}+O(1)$. Furthermore, each rotation decreases the depth of $ \ensuremath{\ensuremath{\mathit{u}}}$. This stops if $ \ensuremath{\ensuremath{\mathit{u}}}$ becomes the root, so the expected number of rotations cannot exceed the expected length of the search path. Therefore, the expected running time of the $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ operation in a Treap is $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$. (Exercise 7.5 asks you to show that the expected number of rotations performed during an addition is actually only $ O(1)$.)

The $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ operation in a Treap is the opposite of the $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ operation. We search for the node, $ \ensuremath{\ensuremath{\mathit{u}}}$, containing $ \ensuremath{\ensuremath{\mathit{x}}}$, then perform rotations to move $ \ensuremath{\ensuremath{\mathit{u}}}$ downwards until it becomes a leaf, and then we splice $ \ensuremath{\ensuremath{\mathit{u}}}$ from the Treap. Notice that, to move $ \ensuremath{\ensuremath{\mathit{u}}}$ downwards, we can perform either a left or right rotation at $ \ensuremath{\ensuremath{\mathit{u}}}$, which will replace $ \ensuremath{\ensuremath{\mathit{u}}}$ with $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{right}}}$ or $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{left}}}$, respectively. The choice is made by the first of the following that apply:

  1. If $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{left}}}$ and $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{right}}}$ are both $ \ensuremath{\ensuremath{\mathit{nil}}}$, then $ \ensuremath{\ensuremath{\mathit{u}}}$ is a leaf and no rotation is performed.
  2. If $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{left}}}$ (or $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{right}}}$) is $ \ensuremath{\ensuremath{\mathit{nil}}}$, then perform a right (or left, respectively) rotation at $ \ensuremath{\ensuremath{\mathit{u}}}$.
  3. If $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{left}}.\en...
...h{\ensuremath{\mathit{u}}.\ensuremath{\mathit{right}}.\ensuremath{\mathit{p}}}}$ (or $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{left}}.\en...
...{\ensuremath{\mathit{u}}.\ensuremath{\mathit{right}}.\ensuremath{\mathit{p}}}})$, then perform a right rotation (or left rotation, respectively) at $ \ensuremath{\ensuremath{\mathit{u}}}$.
These three rules ensure that the Treap doesn't become disconnected and that the heap property is restored once $ \ensuremath{\ensuremath{\mathit{u}}}$ is removed.
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{remove}(\ens...
...ets \ensuremath{\ensuremath{\mathit{u}}.parent}}\\
\end{flushleft}\end{leftbar}
An example of the $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ operation is shown in Figure 7.8.
Figure 7.8: Removing the value 9 from the Treap in Figure 7.5.
\includegraphics[height=.25\textheight ]{figs-python/treap-delete-a}
\includegraphics[height=.25\textheight ]{figs-python/treap-delete-b}
\includegraphics[height=.25\textheight ]{figs-python/treap-delete-c}
\includegraphics[height=.25\textheight ]{figs-python/treap-delete-d}

The trick to analyze the running time of the $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ operation is to notice that this operation reverses the $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ operation. In particular, if we were to reinsert $ \ensuremath{\ensuremath{\mathit{x}}}$, using the same priority $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{p}}}$, then the $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ operation would do exactly the same number of rotations and would restore the Treap to exactly the same state it was in before the $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ operation took place. (Reading from bottom-to-top, Figure 7.8 illustrates the addition of the value 9 into a Treap.) This means that the expected running time of the $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ on a Treap of size $ \ensuremath{\ensuremath{\mathit{n}}}$ is proportional to the expected running time of the $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ operation on a Treap of size $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-1$. We conclude that the expected running time of $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ is $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$.

7.2.1 Summary

The following theorem summarizes the performance of the Treap data structure:

Theorem 7..2   A Treap implements the SSet interface. A Treap supports the operations $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$, $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$, and $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$ in $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ expected time per operation.

It is worth comparing the Treap data structure to the SkiplistSSet data structure. Both implement the SSet operations in $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ expected time per operation. In both data structures, $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ involve a search and then a constant number of pointer changes (see Exercise 7.5 below). Thus, for both these structures, the expected length of the search path is the critical value in assessing their performance. In a SkiplistSSet, the expected length of a search path is

$\displaystyle 2\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}} + O(1) \enspace ,
$

In a Treap, the expected length of a search path is

$\displaystyle 2\ln \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}} +O(1) \approx 1.386\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}} + O(1) \enspace .
$

Thus, the search paths in a Treap are considerably shorter and this translates into noticeably faster operations on Treaps than Skiplists. Exercise 4.7 in Chapter 4 shows how the expected length of the search path in a Skiplist can be reduced to

$\displaystyle e\ln \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}} + O(1) \approx 1.884\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}} + O(1)
$

by using biased coin tosses. Even with this optimization, the expected length of search paths in a SkiplistSSet is noticeably longer than in a Treap.



Footnotes

... interface.7.2
The names Treap comes from the fact that this data structure is simultaneously a binary search tree (Section 6.2) and a heap (Chapter 10).
... rank,7.3
The rank of an element $ \ensuremath{\ensuremath{\mathit{x}}}$ in a set $ S$ of elements is the number of elements in $ S$ that are less than $ \ensuremath{\ensuremath{\mathit{x}}}$.
opendatastructures.org

13 . 2 XFastTrie: Searching in Doubly-Logarithmic Time

Assigned source reading · Pat Morin

Pat Morin — Open Data Structures, pseudocode edition 0.1G

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

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


13.2 XFastTrie: Searching in Doubly-Logarithmic Time

The performance of the BinaryTrie structure is not very impressive. The number of elements, $ \ensuremath{\ensuremath{\mathit{n}}}$, stored in the structure is at most $ 2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}$, so $ \log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}\le \ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}$. In other words, any of the comparison-based SSet structures described in other parts of this book are at least as efficient as a BinaryTrie, and are not restricted to only storing integers.

Next we describe the XFastTrie, which is just a BinaryTrie with $ \ensuremath{\ensuremath{\mathit{w}}+1}$ hash tables--one for each level of the trie. These hash tables are used to speed up the $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$ operation to $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{w}}}})$ time. Recall that the $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$ operation in a BinaryTrie is almost complete once we reach a node, $ \ensuremath{\ensuremath{\mathit{u}}}$, where the search path for $ \ensuremath{\ensuremath{\mathit{x}}}$ would like to proceed to $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{right}}}$ (or $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{left}}}$) but $ \ensuremath{\ensuremath{\mathit{u}}}$ has no right (respectively, left) child. At this point, the search uses $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{jump}}}$ to jump to a leaf, $ \ensuremath{\ensuremath{\mathit{v}}}$, of the BinaryTrie and either return $ \ensuremath{\ensuremath{\mathit{v}}}$ or its successor in the linked list of leaves. An XFastTrie speeds up the search process by using binary search on the levels of the trie to locate the node $ \ensuremath{\ensuremath{\mathit{u}}}$.

To use binary search, we need a way to determine if the node $ \ensuremath{\ensuremath{\mathit{u}}}$ we are looking for is above a particular level, $ \ensuremath{\ensuremath{\mathit{i}}}$, of if $ \ensuremath{\ensuremath{\mathit{u}}}$ is at or below level $ \ensuremath{\ensuremath{\mathit{i}}}$. This information is given by the highest-order $ \ensuremath{\ensuremath{\mathit{i}}}$ bits in the binary representation of $ \ensuremath{\ensuremath{\mathit{x}}}$; these bits determine the search path that $ \ensuremath{\ensuremath{\mathit{x}}}$ takes from the root to level $ \ensuremath{\ensuremath{\mathit{i}}}$. For an example, refer to Figure 13.6; in this figure the last node, $ \ensuremath{\ensuremath{\mathit{u}}}$, on search path for 14 (whose binary representation is 1110) is the node labelled $ 11{\star\star}$ at level 2 because there is no node labelled $ 111{\star}$ at level 3. Thus, we can label each node at level $ \ensuremath{\ensuremath{\mathit{i}}}$ with an $ \ensuremath{\ensuremath{\mathit{i}}}$-bit integer. Then, the node $ \ensuremath{\ensuremath{\mathit{u}}}$ we are searching for would be at or below level $ \ensuremath{\ensuremath{\mathit{i}}}$ if and only if there is a node at level $ \ensuremath{\ensuremath{\mathit{i}}}$ whose label matches the highest-order $ \ensuremath{\ensuremath{\mathit{i}}}$ bits of $ \ensuremath{\ensuremath{\mathit{x}}}$.

Figure 13.6: Since there is no node labelled $ 111\star$, the search path for 14 (1110) ends at the node labelled $ 11{\star\star}$ .
\includegraphics[scale=0.90909]{figs-python/xfast-path}

In an XFastTrie, we store, for each $ \ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}\in\{0,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}\}$, all the nodes at level $ \ensuremath{\ensuremath{\mathit{i}}}$ in a USet, $ \ensuremath{\ensuremath{\mathit{t}}[\ensuremath{\mathit{i}}]}$, that is implemented as a hash table (Chapter 5). Using this USet allows us to check in constant expected time if there is a node at level $ \ensuremath{\ensuremath{\mathit{i}}}$ whose label matches the highest-order $ \ensuremath{\ensuremath{\mathit{i}}}$ bits of $ \ensuremath{\ensuremath{\mathit{x}}}$. In fact, we can even find this node using $ \ensuremath{\ensuremath{\mathit{t}}[\ensuremath{\mathit{i}}].\mathrm{find}(\en...
...{\mathit{x}}\ensuremath{\gg}(\ensuremath{\mathit{w}}-\ensuremath{\mathit{i}})})$

The hash tables $ \ensuremath{\ensuremath{\ensuremath{\mathit{t}}[0]}},\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{t}}[\ensuremath{\mathit{w}}]}}$ allow us to use binary search to find $ \ensuremath{\ensuremath{\mathit{u}}}$. Initially, we know that $ \ensuremath{\ensuremath{\mathit{u}}}$ is at some level $ \ensuremath{\ensuremath{\mathit{i}}}$ with $ 0\le \ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}< \ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}+1$. We therefore initialize $ \ensuremath{\ensuremath{\ensuremath{\mathit{\ell}}}}=0$ and $ \ensuremath{\ensuremath{\ensuremath{\mathit{h}}}}=\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}+1$ and repeatedly look at the hash table $ \ensuremath{\ensuremath{\mathit{t}}[\ensuremath{\mathit{i}}]}$, where $ \ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}=\lfloor
(\ensuremath{\ensuremath{\ensuremath{\mathit{\ell}}+\ensuremath{\mathit{h}}}})/2\rfloor$. If $ \ensuremath{\ensuremath{\ensuremath{\mathit{t}}[\ensuremath{\mathit{i}}]}}$ contains a node whose label matches $ \ensuremath{\ensuremath{\mathit{x}}}$'s highest-order $ \ensuremath{\ensuremath{\mathit{i}}}$ bits then we set $ \ensuremath{\ensuremath{\mathit{\ell}}\gets \ensuremath{i}}$ ( $ \ensuremath{\ensuremath{\mathit{u}}}$ is at or below level $ \ensuremath{\ensuremath{\mathit{i}}}$); otherwise we set $ \ensuremath{\ensuremath{\mathit{h}}\gets \ensuremath{i}}$ ( $ \ensuremath{\ensuremath{\mathit{u}}}$ is above level $ \ensuremath{\ensuremath{\mathit{i}}}$). This process terminates when $ \ensuremath{\ensuremath{\ensuremath{\mathit{h}}-\ensuremath{\mathit{\ell}}}}\le 1$, in which case we determine that $ \ensuremath{\ensuremath{\mathit{u}}}$ is at level $ \ensuremath{\ensuremath{\mathit{\ell}}}$. We then complete the $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$ operation using $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{jump}}}$ and the doubly-linked list of leaves.
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{find}(\ensur...
...suremath{\mathit{next}}.\ensuremath{\mathit{x}}}\\
\end{flushleft}\end{leftbar}
Each iteration of the $ {\color{black} \textbf{while}}$ loop in the above method decreases $ \ensuremath{\ensuremath{\mathit{h}}-\ensuremath{\mathit{\ell}}}$ by roughly a factor of two, so this loop finds $ \ensuremath{\ensuremath{\mathit{u}}}$ after $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{w}}}})$ iterations. Each iteration performs a constant amount of work and one $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$ operation in a USet, which takes a constant expected amount of time. The remaining work takes only constant time, so the $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$ method in an XFastTrie takes only $ O(\log\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}})$ expected time.

The $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ methods for an XFastTrie are almost identical to the same methods in a BinaryTrie. The only modifications are for managing the hash tables $ \ensuremath{\ensuremath{\mathit{t}}[0]}$,..., $ \ensuremath{\ensuremath{\mathit{t}}[\ensuremath{\mathit{w}}]}$. During the $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ operation, when a new node is created at level $ \ensuremath{\ensuremath{\mathit{i}}}$, this node is added to $ \ensuremath{\ensuremath{\mathit{t}}[\ensuremath{\mathit{i}}]}$. During a $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ operation, when a node is removed form level $ \ensuremath{\ensuremath{\mathit{i}}}$, this node is removed from $ \ensuremath{\ensuremath{\mathit{t}}[\ensuremath{\mathit{i}}]}$. Since adding and removing from a hash table take constant expected time, this does not increase the running times of $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ by more than a constant factor. We omit a code listing for $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ since the code is almost identical to the (long) code listing already provided for the same methods in a BinaryTrie.

The following theorem summarizes the performance of an XFastTrie:

Theorem 13..2   An XFastTrie implements the SSet interface for $ \ensuremath{\ensuremath{\mathit{w}}}$-bit integers. An XFastTrie supports the operations
  • $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ in $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}})$ expected time per operation and
  • $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$ in $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{w}}}})$ expected time per operation.
The space used by an XFastTrie that stores $ \ensuremath{\ensuremath{\mathit{n}}}$ values is $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}\cdot\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}})$.

opendatastructures.org

Indexed collections

Assigned source reading · Mozilla Contributors

MDN Web Docs — Mozilla Contributors

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

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

Indexed collections

This chapter introduces collections of data which are ordered by an index value. This includes arrays and array-like constructs such as Array objects and TypedArray objects.

An array is an ordered list of values that you refer to with a name and an index.

For example, consider an array called emp, which contains employees' names indexed by their numerical employee number. So emp[0] would be employee number zero, emp[1] employee number one, and so on.

JavaScript does not have an explicit array data type. However, you can use the predefined Array object and its methods to work with arrays in your applications. The Array object has methods for manipulating arrays in various ways, such as joining, reversing, and sorting them. It has a property for determining the array length and other properties for use with regular expressions.

We will be focusing on arrays in this article, but many of the same concepts apply to typed arrays as well, since arrays and typed arrays share many similar methods. For more information on typed arrays, see the typed array guide.

Creating an array

The following statements create equivalent arrays:

js
const arr1 = new Array(element0, element1, /* …, */ elementN);
const arr2 = Array(element0, element1, /* …, */ elementN);
const arr3 = [element0, element1, /* …, */ elementN];

element0, element1, …, elementN is a list of values for the array's elements. When these values are specified, the array is initialized with them as the array's elements. The array's length property is set to the number of arguments.

The bracket syntax is called an "array literal" or "array initializer." It's shorter than other forms of array creation, and so is generally preferred. See Array literals for details.

To create an array with non-zero length, but without any items, either of the following can be used:

js
// This...
const arr1 = new Array(arrayLength);

// … results in the same array as this
const arr2 = Array(arrayLength);

// This has exactly the same effect
const arr3 = [];
arr3.length = arrayLength;

Note: In the above code, arrayLength must be a Number. Otherwise, an array with a single element (the provided value) will be created. Calling arr.length will return arrayLength, but the array doesn't contain any elements. A for...in loop will not find any property on the array.

In addition to a newly defined variable as shown above, arrays can also be assigned as a property of a new or an existing object:

js
const obj = {};
// …
obj.prop = [element0, element1, /* …, */ elementN];

// OR
const obj = { prop: [element0, element1, /* …, */ elementN] };

If you wish to initialize an array with a single element, and the element happens to be a Number, you must use the bracket syntax. When a single Number value is passed to the Array() constructor or function, it is interpreted as an arrayLength, not as a single element.

This creates an array with only one element: the number 42.

js
const arr = [42];

This creates an array with no elements and arr.length set to 42.

js
const arr = Array(42);

This is equivalent to:

js
const arr = [];
arr.length = 42;

Calling Array(N) results in a RangeError, if N is a non-whole number whose fractional portion is non-zero. The following example illustrates this behavior.

js
const arr = Array(9.3); // RangeError: Invalid array length

If your code needs to create arrays with single elements of an arbitrary data type, it is safer to use array literals. Alternatively, create an empty array first before adding the single element to it.

You can also use the Array.of static method to create arrays with single element.

js
const arr = Array.of(9.3); // arr contains only one element 9.3

Referring to array elements

Because elements are also properties, you can access them using property accessors. Suppose you define the following array:

js
const myArray = ["Wind", "Rain", "Fire"];

You can refer to the first element of the array as myArray[0], the second element of the array as myArray[1], etc. The index of the elements begins with zero.

Note: You can also use property accessors to access other properties of the array, like with an object.

js
const arr = ["one", "two", "three"];
arr[2]; // three
arr["length"]; // 3

Populating an array

You can populate an array by assigning values to its elements. For example:

js
const emp = [];
emp[0] = "Casey Jones";
emp[1] = "Phil Lesh";
emp[2] = "August West";

Note: If you supply a non-integer value to the array operator in the code above, a property will be created in the object representing the array, instead of an array element.

js
const arr = [];
arr[3.4] = "Oranges";
console.log(arr.length); // 0
console.log(Object.hasOwn(arr, 3.4)); // true

You can also populate an array when you create it:

js
const myArray = new Array("Hello", myVar, 3.14159);
// OR
const myArray = ["Mango", "Apple", "Orange"];

Understanding length

At the implementation level, JavaScript's arrays actually store their elements as standard object properties, using the array index as the property name.

The length property is special. Its value is always a positive integer greater than the index of the last element if one exists. (In the example below, 'Dusty' is indexed at 30, so cats.length returns 30 + 1).

Remember, JavaScript Array indexes are 0-based: they start at 0, not 1. This means that the length property will be one more than the highest index stored in the array:

js
const cats = [];
cats[30] = ["Dusty"];
console.log(cats.length); // 31

You can also assign to the length property.

Writing a value that is shorter than the number of stored items truncates the array. Writing 0 empties it entirely:

js
const cats = ["Dusty", "Misty", "Twiggy"];
console.log(cats.length); // 3

cats.length = 2;
console.log(cats); // [ 'Dusty', 'Misty' ] - Twiggy has been removed

cats.length = 0;
console.log(cats); // []; the cats array is empty

cats.length = 3;
console.log(cats); // [ <3 empty items> ]

Iterating over arrays

A common operation is to iterate over the values of an array, processing each one in some way, as follows:

js
const colors = ["red", "green", "blue"];
for (let i = 0; i < colors.length; i++) {
  console.log(colors[i]);
}

If you know that none of the elements in your array evaluate to false in a boolean context—if your array consists only of DOM nodes, for example—you can use a more efficient idiom:

js
const divs = document.getElementsByTagName("div");
for (let i = 0, div; (div = divs[i]); i++) {
  /* Process div in some way */
}

This avoids the overhead of checking the length of the array, and ensures that the div variable is reassigned to the current item each time around the loop for added convenience.

The forEach() method provides another way of iterating over an array:

js
const colors = ["red", "green", "blue"];
colors.forEach((color) => console.log(color));
// red
// green
// blue

The function passed to forEach is executed once for every item in the array, with the array item passed as the argument to the function. Unassigned values are not iterated in a forEach loop.

Note that the elements of an array that are omitted when the array is defined are not listed when iterating by forEach, but are listed when undefined has been manually assigned to the element:

js
const sparseArray = ["first", "second", , "fourth"];

sparseArray.forEach((element) => {
  console.log(element);
});
// Logs:
// first
// second
// fourth

if (sparseArray[2] === undefined) {
  console.log("sparseArray[2] is undefined"); // true
}

const nonsparseArray = ["first", "second", undefined, "fourth"];

nonsparseArray.forEach((element) => {
  console.log(element);
});
// Logs:
// first
// second
// undefined
// fourth

Since JavaScript array elements are saved as standard object properties, it is not advisable to iterate through JavaScript arrays using for...in loops, because normal elements and all enumerable properties will be listed.

Array methods

The Array object has the following methods:

The concat() method joins two or more arrays and returns a new array.

js
let myArray = ["1", "2", "3"];
myArray = myArray.concat("a", "b", "c");
// myArray is now ["1", "2", "3", "a", "b", "c"]

The join() method joins all elements of an array into a string.

js
const myArray = ["Wind", "Rain", "Fire"];
const list = myArray.join(" - "); // list is "Wind - Rain - Fire"

The push() method adds one or more elements to the end of an array and returns the resulting length of the array.

js
const myArray = ["1", "2"];
myArray.push("3"); // myArray is now ["1", "2", "3"]

The pop() method removes the last element from an array and returns that element.

js
const myArray = ["1", "2", "3"];
const last = myArray.pop();
// myArray is now ["1", "2"], last = "3"

The shift() method removes the first element from an array and returns that element.

js
const myArray = ["1", "2", "3"];
const first = myArray.shift();
// myArray is now ["2", "3"], first is "1"

The unshift() method adds one or more elements to the front of an array and returns the new length of the array.

js
const myArray = ["1", "2", "3"];
myArray.unshift("4", "5");
// myArray becomes ["4", "5", "1", "2", "3"]

The slice() method extracts a section of an array and returns a new array.

js
let myArray = ["a", "b", "c", "d", "e"];
myArray = myArray.slice(1, 4); // [ "b", "c", "d"]
// starts at index 1 and extracts all elements
// until index 3

The at() method returns the element at the specified index in the array, or undefined if the index is out of range. It's notably used for negative indices that access elements from the end of the array.

js
const myArray = ["a", "b", "c", "d", "e"];
myArray.at(-2); // "d", the second-last element of myArray

The splice() method removes elements from an array and (optionally) replaces them. It returns the items which were removed from the array.

js
const myArray = ["1", "2", "3", "4", "5"];
myArray.splice(1, 3, "a", "b", "c", "d");
// myArray is now ["1", "a", "b", "c", "d", "5"]
// This code started at index one (or where the "2" was),
// removed 3 elements there, and then inserted all consecutive
// elements in its place.

The reverse() method transposes the elements of an array, in place: the first array element becomes the last and the last becomes the first. It returns a reference to the array.

js
const myArray = ["1", "2", "3"];
myArray.reverse();
// transposes the array so that myArray = ["3", "2", "1"]

The flat() method returns a new array with all sub-array elements concatenated into it recursively up to the specified depth.

js
let myArray = [1, 2, [3, 4]];
myArray = myArray.flat();
// myArray is now [1, 2, 3, 4], since the [3, 4] subarray is flattened

The sort() method sorts the elements of an array in place, and returns a reference to the array.

js
const myArray = ["Wind", "Rain", "Fire"];
myArray.sort();
// sorts the array so that myArray = ["Fire", "Rain", "Wind"]

sort() can also take a callback function to determine how array elements are compared. The callback function is called with two arguments, which are two values from the array. The function compares these two values and returns a positive number, negative number, or zero, indicating the order of the two values. For instance, the following will sort the array by the last letter of a string:

js
const sortFn = (a, b) => {
  if (a[a.length - 1] < b[b.length - 1]) {
    return -1; // Negative number => a < b, a comes before b
  } else if (a[a.length - 1] > b[b.length - 1]) {
    return 1; // Positive number => a > b, a comes after b
  }
  return 0; // Zero => a = b, a and b keep their original order
};
myArray.sort(sortFn);
// sorts the array so that myArray = ["Wind","Fire","Rain"]
  • if a is less than b by the sorting system, return -1 (or any negative number)
  • if a is greater than b by the sorting system, return 1 (or any positive number)
  • if a and b are considered equivalent, return 0.

The indexOf() method searches the array for searchElement and returns the index of the first match.

js
const a = ["a", "b", "a", "b", "a"];
console.log(a.indexOf("b")); // 1

// Now try again, starting from after the last match
console.log(a.indexOf("b", 2)); // 3
console.log(a.indexOf("z")); // -1, because 'z' was not found

The lastIndexOf() method works like indexOf, but starts at the end and searches backwards.

js
const a = ["a", "b", "c", "d", "a", "b"];
console.log(a.lastIndexOf("b")); // 5

// Now try again, starting from before the last match
console.log(a.lastIndexOf("b", 4)); // 1
console.log(a.lastIndexOf("z")); // -1

The forEach() method executes callback on every array item and returns undefined.

js
const a = ["a", "b", "c"];
a.forEach((element) => {
  console.log(element);
});
// Logs:
// a
// b
// c

The forEach method (and others below) that take a callback are known as iterative methods, because they iterate over the entire array in some fashion. Each one takes an optional second argument called thisArg. If provided, thisArg becomes the value of the this keyword inside the body of the callback function. If not provided, as with other cases where a function is invoked outside of an explicit object context, this will refer to the global object (window, globalThis, etc.) when the function is not strict, or undefined when the function is strict.

Note: The sort() method introduced above is not an iterative method, because its callback function is only used for comparison and may not be called in any particular order based on element order. sort() does not accept the thisArg parameter either.

The map() method returns a new array of the return value from executing callback on every array item.

js
const a1 = ["a", "b", "c"];
const a2 = a1.map((item) => item.toUpperCase());
console.log(a2); // ['A', 'B', 'C']

The flatMap() method runs map() followed by a flat() of depth 1.

js
const a1 = ["a", "b", "c"];
const a2 = a1.flatMap((item) => [item.toUpperCase(), item.toLowerCase()]);
console.log(a2); // ['A', 'a', 'B', 'b', 'C', 'c']

The filter() method returns a new array containing the items for which callback returned true.

js
const a1 = ["a", 10, "b", 20, "c", 30];
const a2 = a1.filter((item) => typeof item === "number");
console.log(a2); // [10, 20, 30]

The find() method returns the first item for which callback returned true.

js
const a1 = ["a", 10, "b", 20, "c", 30];
const i = a1.find((item) => typeof item === "number");
console.log(i); // 10

The findLast() method returns the last item for which callback returned true.

js
const a1 = ["a", 10, "b", 20, "c", 30];
const i = a1.findLast((item) => typeof item === "number");
console.log(i); // 30

The findIndex() method returns the index of the first item for which callback returned true.

js
const a1 = ["a", 10, "b", 20, "c", 30];
const i = a1.findIndex((item) => typeof item === "number");
console.log(i); // 1

The findLastIndex() method returns the index of the last item for which callback returned true.

js
const a1 = ["a", 10, "b", 20, "c", 30];
const i = a1.findLastIndex((item) => typeof item === "number");
console.log(i); // 5

The every() method returns true if callback returns true for every item in the array.

js
function isNumber(value) {
  return typeof value === "number";
}
const a1 = [1, 2, 3];
console.log(a1.every(isNumber)); // true
const a2 = [1, "2", 3];
console.log(a2.every(isNumber)); // false

The some() method returns true if callback returns true for at least one item in the array.

js
function isNumber(value) {
  return typeof value === "number";
}
const a1 = [1, 2, 3];
console.log(a1.some(isNumber)); // true
const a2 = [1, "2", 3];
console.log(a2.some(isNumber)); // true
const a3 = ["1", "2", "3"];
console.log(a3.some(isNumber)); // false

The reduce() method applies callback(accumulator, currentValue, currentIndex, array) for each value in the array for the purpose of reducing the list of items down to a single value. The reduce function returns the final value returned by callback function.

If initialValue is specified, then callback is called with initialValue as the first parameter value and the value of the first item in the array as the second parameter value.

If initialValue is not specified, then callback's first two parameter values will be the first and second elements of the array. On every subsequent call, the first parameter's value will be whatever callback returned on the previous call, and the second parameter's value will be the next value in the array.

If callback needs access to the index of the item being processed, or access to the entire array, they are available as optional parameters.

js
const a = [10, 20, 30];
const total = a.reduce(
  (accumulator, currentValue) => accumulator + currentValue,
  0,
);
console.log(total); // 60

The reduceRight() method works like reduce(), but starts with the last element.

reduce and reduceRight are the least obvious of the iterative array methods. They should be used for algorithms that combine two values recursively in order to reduce a sequence down to a single value.

Array transformations

You can transform back and forth between arrays and other data structures.

Grouping the elements of an array

The Object.groupBy() method can be used to group the elements of an array, using a test function that returns a string indicating the group of the current element.

Here we have an inventory array that contains "food" objects that have a name and a type.

js
const inventory = [
  { name: "asparagus", type: "vegetables" },
  { name: "bananas", type: "fruit" },
  { name: "goat", type: "meat" },
  { name: "cherries", type: "fruit" },
  { name: "fish", type: "meat" },
];

To use Object.groupBy(), you supply a callback function that is called with the current element, and optionally the current index and array, and returns a string indicating the group of the element.

The code below uses an arrow function to return the type of each array element (this uses object destructuring syntax for function arguments to unpack the type element from the passed object). The result is an object that has properties named after the unique strings returned by the callback. Each property is assigned an array containing the elements in the group.

js
const result = Object.groupBy(inventory, ({ type }) => type);
console.log(result);
// Logs
// {
//   vegetables: [{ name: 'asparagus', type: 'vegetables' }],
//   fruit: [
//     { name: 'bananas', type: 'fruit' },
//     { name: 'cherries', type: 'fruit' }
//   ],
//   meat: [
//     { name: 'goat', type: 'meat' },
//     { name: 'fish', type: 'meat' }
//   ]
// }

Note that the returned object references the same elements as the original array (not deep copies). Changing the internal structure of these elements will be reflected in both the original array and the returned object.

If you can't use a string as the key, for example, if the information to group is associated with an object that might change, then you can instead use Map.groupBy(). This is very similar to Object.groupBy() except that it groups the elements of the array into a Map that can use an arbitrary value (object or primitive) as a key.

Sparse arrays

Arrays can contain "empty slots", which are not the same as slots filled with the value undefined. Empty slots can be created in one of the following ways:

js
// Array constructor:
const a = Array(5); // [ <5 empty items> ]

// Consecutive commas in array literal:
const b = [1, 2, , , 5]; // [ 1, 2, <2 empty items>, 5 ]

// Directly setting a slot with index greater than array.length:
const c = [1, 2];
c[4] = 5; // [ 1, 2, <2 empty items>, 5 ]

// Elongating an array by directly setting .length:
const d = [1, 2];
d.length = 5; // [ 1, 2, <3 empty items> ]

// Deleting an element:
const e = [1, 2, 3, 4, 5];
delete e[2]; // [ 1, 2, <1 empty item>, 4, 5 ]

In some operations, empty slots behave as if they are filled with undefined.

js
const arr = [1, 2, , , 5]; // Create a sparse array

// Indexed access
console.log(arr[2]); // undefined

// For...of
for (const i of arr) {
  console.log(i);
}
// Logs: 1 2 undefined undefined 5

// Spreading
const another = [...arr]; // "another" is [ 1, 2, undefined, undefined, 5 ]

But in others (most notably array iteration methods), empty slots are skipped.

js
const mapped = arr.map((i) => i + 1); // [ 2, 3, <2 empty items>, 6 ]
arr.forEach((i) => console.log(i)); // 1 2 5
const filtered = arr.filter(() => true); // [ 1, 2, 5 ]
const hasFalsy = arr.some((k) => !k); // false

// Property enumeration
const keys = Object.keys(arr); // [ '0', '1', '4' ]
for (const key in arr) {
  console.log(key);
}
// Logs: '0' '1' '4'
// Spreading into an object uses property enumeration, not the array's iterator
const objectSpread = { ...arr }; // { '0': 1, '1': 2, '4': 5 }

For a complete list of how array methods behave with sparse arrays, see the Array reference page.

Multi-dimensional arrays

Arrays can be nested, meaning that an array can contain another array as an element. Using this characteristic of JavaScript arrays, multi-dimensional arrays can be created.

The following code creates a two-dimensional array.

js
const a = new Array(4);
for (let i = 0; i < 4; i++) {
  a[i] = new Array(4);
  for (let j = 0; j < 4; j++) {
    a[i][j] = `[${i}, ${j}]`;
  }
}

This example creates an array with the following rows:

Row 0: [0, 0] [0, 1] [0, 2] [0, 3]
Row 1: [1, 0] [1, 1] [1, 2] [1, 3]
Row 2: [2, 0] [2, 1] [2, 2] [2, 3]
Row 3: [3, 0] [3, 1] [3, 2] [3, 3]

Using arrays to store other properties

Arrays can also be used like objects, to store related information.

js
const arr = [1, 2, 3];
arr.property = "value";
console.log(arr.property); // "value"

For example, when an array is the result of a match between a regular expression and a string, the array returns properties and elements that provide information about the match. An array is the return value of RegExp.prototype.exec(), String.prototype.match(), and String.prototype.split(). For information on using arrays with regular expressions, see Regular Expressions.

Working with array-like objects

Some JavaScript objects, such as the NodeList returned by document.getElementsByTagName() or the arguments object made available within the body of a function, look and behave like arrays on the surface but do not share all of their methods. The arguments object provides a length attribute but does not implement array methods like forEach().

Array methods cannot be called directly on array-like objects.

js
function printArguments() {
  arguments.forEach((item) => {
    console.log(item);
  }); // TypeError: arguments.forEach is not a function
}

But you can call them indirectly using Function.prototype.call().

js
function printArguments() {
  Array.prototype.forEach.call(arguments, (item) => {
    console.log(item);
  });
}

Array prototype methods can be used on strings as well, since they provide sequential access to their characters in a similar way to arrays:

js
Array.prototype.forEach.call("a string", (chr) => {
  console.log(chr);
});

2.3. Creating a New Table #

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

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

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

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

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

2.3. Creating a New Table #

You can create a new table by specifying the table name, along with all column names and their types:

CREATE TABLE weather (
    city            varchar(80),
    temp_lo         int,           -- low temperature
    temp_hi         int,           -- high temperature
    prcp            real,          -- precipitation
    date            date
);

You can enter this into psql with the line breaks. psql will recognize that the command is not terminated until the semicolon.

White space (i.e., spaces, tabs, and newlines) can be used freely in SQL commands. That means you can type the command aligned differently than above, or even all on one line. Two dashes (“--”) introduce comments. Whatever follows them is ignored up to the end of the line. SQL is case-insensitive about key words and identifiers, except when identifiers are double-quoted to preserve the case (not done above).

varchar(80) specifies a data type that can store arbitrary character strings up to 80 characters in length. int is the normal integer type. real is a type for storing single precision floating-point numbers. date should be self-explanatory. (Yes, the column of type date is also named date. This might be convenient or confusing — you choose.)

PostgreSQL supports the standard SQL types int, smallint, real, double precision, char(N), varchar(N), date, time, timestamp, and interval, as well as other types of general utility and a rich set of geometric types. PostgreSQL can be customized with an arbitrary number of user-defined data types. Consequently, type names are not key words in the syntax, except where required to support special cases in the SQL standard.

The second example will store cities and their associated geographical location:

CREATE TABLE cities (
    name            varchar(80),
    location        point
);

The point type is an example of a PostgreSQL-specific data type.

Finally, it should be mentioned that if you don't need a table any longer or want to recreate it differently you can remove it using the following command:

DROP TABLE tablename;

14.1. Using EXPLAIN #

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

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

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

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

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

14.1. Using EXPLAIN #

PostgreSQL devises a query plan for each query it receives. Choosing the right plan to match the query structure and the properties of the data is absolutely critical for good performance, so the system includes a complex planner that tries to choose good plans. You can use the EXPLAIN command to see what query plan the planner creates for any query. Plan-reading is an art that requires some experience to master, but this section attempts to cover the basics.

Examples in this section are drawn from the regression test database after doing a VACUUM ANALYZE, using v18 development sources. You should be able to get similar results if you try the examples yourself, but your estimated costs and row counts might vary slightly because ANALYZE's statistics are random samples rather than exact, and because costs are inherently somewhat platform-dependent.

The examples use EXPLAIN's default “text” output format, which is compact and convenient for humans to read. If you want to feed EXPLAIN's output to a program for further analysis, you should use one of its machine-readable output formats (XML, JSON, or YAML) instead.

14.1.1. EXPLAIN Basics #

The structure of a query plan is a tree of plan nodes. Nodes at the bottom level of the tree are scan nodes: they return raw rows from a table. There are different types of scan nodes for different table access methods: sequential scans, index scans, and bitmap index scans. There are also non-table row sources, such as VALUES clauses and set-returning functions in FROM, which have their own scan node types. If the query requires joining, aggregation, sorting, or other operations on the raw rows, then there will be additional nodes above the scan nodes to perform these operations. Again, there is usually more than one possible way to do these operations, so different node types can appear here too. The output of EXPLAIN has one line for each node in the plan tree, showing the basic node type plus the cost estimates that the planner made for the execution of that plan node. Additional lines might appear, indented from the node's summary line, to show additional properties of the node. The very first line (the summary line for the topmost node) has the estimated total execution cost for the plan; it is this number that the planner seeks to minimize.

Here is a trivial example, just to show what the output looks like:

EXPLAIN SELECT * FROM tenk1;

                         QUERY PLAN
-------------------------------------------------------------
 Seq Scan on tenk1  (cost=0.00..445.00 rows=10000 width=244)

Since this query has no WHERE clause, it must scan all the rows of the table, so the planner has chosen to use a simple sequential scan plan. The numbers that are quoted in parentheses are (left to right):

  • Estimated start-up cost. This is the time expended before the output phase can begin, e.g., time to do the sorting in a sort node.

  • Estimated total cost. This is stated on the assumption that the plan node is run to completion, i.e., all available rows are retrieved. In practice a node's parent node might stop short of reading all available rows (see the LIMIT example below).

  • Estimated number of rows output by this plan node. Again, the node is assumed to be run to completion.

  • Estimated average width of rows output by this plan node (in bytes).

The costs are measured in arbitrary units determined by the planner's cost parameters (see Section 19.7.2). Traditional practice is to measure the costs in units of disk page fetches; that is, seq_page_cost is conventionally set to 1.0 and the other cost parameters are set relative to that. The examples in this section are run with the default cost parameters.

It's important to understand that the cost of an upper-level node includes the cost of all its child nodes. It's also important to realize that the cost only reflects things that the planner cares about. In particular, the cost does not consider the time spent to convert output values to text form or to transmit them to the client, which could be important factors in the real elapsed time; but the planner ignores those costs because it cannot change them by altering the plan. (Every correct plan will output the same row set, we trust.)

The rows value is a little tricky because it is not the number of rows processed or scanned by the plan node, but rather the number emitted by the node. This is often less than the number scanned, as a result of filtering by any WHERE-clause conditions that are being applied at the node. Ideally the top-level rows estimate will approximate the number of rows actually returned, updated, or deleted by the query.

Returning to our example:

EXPLAIN SELECT * FROM tenk1;

                         QUERY PLAN
-------------------------------------------------------------
 Seq Scan on tenk1  (cost=0.00..445.00 rows=10000 width=244)

These numbers are derived very straightforwardly. If you do:

SELECT relpages, reltuples FROM pg_class WHERE relname = 'tenk1';

you will find that tenk1 has 345 disk pages and 10000 rows. The estimated cost is computed as (disk pages read * seq_page_cost) + (rows scanned * cpu_tuple_cost). By default, seq_page_cost is 1.0 and cpu_tuple_cost is 0.01, so the estimated cost is (345 * 1.0) + (10000 * 0.01) = 445.

Now let's modify the query to add a WHERE condition:

EXPLAIN SELECT * FROM tenk1 WHERE unique1 < 7000;

                         QUERY PLAN
------------------------------------------------------------
 Seq Scan on tenk1  (cost=0.00..470.00 rows=7000 width=244)
   Filter: (unique1 < 7000)

Notice that the EXPLAIN output shows the WHERE clause being applied as a “filter” condition attached to the Seq Scan plan node. This means that the plan node checks the condition for each row it scans, and outputs only the ones that pass the condition. The estimate of output rows has been reduced because of the WHERE clause. However, the scan will still have to visit all 10000 rows, so the cost hasn't decreased; in fact it has gone up a bit (by 10000 * cpu_operator_cost, to be exact) to reflect the extra CPU time spent checking the WHERE condition.

The actual number of rows this query would select is 7000, but the rows estimate is only approximate. If you try to duplicate this experiment, you may well get a slightly different estimate; moreover, it can change after each ANALYZE command, because the statistics produced by ANALYZE are taken from a randomized sample of the table.

Now, let's make the condition more restrictive:

EXPLAIN SELECT * FROM tenk1 WHERE unique1 < 100;

                                  QUERY PLAN
-------------------------------------------------------------------​-----------
 Bitmap Heap Scan on tenk1  (cost=5.06..224.98 rows=100 width=244)
   Recheck Cond: (unique1 < 100)
   ->  Bitmap Index Scan on tenk1_unique1  (cost=0.00..5.04 rows=100 width=0)
         Index Cond: (unique1 < 100)

Here the planner has decided to use a two-step plan: the child plan node visits an index to find the locations of rows matching the index condition, and then the upper plan node actually fetches those rows from the table itself. Fetching rows separately is much more expensive than reading them sequentially, but because not all the pages of the table have to be visited, this is still cheaper than a sequential scan. (The reason for using two plan levels is that the upper plan node sorts the row locations identified by the index into physical order before reading them, to minimize the cost of separate fetches. The “bitmap” mentioned in the node names is the mechanism that does the sorting.)

Now let's add another condition to the WHERE clause:

EXPLAIN SELECT * FROM tenk1 WHERE unique1 < 100 AND stringu1 = 'xxx';

                                  QUERY PLAN
-------------------------------------------------------------------​-----------
 Bitmap Heap Scan on tenk1  (cost=5.04..225.20 rows=1 width=244)
   Recheck Cond: (unique1 < 100)
   Filter: (stringu1 = 'xxx'::name)
   ->  Bitmap Index Scan on tenk1_unique1  (cost=0.00..5.04 rows=100 width=0)
         Index Cond: (unique1 < 100)

The added condition stringu1 = 'xxx' reduces the output row count estimate, but not the cost because we still have to visit the same set of rows. That's because the stringu1 clause cannot be applied as an index condition, since this index is only on the unique1 column. Instead it is applied as a filter on the rows retrieved using the index. Thus the cost has actually gone up slightly to reflect this extra checking.

In some cases the planner will prefer a “simple” index scan plan:

EXPLAIN SELECT * FROM tenk1 WHERE unique1 = 42;

                                 QUERY PLAN
-------------------------------------------------------------------​----------
 Index Scan using tenk1_unique1 on tenk1  (cost=0.29..8.30 rows=1 width=244)
   Index Cond: (unique1 = 42)

In this type of plan the table rows are fetched in index order, which makes them even more expensive to read, but there are so few that the extra cost of sorting the row locations is not worth it. You'll most often see this plan type for queries that fetch just a single row. It's also often used for queries that have an ORDER BY condition that matches the index order, because then no extra sorting step is needed to satisfy the ORDER BY. In this example, adding ORDER BY unique1 would use the same plan because the index already implicitly provides the requested ordering.

The planner may implement an ORDER BY clause in several ways. The above example shows that such an ordering clause may be implemented implicitly. The planner may also add an explicit Sort step:

EXPLAIN SELECT * FROM tenk1 ORDER BY unique1;

                            QUERY PLAN
-------------------------------------------------------------------
 Sort  (cost=1109.39..1134.39 rows=10000 width=244)
   Sort Key: unique1
   ->  Seq Scan on tenk1  (cost=0.00..445.00 rows=10000 width=244)

If a part of the plan guarantees an ordering on a prefix of the required sort keys, then the planner may instead decide to use an Incremental Sort step:

EXPLAIN SELECT * FROM tenk1 ORDER BY hundred, ten LIMIT 100;

                                              QUERY PLAN
-------------------------------------------------------------------​-----------------------------
 Limit  (cost=19.35..39.49 rows=100 width=244)
   ->  Incremental Sort  (cost=19.35..2033.39 rows=10000 width=244)
         Sort Key: hundred, ten
         Presorted Key: hundred
         ->  Index Scan using tenk1_hundred on tenk1  (cost=0.29..1574.20 rows=10000 width=244)

Compared to regular sorts, sorting incrementally allows returning tuples before the entire result set has been sorted, which particularly enables optimizations with LIMIT queries. It may also reduce memory usage and the likelihood of spilling sorts to disk, but it comes at the cost of the increased overhead of splitting the result set into multiple sorting batches.

If there are separate indexes on several of the columns referenced in WHERE, the planner might choose to use an AND or OR combination of the indexes:

EXPLAIN SELECT * FROM tenk1 WHERE unique1 < 100 AND unique2 > 9000;

                                     QUERY PLAN
-------------------------------------------------------------------​------------------
 Bitmap Heap Scan on tenk1  (cost=25.07..60.11 rows=10 width=244)
   Recheck Cond: ((unique1 < 100) AND (unique2 > 9000))
   ->  BitmapAnd  (cost=25.07..25.07 rows=10 width=0)
         ->  Bitmap Index Scan on tenk1_unique1  (cost=0.00..5.04 rows=100 width=0)
               Index Cond: (unique1 < 100)
         ->  Bitmap Index Scan on tenk1_unique2  (cost=0.00..19.78 rows=999 width=0)
               Index Cond: (unique2 > 9000)

But this requires visiting both indexes, so it's not necessarily a win compared to using just one index and treating the other condition as a filter. If you vary the ranges involved you'll see the plan change accordingly.

Here is an example showing the effects of LIMIT:

EXPLAIN SELECT * FROM tenk1 WHERE unique1 < 100 AND unique2 > 9000 LIMIT 2;

                                     QUERY PLAN
-------------------------------------------------------------------​------------------
 Limit  (cost=0.29..14.28 rows=2 width=244)
   ->  Index Scan using tenk1_unique2 on tenk1  (cost=0.29..70.27 rows=10 width=244)
         Index Cond: (unique2 > 9000)
         Filter: (unique1 < 100)

This is the same query as above, but we added a LIMIT so that not all the rows need be retrieved, and the planner changed its mind about what to do. Notice that the total cost and row count of the Index Scan node are shown as if it were run to completion. However, the Limit node is expected to stop after retrieving only a fifth of those rows, so its total cost is only a fifth as much, and that's the actual estimated cost of the query. This plan is preferred over adding a Limit node to the previous plan because the Limit could not avoid paying the startup cost of the bitmap scan, so the total cost would be something over 25 units with that approach.

Let's try joining two tables, using the columns we have been discussing:

EXPLAIN SELECT *
FROM tenk1 t1, tenk2 t2
WHERE t1.unique1 < 10 AND t1.unique2 = t2.unique2;

                                      QUERY PLAN
-------------------------------------------------------------------​-------------------
 Nested Loop  (cost=4.65..118.50 rows=10 width=488)
   ->  Bitmap Heap Scan on tenk1 t1  (cost=4.36..39.38 rows=10 width=244)
         Recheck Cond: (unique1 < 10)
         ->  Bitmap Index Scan on tenk1_unique1  (cost=0.00..4.36 rows=10 width=0)
               Index Cond: (unique1 < 10)
   ->  Index Scan using tenk2_unique2 on tenk2 t2  (cost=0.29..7.90 rows=1 width=244)
         Index Cond: (unique2 = t1.unique2)

In this plan, we have a nested-loop join node with two table scans as inputs, or children. The indentation of the node summary lines reflects the plan tree structure. The join's first, or “outer”, child is a bitmap scan similar to those we saw before. Its cost and row count are the same as we'd get from SELECT ... WHERE unique1 < 10 because we are applying the WHERE clause unique1 < 10 at that node. The t1.unique2 = t2.unique2 clause is not relevant yet, so it doesn't affect the row count of the outer scan. The nested-loop join node will run its second, or “inner” child once for each row obtained from the outer child. Column values from the current outer row can be plugged into the inner scan; here, the t1.unique2 value from the outer row is available, so we get a plan and costs similar to what we saw above for a simple SELECT ... WHERE t2.unique2 = constant case. (The estimated cost is actually a bit lower than what was seen above, as a result of caching that's expected to occur during the repeated index scans on t2.) The costs of the loop node are then set on the basis of the cost of the outer scan, plus one repetition of the inner scan for each outer row (10 * 7.90, here), plus a little CPU time for join processing.

In this example the join's output row count is the same as the product of the two scans' row counts, but that's not true in all cases because there can be additional WHERE clauses that mention both tables and so can only be applied at the join point, not to either input scan. Here's an example:

EXPLAIN SELECT *
FROM tenk1 t1, tenk2 t2
WHERE t1.unique1 < 10 AND t2.unique2 < 10 AND t1.hundred < t2.hundred;

                                         QUERY PLAN
-------------------------------------------------------------------​--------------------------
 Nested Loop  (cost=4.65..49.36 rows=33 width=488)
   Join Filter: (t1.hundred < t2.hundred)
   ->  Bitmap Heap Scan on tenk1 t1  (cost=4.36..39.38 rows=10 width=244)
         Recheck Cond: (unique1 < 10)
         ->  Bitmap Index Scan on tenk1_unique1  (cost=0.00..4.36 rows=10 width=0)
               Index Cond: (unique1 < 10)
   ->  Materialize  (cost=0.29..8.51 rows=10 width=244)
         ->  Index Scan using tenk2_unique2 on tenk2 t2  (cost=0.29..8.46 rows=10 width=244)
               Index Cond: (unique2 < 10)

The condition t1.hundred < t2.hundred can't be tested in the tenk2_unique2 index, so it's applied at the join node. This reduces the estimated output row count of the join node, but does not change either input scan.

Notice that here the planner has chosen to “materialize” the inner relation of the join, by putting a Materialize plan node atop it. This means that the t2 index scan will be done just once, even though the nested-loop join node needs to read that data ten times, once for each row from the outer relation. The Materialize node saves the data in memory as it's read, and then returns the data from memory on each subsequent pass.

When dealing with outer joins, you might see join plan nodes with both “Join Filter” and plain “Filter” conditions attached. Join Filter conditions come from the outer join's ON clause, so a row that fails the Join Filter condition could still get emitted as a null-extended row. But a plain Filter condition is applied after the outer-join rules and so acts to remove rows unconditionally. In an inner join there is no semantic difference between these types of filters.

If we change the query's selectivity a bit, we might get a very different join plan:

EXPLAIN SELECT *
FROM tenk1 t1, tenk2 t2
WHERE t1.unique1 < 100 AND t1.unique2 = t2.unique2;

                                        QUERY PLAN
-------------------------------------------------------------------​-----------------------
 Hash Join  (cost=226.23..709.73 rows=100 width=488)
   Hash Cond: (t2.unique2 = t1.unique2)
   ->  Seq Scan on tenk2 t2  (cost=0.00..445.00 rows=10000 width=244)
   ->  Hash  (cost=224.98..224.98 rows=100 width=244)
         ->  Bitmap Heap Scan on tenk1 t1  (cost=5.06..224.98 rows=100 width=244)
               Recheck Cond: (unique1 < 100)
               ->  Bitmap Index Scan on tenk1_unique1  (cost=0.00..5.04 rows=100 width=0)
                     Index Cond: (unique1 < 100)

Here, the planner has chosen to use a hash join, in which rows of one table are entered into an in-memory hash table, after which the other table is scanned and the hash table is probed for matches to each row. Again note how the indentation reflects the plan structure: the bitmap scan on tenk1 is the input to the Hash node, which constructs the hash table. That's then returned to the Hash Join node, which reads rows from its outer child plan and searches the hash table for each one.

Another possible type of join is a merge join, illustrated here:

EXPLAIN SELECT *
FROM tenk1 t1, onek t2
WHERE t1.unique1 < 100 AND t1.unique2 = t2.unique2;

                                        QUERY PLAN
-------------------------------------------------------------------​-----------------------
 Merge Join  (cost=0.56..233.49 rows=10 width=488)
   Merge Cond: (t1.unique2 = t2.unique2)
   ->  Index Scan using tenk1_unique2 on tenk1 t1  (cost=0.29..643.28 rows=100 width=244)
         Filter: (unique1 < 100)
   ->  Index Scan using onek_unique2 on onek t2  (cost=0.28..166.28 rows=1000 width=244)

Merge join requires its input data to be sorted on the join keys. In this example each input is sorted by using an index scan to visit the rows in the correct order; but a sequential scan and sort could also be used. (Sequential-scan-and-sort frequently beats an index scan for sorting many rows, because of the nonsequential disk access required by the index scan.)

One way to look at variant plans is to force the planner to disregard whatever strategy it thought was the cheapest, using the enable/disable flags described in Section 19.7.1. (This is a crude tool, but useful. See also Section 14.3.) For example, if we're unconvinced that merge join is the best join type for the previous example, we could try

SET enable_mergejoin = off;

EXPLAIN SELECT *
FROM tenk1 t1, onek t2
WHERE t1.unique1 < 100 AND t1.unique2 = t2.unique2;

                                        QUERY PLAN
-------------------------------------------------------------------​-----------------------
 Hash Join  (cost=226.23..344.08 rows=10 width=488)
   Hash Cond: (t2.unique2 = t1.unique2)
   ->  Seq Scan on onek t2  (cost=0.00..114.00 rows=1000 width=244)
   ->  Hash  (cost=224.98..224.98 rows=100 width=244)
         ->  Bitmap Heap Scan on tenk1 t1  (cost=5.06..224.98 rows=100 width=244)
               Recheck Cond: (unique1 < 100)
               ->  Bitmap Index Scan on tenk1_unique1  (cost=0.00..5.04 rows=100 width=0)
                     Index Cond: (unique1 < 100)

which shows that the planner thinks that hash join would be nearly 50% more expensive than merge join for this case. Of course, the next question is whether it's right about that. We can investigate that using EXPLAIN ANALYZE, as discussed below.

When using the enable/disable flags to disable plan node types, many of the flags only discourage the use of the corresponding plan node and don't outright disallow the planner's ability to use the plan node type. This is by design so that the planner still maintains the ability to form a plan for a given query. When the resulting plan contains a disabled node, the EXPLAIN output will indicate this fact.

SET enable_seqscan = off;
EXPLAIN SELECT * FROM unit;

                       QUERY PLAN
---------------------------------------------------------
 Seq Scan on unit  (cost=0.00..21.30 rows=1130 width=44)
   Disabled: true

Because the unit table has no indexes, there is no other means to read the table data, so the sequential scan is the only option available to the query planner.

Some query plans involve subplans, which arise from sub-SELECTs in the original query. Such queries can sometimes be transformed into ordinary join plans, but when they cannot be, we get plans like:

EXPLAIN VERBOSE SELECT unique1
FROM tenk1 t
WHERE t.ten < ALL (SELECT o.ten FROM onek o WHERE o.four = t.four);

                               QUERY PLAN
-------------------------------------------------------------------​------
 Seq Scan on public.tenk1 t  (cost=0.00..586095.00 rows=5000 width=4)
   Output: t.unique1
   Filter: (ALL (t.ten < (SubPlan 1).col1))
   SubPlan 1
     ->  Seq Scan on public.onek o  (cost=0.00..116.50 rows=250 width=4)
           Output: o.ten
           Filter: (o.four = t.four)

This rather artificial example serves to illustrate a couple of points: values from the outer plan level can be passed down into a subplan (here, t.four is passed down) and the results of the sub-select are available to the outer plan. Those result values are shown by EXPLAIN with notations like (subplan_name).colN, which refers to the N'th output column of the sub-SELECT.

In the example above, the ALL operator runs the subplan again for each row of the outer query (which accounts for the high estimated cost). Some queries can use a hashed subplan to avoid that:

EXPLAIN SELECT *
FROM tenk1 t
WHERE t.unique1 NOT IN (SELECT o.unique1 FROM onek o);

                                         QUERY PLAN
-------------------------------------------------------------------​-------------------------
 Seq Scan on tenk1 t  (cost=61.77..531.77 rows=5000 width=244)
   Filter: (NOT (ANY (unique1 = (hashed SubPlan 1).col1)))
   SubPlan 1
     ->  Index Only Scan using onek_unique1 on onek o  (cost=0.28..59.27 rows=1000 width=4)
(4 rows)

Here, the subplan is run a single time and its output is loaded into an in-memory hash table, which is then probed by the outer ANY operator. This requires that the sub-SELECT not reference any variables of the outer query, and that the ANY's comparison operator be amenable to hashing.

If, in addition to not referencing any variables of the outer query, the sub-SELECT cannot return more than one row, it may instead be implemented as an initplan:

EXPLAIN VERBOSE SELECT unique1
FROM tenk1 t1 WHERE t1.ten = (SELECT (random() * 10)::integer);

                             QUERY PLAN
------------------------------------------------------------​--------
 Seq Scan on public.tenk1 t1  (cost=0.02..470.02 rows=1000 width=4)
   Output: t1.unique1
   Filter: (t1.ten = (InitPlan 1).col1)
   InitPlan 1
     ->  Result  (cost=0.00..0.02 rows=1 width=4)
           Output: ((random() * '10'::double precision))::integer

An initplan is run only once per execution of the outer plan, and its results are saved for re-use in later rows of the outer plan. So in this example random() is evaluated only once and all the values of t1.ten are compared to the same randomly-chosen integer. That's quite different from what would happen without the sub-SELECT construct.

14.1.2. EXPLAIN ANALYZE #

It is possible to check the accuracy of the planner's estimates by using EXPLAIN's ANALYZE option. With this option, EXPLAIN actually executes the query, and then displays the true row counts and true run time accumulated within each plan node, along with the same estimates that a plain EXPLAIN shows. For example, we might get a result like this:

EXPLAIN ANALYZE SELECT *
FROM tenk1 t1, tenk2 t2
WHERE t1.unique1 < 10 AND t1.unique2 = t2.unique2;

                                                           QUERY PLAN
-------------------------------------------------------------------​--------------------------------------------------------------
 Nested Loop  (cost=4.65..118.50 rows=10 width=488) (actual time=0.017..0.051 rows=10.00 loops=1)
   Buffers: shared hit=36 read=6
   ->  Bitmap Heap Scan on tenk1 t1  (cost=4.36..39.38 rows=10 width=244) (actual time=0.009..0.017 rows=10.00 loops=1)
         Recheck Cond: (unique1 < 10)
         Heap Blocks: exact=10
         Buffers: shared hit=3 read=5 written=4
         ->  Bitmap Index Scan on tenk1_unique1  (cost=0.00..4.36 rows=10 width=0) (actual time=0.004..0.004 rows=10.00 loops=1)
               Index Cond: (unique1 < 10)
               Index Searches: 1
               Buffers: shared hit=2
   ->  Index Scan using tenk2_unique2 on tenk2 t2  (cost=0.29..7.90 rows=1 width=244) (actual time=0.003..0.003 rows=1.00 loops=10)
         Index Cond: (unique2 = t1.unique2)
         Index Searches: 10
         Buffers: shared hit=24 read=6
 Planning:
   Buffers: shared hit=15 dirtied=9
 Planning Time: 0.485 ms
 Execution Time: 0.073 ms

Note that the “actual time” values are in milliseconds of real time, whereas the cost estimates are expressed in arbitrary units; so they are unlikely to match up. The thing that's usually most important to look for is whether the estimated row counts are reasonably close to reality. In this example the estimates were all dead-on, but that's quite unusual in practice.

In some query plans, it is possible for a subplan node to be executed more than once. For example, the inner index scan will be executed once per outer row in the above nested-loop plan. In such cases, the loops value reports the total number of executions of the node, and the actual time and rows values shown are averages per-execution. This is done to make the numbers comparable with the way that the cost estimates are shown. Multiply by the loops value to get the total time actually spent in the node. In the above example, we spent a total of 0.030 milliseconds executing the index scans on tenk2.

In some cases EXPLAIN ANALYZE shows additional execution statistics beyond the plan node execution times and row counts. For example, Sort and Hash nodes provide extra information:

EXPLAIN ANALYZE SELECT *
FROM tenk1 t1, tenk2 t2
WHERE t1.unique1 < 100 AND t1.unique2 = t2.unique2 ORDER BY t1.fivethous;

                                                                 QUERY PLAN
-------------------------------------------------------------------​-------------------------------------------------------------------​------
 Sort  (cost=713.05..713.30 rows=100 width=488) (actual time=2.995..3.002 rows=100.00 loops=1)
   Sort Key: t1.fivethous
   Sort Method: quicksort  Memory: 74kB
   Buffers: shared hit=440
   ->  Hash Join  (cost=226.23..709.73 rows=100 width=488) (actual time=0.515..2.920 rows=100.00 loops=1)
         Hash Cond: (t2.unique2 = t1.unique2)
         Buffers: shared hit=437
         ->  Seq Scan on tenk2 t2  (cost=0.00..445.00 rows=10000 width=244) (actual time=0.026..1.790 rows=10000.00 loops=1)
               Buffers: shared hit=345
         ->  Hash  (cost=224.98..224.98 rows=100 width=244) (actual time=0.476..0.477 rows=100.00 loops=1)
               Buckets: 1024  Batches: 1  Memory Usage: 35kB
               Buffers: shared hit=92
               ->  Bitmap Heap Scan on tenk1 t1  (cost=5.06..224.98 rows=100 width=244) (actual time=0.030..0.450 rows=100.00 loops=1)
                     Recheck Cond: (unique1 < 100)
                     Heap Blocks: exact=90
                     Buffers: shared hit=92
                     ->  Bitmap Index Scan on tenk1_unique1  (cost=0.00..5.04 rows=100 width=0) (actual time=0.013..0.013 rows=100.00 loops=1)
                           Index Cond: (unique1 < 100)
                           Index Searches: 1
                           Buffers: shared hit=2
 Planning:
   Buffers: shared hit=12
 Planning Time: 0.187 ms
 Execution Time: 3.036 ms

The Sort node shows the sort method used (in particular, whether the sort was in-memory or on-disk) and the amount of memory or disk space needed. The Hash node shows the number of hash buckets and batches as well as the peak amount of memory used for the hash table. (If the number of batches exceeds one, there will also be disk space usage involved, but that is not shown.)

Index Scan nodes (as well as Bitmap Index Scan and Index-Only Scan nodes) show an “Index Searches” line that reports the total number of searches across all node executions/loops:

EXPLAIN ANALYZE SELECT * FROM tenk1 WHERE thousand IN (1, 500, 700, 999);
                                                            QUERY PLAN
-------------------------------------------------------------------​---------------------------------------------------------------
 Bitmap Heap Scan on tenk1  (cost=9.45..73.44 rows=40 width=244) (actual time=0.012..0.028 rows=40.00 loops=1)
   Recheck Cond: (thousand = ANY ('{1,500,700,999}'::integer[]))
   Heap Blocks: exact=39
   Buffers: shared hit=47
   ->  Bitmap Index Scan on tenk1_thous_tenthous  (cost=0.00..9.44 rows=40 width=0) (actual time=0.009..0.009 rows=40.00 loops=1)
         Index Cond: (thousand = ANY ('{1,500,700,999}'::integer[]))
         Index Searches: 4
         Buffers: shared hit=8
 Planning Time: 0.029 ms
 Execution Time: 0.034 ms

Here we see a Bitmap Index Scan node that needed 4 separate index searches. The scan had to search the index from the tenk1_thous_tenthous index root page once per integer value from the predicate's IN construct. However, the number of index searches often won't have such a simple correspondence to the query predicate:

EXPLAIN ANALYZE SELECT * FROM tenk1 WHERE thousand IN (1, 2, 3, 4);
                                                            QUERY PLAN
-------------------------------------------------------------------​---------------------------------------------------------------
 Bitmap Heap Scan on tenk1  (cost=9.45..73.44 rows=40 width=244) (actual time=0.009..0.019 rows=40.00 loops=1)
   Recheck Cond: (thousand = ANY ('{1,2,3,4}'::integer[]))
   Heap Blocks: exact=38
   Buffers: shared hit=40
   ->  Bitmap Index Scan on tenk1_thous_tenthous  (cost=0.00..9.44 rows=40 width=0) (actual time=0.005..0.005 rows=40.00 loops=1)
         Index Cond: (thousand = ANY ('{1,2,3,4}'::integer[]))
         Index Searches: 1
         Buffers: shared hit=2
 Planning Time: 0.029 ms
 Execution Time: 0.026 ms

This variant of our IN query performed only 1 index search. It spent less time traversing the index (compared to the original query) because its IN construct uses values matching index tuples stored next to each other, on the same tenk1_thous_tenthous index leaf page.

The “Index Searches” line is also useful with B-tree index scans that apply the skip scan optimization to more efficiently traverse through an index:

EXPLAIN ANALYZE SELECT four, unique1 FROM tenk1 WHERE four BETWEEN 1 AND 3 AND unique1 = 42;
                                                              QUERY PLAN
-------------------------------------------------------------------​---------------------------------------------------------------
 Index Only Scan using tenk1_four_unique1_idx on tenk1  (cost=0.29..6.90 rows=1 width=8) (actual time=0.006..0.007 rows=1.00 loops=1)
   Index Cond: ((four >= 1) AND (four <= 3) AND (unique1 = 42))
   Heap Fetches: 0
   Index Searches: 3
   Buffers: shared hit=7
 Planning Time: 0.029 ms
 Execution Time: 0.012 ms

Here we see an Index-Only Scan node using tenk1_four_unique1_idx, a multi-column index on the tenk1 table's four and unique1 columns. The scan performs 3 searches that each read a single index leaf page: “four = 1 AND unique1 = 42”, “four = 2 AND unique1 = 42”, and “four = 3 AND unique1 = 42”. This index is generally a good target for skip scan, since, as discussed in Section 11.3, its leading column (the four column) contains only 4 distinct values, while its second/final column (the unique1 column) contains many distinct values.

Another type of extra information is the number of rows removed by a filter condition:

EXPLAIN ANALYZE SELECT * FROM tenk1 WHERE ten < 7;

                                               QUERY PLAN
-------------------------------------------------------------------​--------------------------------------
 Seq Scan on tenk1  (cost=0.00..470.00 rows=7000 width=244) (actual time=0.030..1.995 rows=7000.00 loops=1)
   Filter: (ten < 7)
   Rows Removed by Filter: 3000
   Buffers: shared hit=345
 Planning Time: 0.102 ms
 Execution Time: 2.145 ms

These counts can be particularly valuable for filter conditions applied at join nodes. The “Rows Removed” line only appears when at least one scanned row, or potential join pair in the case of a join node, is rejected by the filter condition.

A case similar to filter conditions occurs with “lossy” index scans. For example, consider this search for polygons containing a specific point:

EXPLAIN ANALYZE SELECT * FROM polygon_tbl WHERE f1 @> polygon '(0.5,2.0)';

                                              QUERY PLAN
-------------------------------------------------------------------​-----------------------------------
 Seq Scan on polygon_tbl  (cost=0.00..1.09 rows=1 width=85) (actual time=0.023..0.023 rows=0.00 loops=1)
   Filter: (f1 @> '((0.5,2))'::polygon)
   Rows Removed by Filter: 7
   Buffers: shared hit=1
 Planning Time: 0.039 ms
 Execution Time: 0.033 ms

The planner thinks (quite correctly) that this sample table is too small to bother with an index scan, so we have a plain sequential scan in which all the rows got rejected by the filter condition. But if we force an index scan to be used, we see:

SET enable_seqscan TO off;

EXPLAIN ANALYZE SELECT * FROM polygon_tbl WHERE f1 @> polygon '(0.5,2.0)';

                                                        QUERY PLAN
-------------------------------------------------------------------​-------------------------------------------------------
 Index Scan using gpolygonind on polygon_tbl  (cost=0.13..8.15 rows=1 width=85) (actual time=0.074..0.074 rows=0.00 loops=1)
   Index Cond: (f1 @> '((0.5,2))'::polygon)
   Rows Removed by Index Recheck: 1
   Index Searches: 1
   Buffers: shared hit=1
 Planning Time: 0.039 ms
 Execution Time: 0.098 ms

Here we can see that the index returned one candidate row, which was then rejected by a recheck of the index condition. This happens because a GiST index is “lossy” for polygon containment tests: it actually returns the rows with polygons that overlap the target, and then we have to do the exact containment test on those rows.

EXPLAIN has a BUFFERS option which provides additional detail about I/O operations performed during the planning and execution of the given query. The buffer numbers displayed show the count of the non-distinct buffers hit, read, dirtied, and written for the given node and all of its child nodes. The ANALYZE option implicitly enables the BUFFERS option. If this is undesired, BUFFERS may be explicitly disabled:

EXPLAIN (ANALYZE, BUFFERS OFF) SELECT * FROM tenk1 WHERE unique1 < 100 AND unique2 > 9000;

                                                           QUERY PLAN
-------------------------------------------------------------------​--------------------------------------------------------------
 Bitmap Heap Scan on tenk1  (cost=25.07..60.11 rows=10 width=244) (actual time=0.105..0.114 rows=10.00 loops=1)
   Recheck Cond: ((unique1 < 100) AND (unique2 > 9000))
   Heap Blocks: exact=10
   ->  BitmapAnd  (cost=25.07..25.07 rows=10 width=0) (actual time=0.100..0.101 rows=0.00 loops=1)
         ->  Bitmap Index Scan on tenk1_unique1  (cost=0.00..5.04 rows=100 width=0) (actual time=0.027..0.027 rows=100.00 loops=1)
               Index Cond: (unique1 < 100)
               Index Searches: 1
         ->  Bitmap Index Scan on tenk1_unique2  (cost=0.00..19.78 rows=999 width=0) (actual time=0.070..0.070 rows=999.00 loops=1)
               Index Cond: (unique2 > 9000)
               Index Searches: 1
 Planning Time: 0.162 ms
 Execution Time: 0.143 ms

Keep in mind that because EXPLAIN ANALYZE actually runs the query, any side-effects will happen as usual, even though whatever results the query might output are discarded in favor of printing the EXPLAIN data. If you want to analyze a data-modifying query without changing your tables, you can roll the command back afterwards, for example:

BEGIN;

EXPLAIN ANALYZE UPDATE tenk1 SET hundred = hundred + 1 WHERE unique1 < 100;

                                                           QUERY PLAN
-------------------------------------------------------------------​-------------------------------------------------------------
 Update on tenk1  (cost=5.06..225.23 rows=0 width=0) (actual time=1.634..1.635 rows=0.00 loops=1)
   ->  Bitmap Heap Scan on tenk1  (cost=5.06..225.23 rows=100 width=10) (actual time=0.065..0.141 rows=100.00 loops=1)
         Recheck Cond: (unique1 < 100)
         Heap Blocks: exact=90
         Buffers: shared hit=4 read=2
         ->  Bitmap Index Scan on tenk1_unique1  (cost=0.00..5.04 rows=100 width=0) (actual time=0.031..0.031 rows=100.00 loops=1)
               Index Cond: (unique1 < 100)
               Index Searches: 1
               Buffers: shared read=2
 Planning Time: 0.151 ms
 Execution Time: 1.856 ms

ROLLBACK;

As seen in this example, when the query is an INSERT, UPDATE, DELETE, or MERGE command, the actual work of applying the table changes is done by a top-level Insert, Update, Delete, or Merge plan node. The plan nodes underneath this node perform the work of locating the old rows and/or computing the new data. So above, we see the same sort of bitmap table scan we've seen already, and its output is fed to an Update node that stores the updated rows. It's worth noting that although the data-modifying node can take a considerable amount of run time (here, it's consuming the lion's share of the time), the planner does not currently add anything to the cost estimates to account for that work. That's because the work to be done is the same for every correct query plan, so it doesn't affect planning decisions.

When an UPDATE, DELETE, or MERGE command affects a partitioned table or inheritance hierarchy, the output might look like this:

EXPLAIN UPDATE gtest_parent SET f1 = CURRENT_DATE WHERE f2 = 101;

                                       QUERY PLAN
-------------------------------------------------------------------​---------------------
 Update on gtest_parent  (cost=0.00..3.06 rows=0 width=0)
   Update on gtest_child gtest_parent_1
   Update on gtest_child2 gtest_parent_2
   Update on gtest_child3 gtest_parent_3
   ->  Append  (cost=0.00..3.06 rows=3 width=14)
         ->  Seq Scan on gtest_child gtest_parent_1  (cost=0.00..1.01 rows=1 width=14)
               Filter: (f2 = 101)
         ->  Seq Scan on gtest_child2 gtest_parent_2  (cost=0.00..1.01 rows=1 width=14)
               Filter: (f2 = 101)
         ->  Seq Scan on gtest_child3 gtest_parent_3  (cost=0.00..1.01 rows=1 width=14)
               Filter: (f2 = 101)

In this example the Update node needs to consider three child tables, but not the originally-mentioned partitioned table (since that never stores any data). So there are three input scanning subplans, one per table. For clarity, the Update node is annotated to show the specific target tables that will be updated, in the same order as the corresponding subplans.

The Planning time shown by EXPLAIN ANALYZE is the time it took to generate the query plan from the parsed query and optimize it. It does not include parsing or rewriting.

The Execution time shown by EXPLAIN ANALYZE includes executor start-up and shut-down time, as well as the time to run any triggers that are fired, but it does not include parsing, rewriting, or planning time. Time spent executing BEFORE triggers, if any, is included in the time for the related Insert, Update, or Delete node; but time spent executing AFTER triggers is not counted there because AFTER triggers are fired after completion of the whole plan. The total time spent in each trigger (either BEFORE or AFTER) is also shown separately. Note that deferred constraint triggers will not be executed until end of transaction and are thus not considered at all by EXPLAIN ANALYZE.

The time shown for the top-level node does not include any time needed to convert the query's output data into displayable form or to send it to the client. While EXPLAIN ANALYZE will never send the data to the client, it can be told to convert the query's output data to displayable form and measure the time needed for that, by specifying the SERIALIZE option. That time will be shown separately, and it's also included in the total Execution time.

14.1.3. Caveats #

There are two significant ways in which run times measured by EXPLAIN ANALYZE can deviate from normal execution of the same query. First, since no output rows are delivered to the client, network transmission costs are not included. I/O conversion costs are not included either unless SERIALIZE is specified. Second, the measurement overhead added by EXPLAIN ANALYZE can be significant, especially on machines with slow gettimeofday() operating-system calls. You can use the pg_test_timing tool to measure the overhead of timing on your system.

EXPLAIN results should not be extrapolated to situations much different from the one you are actually testing; for example, results on a toy-sized table cannot be assumed to apply to large tables. The planner's cost estimates are not linear and so it might choose a different plan for a larger or smaller table. An extreme example is that on a table that only occupies one disk page, you'll nearly always get a sequential scan plan whether indexes are available or not. The planner realizes that it's going to take one disk page read to process the table in any case, so there's no value in expending additional page reads to look at an index. (We saw this happening in the polygon_tbl example above.)

There are cases in which the actual and estimated values won't match up well, but nothing is really wrong. One such case occurs when plan node execution is stopped short by a LIMIT or similar effect. For example, in the LIMIT query we used before,

EXPLAIN ANALYZE SELECT * FROM tenk1 WHERE unique1 < 100 AND unique2 > 9000 LIMIT 2;

                                                          QUERY PLAN
-------------------------------------------------------------------​------------------------------------------------------------
 Limit  (cost=0.29..14.33 rows=2 width=244) (actual time=0.051..0.071 rows=2.00 loops=1)
   Buffers: shared hit=16
   ->  Index Scan using tenk1_unique2 on tenk1  (cost=0.29..70.50 rows=10 width=244) (actual time=0.051..0.070 rows=2.00 loops=1)
         Index Cond: (unique2 > 9000)
         Filter: (unique1 < 100)
         Rows Removed by Filter: 287
         Index Searches: 1
         Buffers: shared hit=16
 Planning Time: 0.077 ms
 Execution Time: 0.086 ms

the estimated cost and row count for the Index Scan node are shown as though it were run to completion. But in reality the Limit node stopped requesting rows after it got two, so the actual row count is only 2 and the run time is less than the cost estimate would suggest. This is not an estimation error, only a discrepancy in the way the estimates and true values are displayed.

Merge joins also have measurement artifacts that can confuse the unwary. A merge join will stop reading one input if it's exhausted the other input and the next key value in the one input is greater than the last key value of the other input; in such a case there can be no more matches and so no need to scan the rest of the first input. This results in not reading all of one child, with results like those mentioned for LIMIT. Also, if the outer (first) child contains rows with duplicate key values, the inner (second) child is backed up and rescanned for the portion of its rows matching that key value. EXPLAIN ANALYZE counts these repeated emissions of the same inner rows as if they were real additional rows. When there are many outer duplicates, the reported actual row count for the inner child plan node can be significantly larger than the number of rows that are actually in the inner relation.

BitmapAnd and BitmapOr nodes always report their actual row counts as zero, due to implementation limitations.

Normally, EXPLAIN will display every plan node created by the planner. However, there are cases where the executor can determine that certain nodes need not be executed because they cannot produce any rows, based on parameter values that were not available at planning time. (Currently this can only happen for child nodes of an Append or MergeAppend node that is scanning a partitioned table.) When this happens, those plan nodes are omitted from the EXPLAIN output and a Subplans Removed: N annotation appears instead.

2.2. Data Preprocessing Open the notebook in SageMaker Studio Lab

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

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

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

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

2.2. Data Preprocessing
Open the notebook in SageMaker Studio Lab

So far, we have been working with synthetic data that arrived in ready-made tensors. However, to apply deep learning in the wild we must extract messy data stored in arbitrary formats, and preprocess it to suit our needs. Fortunately, the pandas library can do much of the heavy lifting. This section, while no substitute for a proper pandas tutorial, will give you a crash course on some of the most common routines.

2.2.1. Reading the Dataset

Comma-separated values (CSV) files are ubiquitous for the storing of tabular (spreadsheet-like) data. In them, each line corresponds to one record and consists of several (comma-separated) fields, e.g., “Albert Einstein,March 14 1879,Ulm,Federal polytechnic school,field of gravitational physics”. To demonstrate how to load CSV files with pandas, we create a CSV file below ../data/house_tiny.csv. This file represents a dataset of homes, where each row corresponds to a distinct home and the columns correspond to the number of rooms (NumRooms), the roof type (RoofType), and the price (Price).

import os

os.makedirs(os.path.join('..', 'data'), exist_ok=True)
data_file = os.path.join('..', 'data', 'house_tiny.csv')
with open(data_file, 'w') as f:
    f.write('''NumRooms,RoofType,Price
NA,NA,127500
2,NA,106000
4,Slate,178100
NA,NA,140000''')

Now let’s import pandas and load the dataset with read_csv.

import pandas as pd

data = pd.read_csv(data_file)
print(data)
   NumRooms RoofType   Price
0       NaN      NaN  127500
1       2.0      NaN  106000
2       4.0    Slate  178100
3       NaN      NaN  140000

2.2.2. Data Preparation

In supervised learning, we train models to predict a designated target value, given some set of input values. Our first step in processing the dataset is to separate out columns corresponding to input versus target values. We can select columns either by name or via integer-location based indexing (iloc).

You might have noticed that pandas replaced all CSV entries with value NA with a special NaN (not a number) value. This can also happen whenever an entry is empty, e.g., “3,,,270000”. These are called missing values and they are the “bed bugs” of data science, a persistent menace that you will confront throughout your career. Depending upon the context, missing values might be handled either via imputation or deletion. Imputation replaces missing values with estimates of their values while deletion simply discards either those rows or those columns that contain missing values.

Here are some common imputation heuristics. For categorical input fields, we can treat NaN as a category. Since the RoofType column takes values Slate and NaN, pandas can convert this column into two columns RoofType_Slate and RoofType_nan. A row whose roof type is Slate will set values of RoofType_Slate and RoofType_nan to 1 and 0, respectively. The converse holds for a row with a missing RoofType value.

inputs, targets = data.iloc[:, 0:2], data.iloc[:, 2]
inputs = pd.get_dummies(inputs, dummy_na=True)
print(inputs)
   NumRooms  RoofType_Slate  RoofType_nan
0       NaN           False          True
1       2.0           False          True
2       4.0            True         False
3       NaN           False          True

For missing numerical values, one common heuristic is to replace the NaN entries with the mean value of the corresponding column.

inputs = inputs.fillna(inputs.mean())
print(inputs)
   NumRooms  RoofType_Slate  RoofType_nan
0       3.0           False          True
1       2.0           False          True
2       4.0            True         False
3       3.0           False          True

2.2.3. Conversion to the Tensor Format

Now that all the entries in inputs and targets are numerical, we can load them into a tensor (recall Section 2.1).

import torch

X = torch.tensor(inputs.to_numpy(dtype=float))
y = torch.tensor(targets.to_numpy(dtype=float))
X, y
(tensor([[3., 0., 1.],
         [2., 0., 1.],
         [4., 1., 0.],
         [3., 0., 1.]], dtype=torch.float64),
 tensor([127500., 106000., 178100., 140000.], dtype=torch.float64))

2.2.4. Discussion

You now know how to partition data columns, impute missing variables, and load pandas data into tensors. In Section 5.7, you will pick up some more data processing skills. While this crash course kept things simple, data processing can get hairy. For example, rather than arriving in a single CSV file, our dataset might be spread across multiple files extracted from a relational database. For instance, in an e-commerce application, customer addresses might live in one table and purchase data in another. Moreover, practitioners face myriad data types beyond categorical and numeric, for example, text strings, images, audio data, and point clouds. Oftentimes, advanced tools and efficient algorithms are required in order to prevent data processing from becoming the biggest bottleneck in the machine learning pipeline. These problems will arise when we get to computer vision and natural language processing. Finally, we must pay attention to data quality. Real-world datasets are often plagued by outliers, faulty measurements from sensors, and recording errors, which must be addressed before feeding the data into any model. Data visualization tools such as seaborn, Bokeh, or matplotlib can help you to manually inspect the data and develop intuitions about the type of problems you may need to address.

2.2.5. Exercises

  1. Try loading datasets, e.g., Abalone from the UCI Machine Learning Repository and inspect their properties. What fraction of them has missing values? What fraction of the variables is numerical, categorical, or text?

  2. Try indexing and selecting data columns by name rather than by column number. The pandas documentation on indexing has further details on how to do this.

  3. How large a dataset do you think you could load this way? What might be the limitations? Hint: consider the time to read the data, representation, processing, and memory footprint. Try this out on your laptop. What happens if you try it out on a server?

  4. How would you deal with data that has a very large number of categories? What if the category labels are all unique? Should you include the latter?

  5. What alternatives to pandas can you think of? How about loading NumPy tensors from a file? Check out Pillow, the Python Imaging Library.

22.8. Distributions Open the notebook in SageMaker Studio Lab

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

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

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

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

22.8. Distributions
Open the notebook in SageMaker Studio Lab

Now that we have learned how to work with probability in both the discrete and the continuous setting, let’s get to know some of the common distributions encountered. Depending on the area of machine learning, we may need to be familiar with vastly more of these, or for some areas of deep learning potentially none at all. This is, however, a good basic list to be familiar with. Let’s first import some common libraries.

%matplotlib inline
from math import erf, factorial
import torch
from IPython import display
from d2l import torch as d2l

torch.pi = torch.acos(torch.zeros(1)) * 2  # Define pi in torch

22.8.1. Bernoulli

This is the simplest random variable usually encountered. This random variable encodes a coin flip which comes up \(1\) with probability \(p\) and \(0\) with probability \(1-p\). If we have a random variable \(X\) with this distribution, we will write

(22.8.1)\[X \sim \textrm{Bernoulli}(p).\]

The cumulative distribution function is

(22.8.2)\[\begin{split}F(x) = \begin{cases} 0 & x < 0, \\ 1-p & 0 \le x < 1, \\ 1 & x >= 1 . \end{cases}\end{split}\]

The probability mass function is plotted below.

p = 0.3

d2l.set_figsize()
d2l.plt.stem([0, 1], [1 - p, p], use_line_collection=True)
d2l.plt.xlabel('x')
d2l.plt.ylabel('p.m.f.')
d2l.plt.show()
../_images/output_distributions_c7d568_15_0.svg

Now, let’s plot the cumulative distribution function (22.8.2).

x = torch.arange(-1, 2, 0.01)

def F(x):
    return 0 if x < 0 else 1 if x > 1 else 1 - p

d2l.plot(x, torch.tensor([F(y) for y in x]), 'x', 'c.d.f.')
../_images/output_distributions_c7d568_27_0.svg

If \(X \sim \textrm{Bernoulli}(p)\), then:

  • \(\mu_X = p\),

  • \(\sigma_X^2 = p(1-p)\).

We can sample an array of arbitrary shape from a Bernoulli random variable as follows.

1*(torch.rand(10, 10) < p)
tensor([[0, 1, 0, 0, 1, 0, 0, 0, 0, 0],
        [0, 1, 0, 0, 0, 0, 1, 0, 0, 0],
        [0, 1, 0, 0, 1, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 1, 0, 0, 1, 0, 0, 1],
        [0, 0, 0, 0, 0, 0, 1, 1, 0, 0],
        [1, 1, 0, 0, 1, 1, 1, 1, 1, 0],
        [1, 0, 0, 0, 1, 0, 1, 1, 0, 0],
        [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
        [1, 0, 1, 1, 1, 1, 0, 1, 0, 0]])

22.8.2. Discrete Uniform

The next commonly encountered random variable is a discrete uniform. For our discussion here, we will assume that it is supported on the integers \(\{1, 2, \ldots, n\}\), however any other set of values can be freely chosen. The meaning of the word uniform in this context is that every possible value is equally likely. The probability for each value \(i \in \{1, 2, 3, \ldots, n\}\) is \(p_i = \frac{1}{n}\). We will denote a random variable \(X\) with this distribution as

(22.8.3)\[X \sim U(n).\]

The cumulative distribution function is

(22.8.4)\[\begin{split}F(x) = \begin{cases} 0 & x < 1, \\ \frac{k}{n} & k \le x < k+1 \textrm{ with } 1 \le k < n, \\ 1 & x >= n . \end{cases}\end{split}\]

Let’s first plot the probability mass function.

n = 5

d2l.plt.stem([i+1 for i in range(n)], n*[1 / n], use_line_collection=True)
d2l.plt.xlabel('x')
d2l.plt.ylabel('p.m.f.')
d2l.plt.show()
../_images/output_distributions_c7d568_51_0.svg

Now, let’s plot the cumulative distribution function (22.8.4).

x = torch.arange(-1, 6, 0.01)

def F(x):
    return 0 if x < 1 else 1 if x > n else torch.floor(x) / n

d2l.plot(x, torch.tensor([F(y) for y in x]), 'x', 'c.d.f.')
../_images/output_distributions_c7d568_63_0.svg

If \(X \sim U(n)\), then:

  • \(\mu_X = \frac{1+n}{2}\),

  • \(\sigma_X^2 = \frac{n^2-1}{12}\).

We can sample an array of arbitrary shape from a discrete uniform random variable as follows.

torch.randint(1, n, size=(10, 10))
tensor([[1, 4, 3, 2, 1, 1, 3, 1, 1, 4],
        [4, 1, 1, 4, 4, 1, 4, 3, 2, 4],
        [2, 4, 4, 1, 4, 2, 4, 3, 2, 1],
        [1, 2, 3, 1, 1, 4, 2, 4, 1, 3],
        [1, 2, 4, 1, 4, 3, 3, 2, 2, 1],
        [1, 2, 2, 4, 1, 3, 2, 4, 2, 3],
        [1, 2, 3, 4, 1, 3, 4, 1, 4, 3],
        [3, 1, 1, 4, 4, 1, 3, 1, 1, 2],
        [2, 2, 4, 3, 4, 2, 3, 4, 2, 4],
        [1, 4, 3, 3, 2, 3, 3, 4, 1, 3]])

22.8.3. Continuous Uniform

Next, let’s discuss the continuous uniform distribution. The idea behind this random variable is that if we increase the \(n\) in the discrete uniform distribution, and then scale it to fit within the interval \([a, b]\), we will approach a continuous random variable that just picks an arbitrary value in \([a, b]\) all with equal probability. We will denote this distribution as

(22.8.5)\[X \sim U(a, b).\]

The probability density function is

(22.8.6)\[\begin{split}p(x) = \begin{cases} \frac{1}{b-a} & x \in [a, b], \\ 0 & x \not\in [a, b].\end{cases}\end{split}\]

The cumulative distribution function is

(22.8.7)\[\begin{split}F(x) = \begin{cases} 0 & x < a, \\ \frac{x-a}{b-a} & x \in [a, b], \\ 1 & x >= b . \end{cases}\end{split}\]

Let’s first plot the probability density function (22.8.6).

a, b = 1, 3

x = torch.arange(0, 4, 0.01)
p = (x > a).type(torch.float32)*(x < b).type(torch.float32)/(b-a)
d2l.plot(x, p, 'x', 'p.d.f.')
../_images/output_distributions_c7d568_87_0.svg

Now, let’s plot the cumulative distribution function (22.8.7).

def F(x):
    return 0 if x < a else 1 if x > b else (x - a) / (b - a)

d2l.plot(x, torch.tensor([F(y) for y in x]), 'x', 'c.d.f.')
../_images/output_distributions_c7d568_99_0.svg

If \(X \sim U(a, b)\), then:

  • \(\mu_X = \frac{a+b}{2}\),

  • \(\sigma_X^2 = \frac{(b-a)^2}{12}\).

We can sample an array of arbitrary shape from a uniform random variable as follows. Note that it by default samples from a \(U(0,1)\), so if we want a different range we need to scale it.

(b - a) * torch.rand(10, 10) + a
tensor([[2.4857, 2.2461, 1.6809, 2.7434, 2.7072, 2.6190, 1.4883, 1.2517, 1.3454,
         2.4754],
        [1.0974, 1.5680, 1.8788, 2.8231, 2.1695, 2.6461, 1.4914, 1.4887, 1.3860,
         1.9090],
        [1.3746, 1.7773, 1.2412, 1.1950, 2.7281, 2.8356, 1.2266, 2.4724, 2.4641,
         2.8991],
        [2.4018, 2.6727, 1.0308, 1.1951, 1.9390, 1.6486, 2.8314, 1.1025, 1.3354,
         1.0130],
        [1.1281, 1.8000, 2.3788, 2.6580, 1.6750, 2.2081, 1.2705, 1.0757, 2.3311,
         2.6557],
        [2.9912, 1.2263, 1.8115, 1.5940, 1.9321, 1.6469, 2.2990, 2.1473, 1.8165,
         1.2806],
        [1.1672, 1.1536, 1.9649, 2.1655, 1.7170, 1.0284, 1.3305, 2.1904, 1.4036,
         2.1958],
        [2.5891, 2.5840, 2.2679, 2.0687, 2.9249, 1.6741, 1.2238, 2.4463, 2.2235,
         2.7038],
        [1.8697, 2.4965, 1.5785, 2.7890, 2.3319, 2.1434, 2.3333, 1.0286, 1.9245,
         1.7640],
        [1.2504, 1.7558, 1.4322, 1.5226, 1.3380, 1.1388, 1.8707, 2.2330, 2.3818,
         2.2087]])

22.8.4. Binomial

Let’s make things a little more complex and examine the binomial random variable. This random variable originates from performing a sequence of \(n\) independent experiments, each of which has probability \(p\) of succeeding, and asking how many successes we expect to see.

Let’s express this mathematically. Each experiment is an independent random variable \(X_i\) where we will use \(1\) to encode success, and \(0\) to encode failure. Since each is an independent coin flip which is successful with probability \(p\), we can say that \(X_i \sim \textrm{Bernoulli}(p)\). Then, the binomial random variable is

(22.8.8)\[X = \sum_{i=1}^n X_i.\]

In this case, we will write

(22.8.9)\[X \sim \textrm{Binomial}(n, p).\]

To get the cumulative distribution function, we need to notice that getting exactly \(k\) successes can occur in \(\binom{n}{k} = \frac{n!}{k!(n-k)!}\) ways each of which has a probability of \(p^k(1-p)^{n-k}\) of occurring. Thus the cumulative distribution function is

(22.8.10)\[\begin{split}F(x) = \begin{cases} 0 & x < 0, \\ \sum_{m \le k} \binom{n}{m} p^m(1-p)^{n-m} & k \le x < k+1 \textrm{ with } 0 \le k < n, \\ 1 & x >= n . \end{cases}\end{split}\]

Let’s first plot the probability mass function.

n, p = 10, 0.2

# Compute binomial coefficient
def binom(n, k):
    comb = 1
    for i in range(min(k, n - k)):
        comb = comb * (n - i) // (i + 1)
    return comb

pmf = torch.tensor([p**i * (1-p)**(n - i) * binom(n, i) for i in range(n + 1)])

d2l.plt.stem([i for i in range(n + 1)], pmf, use_line_collection=True)
d2l.plt.xlabel('x')
d2l.plt.ylabel('p.m.f.')
d2l.plt.show()
../_images/output_distributions_c7d568_123_0.svg

Now, let’s plot the cumulative distribution function (22.8.10).

x = torch.arange(-1, 11, 0.01)
cmf = torch.cumsum(pmf, dim=0)

def F(x):
    return 0 if x < 0 else 1 if x > n else cmf[int(x)]

d2l.plot(x, torch.tensor([F(y) for y in x.tolist()]), 'x', 'c.d.f.')
../_images/output_distributions_c7d568_135_0.svg

If \(X \sim \textrm{Binomial}(n, p)\), then:

  • \(\mu_X = np\),

  • \(\sigma_X^2 = np(1-p)\).

This follows from the linearity of expected value over the sum of \(n\) Bernoulli random variables, and the fact that the variance of the sum of independent random variables is the sum of the variances. This can be sampled as follows.

m = torch.distributions.binomial.Binomial(n, p)
m.sample(sample_shape=(10, 10))
tensor([[6., 3., 4., 3., 3., 1., 3., 3., 3., 3.],
        [3., 1., 2., 2., 3., 2., 1., 3., 1., 4.],
        [6., 1., 0., 3., 0., 3., 1., 0., 1., 1.],
        [1., 2., 3., 1., 2., 2., 2., 2., 3., 2.],
        [2., 2., 5., 4., 1., 3., 4., 3., 2., 0.],
        [2., 0., 2., 2., 3., 1., 1., 4., 3., 1.],
        [1., 1., 3., 2., 4., 2., 2., 2., 1., 0.],
        [0., 3., 2., 1., 1., 3., 2., 1., 1., 3.],
        [2., 3., 2., 3., 4., 3., 1., 2., 1., 2.],
        [1., 2., 1., 1., 3., 2., 4., 3., 3., 2.]])

22.8.5. Poisson

Let’s now perform a thought experiment. We are standing at a bus stop and we want to know how many buses will arrive in the next minute. Let’s start by considering \(X^{(1)} \sim \textrm{Bernoulli}(p)\) which is simply the probability that a bus arrives in the one minute window. For bus stops far from an urban center, this might be a pretty good approximation. We may never see more than one bus in a minute.

However, if we are in a busy area, it is possible or even likely that two buses will arrive. We can model this by splitting our random variable into two parts for the first 30 seconds, or the second 30 seconds. In this case we can write

(22.8.11)\[X^{(2)} \sim X^{(2)}_1 + X^{(2)}_2,\]

where \(X^{(2)}\) is the total sum, and \(X^{(2)}_i \sim \textrm{Bernoulli}(p/2)\). The total distribution is then \(X^{(2)} \sim \textrm{Binomial}(2, p/2)\).

Why stop here? Let’s continue to split that minute into \(n\) parts. By the same reasoning as above, we see that

(22.8.12)\[X^{(n)} \sim \textrm{Binomial}(n, p/n).\]

Consider these random variables. By the previous section, we know that (22.8.12) has mean \(\mu_{X^{(n)}} = n(p/n) = p\), and variance \(\sigma_{X^{(n)}}^2 = n(p/n)(1-(p/n)) = p(1-p/n)\). If we take \(n \rightarrow \infty\), we can see that these numbers stabilize to \(\mu_{X^{(\infty)}} = p\), and variance \(\sigma_{X^{(\infty)}}^2 = p\). This indicates that there could be some random variable we can define in this infinite subdivision limit.

This should not come as too much of a surprise, since in the real world we can just count the number of bus arrivals, however it is nice to see that our mathematical model is well defined. This discussion can be made formal as the law of rare events.

Following through this reasoning carefully, we can arrive at the following model. We will say that \(X \sim \textrm{Poisson}(\lambda)\) if it is a random variable which takes the values \(\{0,1,2, \ldots\}\) with probability

(22.8.13)\[p_k = \frac{\lambda^ke^{-\lambda}}{k!}.\]

The value \(\lambda > 0\) is known as the rate (or the shape parameter), and denotes the average number of arrivals we expect in one unit of time.

We may sum this probability mass function to get the cumulative distribution function.

(22.8.14)\[\begin{split}F(x) = \begin{cases} 0 & x < 0, \\ e^{-\lambda}\sum_{m = 0}^k \frac{\lambda^m}{m!} & k \le x < k+1 \textrm{ with } 0 \le k. \end{cases}\end{split}\]

Let’s first plot the probability mass function (22.8.13).

lam = 5.0

xs = [i for i in range(20)]
pmf = torch.tensor([torch.exp(torch.tensor(-lam)) * lam**k
                    / factorial(k) for k in xs])

d2l.plt.stem(xs, pmf, use_line_collection=True)
d2l.plt.xlabel('x')
d2l.plt.ylabel('p.m.f.')
d2l.plt.show()
../_images/output_distributions_c7d568_159_0.svg

Now, let’s plot the cumulative distribution function (22.8.14).

x = torch.arange(-1, 21, 0.01)
cmf = torch.cumsum(pmf, dim=0)
def F(x):
    return 0 if x < 0 else 1 if x > n else cmf[int(x)]

d2l.plot(x, torch.tensor([F(y) for y in x.tolist()]), 'x', 'c.d.f.')
../_images/output_distributions_c7d568_171_0.svg

As we saw above, the means and variances are particularly concise. If \(X \sim \textrm{Poisson}(\lambda)\), then:

  • \(\mu_X = \lambda\),

  • \(\sigma_X^2 = \lambda\).

This can be sampled as follows.

m = torch.distributions.poisson.Poisson(lam)
m.sample((10, 10))
tensor([[ 1.,  4.,  6.,  8.,  4.,  4.,  4.,  7.,  6.,  4.],
        [ 3.,  6.,  7.,  7.,  5.,  7.,  7.,  3.,  5.,  4.],
        [ 4.,  1.,  3.,  3., 10.,  5.,  5.,  3.,  7.,  5.],
        [ 4.,  3.,  4., 10.,  8.,  6.,  4.,  6.,  5.,  5.],
        [ 5., 11.,  1.,  5.,  7.,  5.,  2.,  4.,  3.,  5.],
        [ 6.,  6.,  4.,  4.,  3.,  1.,  5.,  8.,  4.,  5.],
        [ 2.,  9.,  7.,  2.,  6.,  5.,  2.,  8.,  6., 10.],
        [ 1.,  4.,  3.,  7.,  3.,  1.,  7.,  5.,  3.,  6.],
        [ 5.,  4.,  6.,  4.,  9.,  8.,  3.,  3.,  1.,  8.],
        [ 3., 12.,  9., 13.,  2., 14.,  3.,  2.,  0.,  3.]])

22.8.6. Gaussian

Now Let’s try a different, but related experiment. Let’s say we again are performing \(n\) independent \(\textrm{Bernoulli}(p)\) measurements \(X_i\). The distribution of the sum of these is \(X^{(n)} \sim \textrm{Binomial}(n, p)\). Rather than taking a limit as \(n\) increases and \(p\) decreases, Let’s fix \(p\), and then send \(n \rightarrow \infty\). In this case \(\mu_{X^{(n)}} = np \rightarrow \infty\) and \(\sigma_{X^{(n)}}^2 = np(1-p) \rightarrow \infty\), so there is no reason to think this limit should be well defined.

However, not all hope is lost! Let’s just make the mean and variance be well behaved by defining

(22.8.15)\[Y^{(n)} = \frac{X^{(n)} - \mu_{X^{(n)}}}{\sigma_{X^{(n)}}}.\]

This can be seen to have mean zero and variance one, and so it is plausible to believe that it will converge to some limiting distribution. If we plot what these distributions look like, we will become even more convinced that it will work.

p = 0.2
ns = [1, 10, 100, 1000]
d2l.plt.figure(figsize=(10, 3))
for i in range(4):
    n = ns[i]
    pmf = torch.tensor([p**i * (1-p)**(n-i) * binom(n, i)
                        for i in range(n + 1)])
    d2l.plt.subplot(1, 4, i + 1)
    d2l.plt.stem([(i - n*p)/torch.sqrt(torch.tensor(n*p*(1 - p)))
                  for i in range(n + 1)], pmf,
                 use_line_collection=True)
    d2l.plt.xlim([-4, 4])
    d2l.plt.xlabel('x')
    d2l.plt.ylabel('p.m.f.')
    d2l.plt.title("n = {}".format(n))
d2l.plt.show()
../_images/output_distributions_c7d568_195_0.svg

One thing to note: compared to the Poisson case, we are now dividing by the standard deviation which means that we are squeezing the possible outcomes into smaller and smaller areas. This is an indication that our limit will no longer be discrete, but rather continuous.

A derivation of what occurs is beyond the scope of this document, but the central limit theorem states that as \(n \rightarrow \infty\), this will yield the Gaussian Distribution (or sometimes normal distribution). More explicitly, for any \(a, b\):

(22.8.16)\[\lim_{n \rightarrow \infty} P(Y^{(n)} \in [a, b]) = P(\mathcal{N}(0,1) \in [a, b]),\]

where we say a random variable is normally distributed with given mean \(\mu\) and variance \(\sigma^2\), written \(X \sim \mathcal{N}(\mu, \sigma^2)\) if \(X\) has density

(22.8.17)\[p_X(x) = \frac{1}{\sqrt{2\pi\sigma^2}}e^{-\frac{(x-\mu)^2}{2\sigma^2}}.\]

Let’s first plot the probability density function (22.8.17).

mu, sigma = 0, 1

x = torch.arange(-3, 3, 0.01)
p = 1 / torch.sqrt(2 * torch.pi * sigma**2) * torch.exp(
    -(x - mu)**2 / (2 * sigma**2))

d2l.plot(x, p, 'x', 'p.d.f.')
../_images/output_distributions_c7d568_207_0.svg

Now, let’s plot the cumulative distribution function. It is beyond the scope of this appendix, but the Gaussian c.d.f. does not have a closed-form formula in terms of more elementary functions. We will use erf which provides a way to compute this integral numerically.

def phi(x):
    return (1.0 + erf((x - mu) / (sigma * torch.sqrt(torch.tensor(2.))))) / 2.0

d2l.plot(x, torch.tensor([phi(y) for y in x.tolist()]), 'x', 'c.d.f.')
../_images/output_distributions_c7d568_219_0.svg

Keen-eyed readers will recognize some of these terms. Indeed, we encountered this integral in Section 22.5. Indeed we need exactly that computation to see that this \(p_X(x)\) has total area one and is thus a valid density.

Our choice of working with coin flips made computations shorter, but nothing about that choice was fundamental. Indeed, if we take any collection of independent identically distributed random variables \(X_i\), and form

(22.8.18)\[X^{(N)} = \sum_{i=1}^N X_i.\]

Then

(22.8.19)\[\frac{X^{(N)} - \mu_{X^{(N)}}}{\sigma_{X^{(N)}}}\]

will be approximately Gaussian. There are additional requirements needed to make it work, most commonly \(E[X^4] < \infty\), but the philosophy is clear.

The central limit theorem is the reason why the Gaussian is fundamental to probability, statistics, and machine learning. Whenever we can say that something we measured is a sum of many small independent contributions, we can assume that the thing being measured will be close to Gaussian.

There are many more fascinating properties of Gaussians, and we would like to discuss one more here. The Gaussian is what is known as a maximum entropy distribution. We will get into entropy more deeply in Section 22.11, however all we need to know at this point is that it is a measure of randomness. In a rigorous mathematical sense, we can think of the Gaussian as the most random choice of random variable with fixed mean and variance. Thus, if we know that our random variable has some mean and variance, the Gaussian is in a sense the most conservative choice of distribution we can make.

To close the section, let’s recall that if \(X \sim \mathcal{N}(\mu, \sigma^2)\), then:

  • \(\mu_X = \mu\),

  • \(\sigma_X^2 = \sigma^2\).

We can sample from the Gaussian (or standard normal) distribution as shown below.

torch.normal(mu, sigma, size=(10, 10))
tensor([[ 1.3588,  0.0473, -1.5805, -0.0108,  0.4253,  0.7924, -0.6547,  0.7313,
         -0.3038,  1.1935],
        [ 0.0089,  0.8951,  1.0055,  0.0956, -1.1109, -0.6342,  1.6772,  1.0314,
          0.3819, -1.7822],
        [-0.0604, -1.0318,  0.9113,  1.3118, -1.8370, -0.9023,  1.0365,  0.9052,
         -0.6411, -0.8949],
        [-0.1713, -0.2347,  0.0767, -0.6375, -0.4612, -1.6875, -0.1570,  1.0591,
          0.8377,  0.5097],
        [ 0.2762, -0.6213, -0.3422,  0.9449, -0.7544, -0.2150,  1.0240,  1.0253,
         -0.9182,  1.1536],
        [ 0.0614,  0.2758, -0.3610, -1.0577, -0.5513, -0.9158,  0.7539,  0.9204,
         -0.5908,  0.9113],
        [ 1.6190, -0.9213, -0.7944, -2.2621,  0.5826, -1.8287,  1.4097, -0.5744,
         -0.0668,  1.2074],
        [-0.0624,  0.1928,  1.3002,  0.6756,  1.1590,  1.0144,  1.1840, -0.5010,
          0.6026, -0.7722],
        [-2.0148,  0.6958,  0.9940,  0.8477,  1.0957, -0.5253,  0.2353, -0.2663,
          1.2275,  0.5993],
        [ 0.4651, -0.8218, -0.5441, -2.0338, -0.6930, -0.0674, -0.4448, -0.8397,
          0.0360, -0.7089]])

22.8.7. Exponential Family

One shared property for all the distributions listed above is that they all belong to which is known as the exponential family. The exponential family is a set of distributions whose density can be expressed in the following form:

(22.8.20)\[p(\mathbf{x} \mid \boldsymbol{\eta}) = h(\mathbf{x}) \cdot \exp \left( \boldsymbol{\eta}^{\top} \cdot T(\mathbf{x}) - A(\boldsymbol{\eta}) \right)\]

As this definition can be a little subtle, let’s examine it closely.

First, \(h(\mathbf{x})\) is known as the underlying measure or the base measure. This can be viewed as an original choice of measure we are modifying with our exponential weight.

Second, we have the vector \(\boldsymbol{\eta} = (\eta_1, \eta_2, ..., \eta_l) \in \mathbb{R}^l\) called the natural parameters or canonical parameters. These define how the base measure will be modified. The natural parameters enter into the new measure by taking the dot product of these parameters against some function \(T(\cdot)\) of \(\mathbf{x}= (x_1, x_2, ..., x_n) \in \mathbb{R}^n\) and exponentiated. The vector \(T(\mathbf{x})= (T_1(\mathbf{x}), T_2(\mathbf{x}), ..., T_l(\mathbf{x}))\) is called the sufficient statistics for \(\boldsymbol{\eta}\). This name is used since the information represented by \(T(\mathbf{x})\) is sufficient to calculate the probability density and no other information from the sample \(\mathbf{x}\)’s are required.

Third, we have \(A(\boldsymbol{\eta})\), which is referred to as the cumulant function, which ensures that the above distribution (22.8.20) integrates to one, i.e.,

(22.8.21)\[A(\boldsymbol{\eta}) = \log \left[\int h(\mathbf{x}) \cdot \exp \left(\boldsymbol{\eta}^{\top} \cdot T(\mathbf{x}) \right) d\mathbf{x} \right].\]

To be concrete, let’s consider the Gaussian. Assuming that \(\mathbf{x}\) is an univariate variable, we saw that it had a density of

(22.8.22)\[\begin{split}\begin{aligned} p(x \mid \mu, \sigma) &= \frac{1}{\sqrt{2 \pi \sigma^2}} \cdot \exp \left\{ \frac{-(x-\mu)^2}{2 \sigma^2} \right\} \\ &= \frac{1}{\sqrt{2 \pi}} \cdot \exp \left\{ \frac{\mu}{\sigma^2}x -\frac{1}{2 \sigma^2} x^2 - \left( \frac{1}{2 \sigma^2} \mu^2 +\log(\sigma) \right) \right\}. \end{aligned}\end{split}\]

This matches the definition of the exponential family with:

  • underlying measure: \(h(x) = \frac{1}{\sqrt{2 \pi}}\),

  • natural parameters: \(\boldsymbol{\eta} = \begin{bmatrix} \eta_1 \\ \eta_2 \end{bmatrix} = \begin{bmatrix} \frac{\mu}{\sigma^2} \\ \frac{1}{2 \sigma^2} \end{bmatrix}\),

  • sufficient statistics: \(T(x) = \begin{bmatrix}x\\-x^2\end{bmatrix}\), and

  • cumulant function: \(A({\boldsymbol\eta}) = \frac{1}{2 \sigma^2} \mu^2 + \log(\sigma) = \frac{\eta_1^2}{4 \eta_2} - \frac{1}{2}\log(2 \eta_2)\).

It is worth noting that the exact choice of each of above terms is somewhat arbitrary. Indeed, the important feature is that the distribution can be expressed in this form, not the exact form itself.

As we allude to in Section 4.1.2.2, a widely used technique is to assume that the final output \(\mathbf{y}\) follows an exponential family distribution. The exponential family is a common and powerful family of distributions encountered frequently in machine learning.

22.8.8. Summary

  • Bernoulli random variables can be used to model events with a yes/no outcome.

  • Discrete uniform distributions model selects from a finite set of possibilities.

  • Continuous uniform distributions select from an interval.

  • Binomial distributions model a series of Bernoulli random variables, and count the number of successes.

  • Poisson random variables model the arrival of rare events.

  • Gaussian random variables model the result of adding a large number of independent random variables together.

  • All the above distributions belong to exponential family.

22.8.9. Exercises

  1. What is the standard deviation of a random variable that is the difference \(X-Y\) of two independent binomial random variables \(X, Y \sim \textrm{Binomial}(16, 1/2)\).

  2. If we take a Poisson random variable \(X \sim \textrm{Poisson}(\lambda)\) and consider \((X - \lambda)/\sqrt{\lambda}\) as \(\lambda \rightarrow \infty\), we can show that this becomes approximately Gaussian. Why does this make sense?

  3. What is the probability mass function for a sum of two discrete uniform random variables on \(n\) elements?

3.4. Metrics and scoring: quantifying the quality of predictions

Assigned source reading · The scikit-learn developers

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

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

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

Full license and notices
BSD 3-Clause License

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

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

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

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

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

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

3.4. Metrics and scoring: quantifying the quality of predictions

3.4.1. Which scoring function should I use?

Before we take a closer look into the details of the many scores and evaluation metrics, we want to give some guidance, inspired by statistical decision theory, on the choice of scoring functions for supervised learning, see [Gneiting2009]:

  • Which scoring function should I use?

  • Which scoring function is a good one for my task?

In a nutshell, if the scoring function is given, e.g. in a kaggle competition or in a business context, use that one. If you are free to choose, it starts by considering the ultimate goal and application of the prediction. It is useful to distinguish two steps:

  • Predicting

  • Decision making

Predicting: Usually, the response variable \(Y\) is a random variable, in the sense that there is no deterministic function \(Y = g(X)\) of the features \(X\). Instead, there is a probability distribution \(F\) of \(Y\). One can aim to predict the whole distribution, known as probabilistic prediction, or—more the focus of scikit-learn—issue a point prediction (or point forecast) by choosing a property or functional of that distribution \(F\). Typical examples are the mean (expected value), the median or a quantile of the response variable \(Y\) (conditionally on \(X\)).

Once that is settled, use a strictly consistent scoring function for that (target) functional, see [Gneiting2009]. This means using a scoring function that is aligned with measuring the distance between predictions y_pred and the true target functional using observations of \(Y\), i.e. y_true. For classification strictly proper scoring rules, see Wikipedia entry for Scoring rule and [Gneiting2007], coincide with strictly consistent scoring functions. The table further below provides examples. One could say that consistent scoring functions act as truth serum in that they guarantee “that truth telling […] is an optimal strategy in expectation” [Gneiting2014].

Once a strictly consistent scoring function is chosen, it is best used for both: as loss function for model training and as metric/score in model evaluation and model comparison.

Note that for regressors, the prediction is done with predict while for classifiers it is usually predict_proba.

Decision Making: The most common decisions are done on binary classification tasks, where the result of predict_proba is turned into a single outcome, e.g., from the predicted probability of rain a decision is made on how to act (whether to take mitigating measures like an umbrella or not). For classifiers, this is what predict returns. See also Tuning the decision threshold for class prediction. There are many scoring functions which measure different aspects of such a decision, most of them are covered with or derived from the metrics.confusion_matrix.

List of strictly consistent scoring functions: Here, we list some of the most relevant statistical functionals and corresponding strictly consistent scoring functions for tasks in practice. Note that the list is not complete and that there are more of them. For further criteria on how to select a specific one, see [Fissler2022].

functional

scoring or loss function

response y

prediction

Classification

mean

Brier score 1

multi-class

predict_proba

mean

log loss

multi-class

predict_proba

mode

zero-one loss 2

multi-class

predict, categorical

Regression

mean

squared error 3

all reals

predict, all reals

mean

Poisson deviance

non-negative

predict, strictly positive

mean

Gamma deviance

strictly positive

predict, strictly positive

mean

Tweedie deviance

depends on power

predict, depends on power

median

absolute error

all reals

predict, all reals

quantile

pinball loss

all reals

predict, all reals

mode

no consistent one exists

reals

1 The Brier score is just a different name for the squared error in case of classification with one-hot encoded targets.

2 The zero-one loss is only consistent but not strictly consistent for the mode. The zero-one loss is equivalent to one minus the accuracy score, meaning it gives different score values but the same ranking.

3 R² gives the same ranking as squared error.

Fictitious Example: Let’s make the above arguments more tangible. Consider a setting in network reliability engineering, such as maintaining stable internet or Wi-Fi connections. As provider of the network, you have access to the dataset of log entries of network connections containing network load over time and many interesting features. Your goal is to improve the reliability of the connections. In fact, you promise your customers that on at least 99% of all days there are no connection discontinuities larger than 1 minute. Therefore, you are interested in a prediction of the 99% quantile (of longest connection interruption duration per day) in order to know in advance when to add more bandwidth and thereby satisfy your customers. So the target functional is the 99% quantile. From the table above, you choose the pinball loss as scoring function (fair enough, not much choice given), for model training (e.g. HistGradientBoostingRegressor(loss="quantile", quantile=0.99)) as well as model evaluation (mean_pinball_loss(..., alpha=0.99) - we apologize for the different argument names, quantile and alpha) be it in grid search for finding hyperparameters or in comparing to other models like QuantileRegressor(quantile=0.99).

References

[Gneiting2007]

T. Gneiting and A. E. Raftery. Strictly Proper Scoring Rules, Prediction, and Estimation In: Journal of the American Statistical Association 102 (2007), pp. 359– 378. link to pdf

[Gneiting2009] (1,2)

T. Gneiting. Making and Evaluating Point Forecasts Journal of the American Statistical Association 106 (2009): 746 - 762.

[Gneiting2014]

T. Gneiting and M. Katzfuss. Probabilistic Forecasting. In: Annual Review of Statistics and Its Application 1.1 (2014), pp. 125–151.

3.4.2. Scoring API overview

There are 3 different APIs for evaluating the quality of a model’s predictions:

Finally, Dummy estimators are useful to get a baseline value of those metrics for random predictions.

See also

For “pairwise” metrics, between samples and not estimators or predictions, see the Pairwise metrics, Affinities and Kernels section.

3.4.3. The scoring parameter: defining model evaluation rules

Model selection and evaluation tools that internally use cross-validation (such as model_selection.GridSearchCV, model_selection.validation_curve and linear_model.LogisticRegressionCV) take a scoring parameter that controls what metric they apply to the estimators evaluated.

They can be specified in several ways:

  • None: the estimator’s default evaluation criterion (i.e., the metric used in the estimator’s score method) is used.

  • String name: common metrics can be passed via a string name.

  • Callable: more complex metrics can be passed via a custom metric callable (e.g., function).

Some tools do also accept multiple metric evaluation. See Using multiple metric evaluation for details.

3.4.3.1. String name scorers

For the most common use cases, you can designate a scorer object with the scoring parameter via a string name; the table below shows all possible values. All scorer objects follow the convention that higher return values are better than lower return values. Thus metrics which measure the distance between the model and the data, like metrics.mean_squared_error, are available as ‘neg_mean_squared_error’ which return the negated value of the metric.

Scoring string name

Function

Comment

Classification

‘accuracy’

metrics.accuracy_score

‘balanced_accuracy’

metrics.balanced_accuracy_score

‘top_k_accuracy’

metrics.top_k_accuracy_score

‘average_precision’

metrics.average_precision_score

‘neg_brier_score’

metrics.brier_score_loss

requires predict_proba support

‘f1’

metrics.f1_score

for binary targets

‘f1_micro’

metrics.f1_score

micro-averaged

‘f1_macro’

metrics.f1_score

macro-averaged

‘f1_weighted’

metrics.f1_score

weighted average

‘f1_samples’

metrics.f1_score

by multilabel sample

‘neg_log_loss’

metrics.log_loss

requires predict_proba support

‘precision’ etc.

metrics.precision_score

suffixes apply as with ‘f1’

‘recall’ etc.

metrics.recall_score

suffixes apply as with ‘f1’

‘jaccard’ etc.

metrics.jaccard_score

suffixes apply as with ‘f1’

‘roc_auc’

metrics.roc_auc_score

‘roc_auc_ovr’

metrics.roc_auc_score

‘roc_auc_ovo’

metrics.roc_auc_score

‘roc_auc_ovr_weighted’

metrics.roc_auc_score

‘roc_auc_ovo_weighted’

metrics.roc_auc_score

‘d2_log_loss_score’

metrics.d2_log_loss_score

requires predict_proba support

‘d2_brier_score’

metrics.d2_brier_score

requires predict_proba support

Clustering

‘adjusted_mutual_info_score’

metrics.adjusted_mutual_info_score

‘adjusted_rand_score’

metrics.adjusted_rand_score

‘completeness_score’

metrics.completeness_score

‘fowlkes_mallows_score’

metrics.fowlkes_mallows_score

‘homogeneity_score’

metrics.homogeneity_score

‘mutual_info_score’

metrics.mutual_info_score

‘normalized_mutual_info_score’

metrics.normalized_mutual_info_score

‘rand_score’

metrics.rand_score

‘v_measure_score’

metrics.v_measure_score

Regression

‘explained_variance’

metrics.explained_variance_score

‘neg_max_error’

metrics.max_error

‘neg_mean_absolute_error’

metrics.mean_absolute_error

‘neg_mean_squared_error’

metrics.mean_squared_error

‘neg_root_mean_squared_error’

metrics.root_mean_squared_error

‘neg_mean_squared_log_error’

metrics.mean_squared_log_error

‘neg_root_mean_squared_log_error’

metrics.root_mean_squared_log_error

‘neg_median_absolute_error’

metrics.median_absolute_error

‘r2’

metrics.r2_score

‘neg_mean_poisson_deviance’

metrics.mean_poisson_deviance

‘neg_mean_gamma_deviance’

metrics.mean_gamma_deviance

‘neg_mean_absolute_percentage_error’

metrics.mean_absolute_percentage_error

‘d2_absolute_error_score’

metrics.d2_absolute_error_score

Usage examples:

>>> from sklearn import svm, datasets
>>> from sklearn.model_selection import cross_val_score
>>> X, y = datasets.load_iris(return_X_y=True)
>>> clf = svm.SVC(random_state=0)
>>> cross_val_score(clf, X, y, cv=5, scoring='recall_macro')
array([0.96, 0.96, 0.96, 0.93, 1.        ])

Note

If a wrong scoring name is passed, an InvalidParameterError is raised. You can retrieve the names of all available scorers by calling get_scorer_names.

3.4.3.2. Callable scorers

For more complex use cases and more flexibility, you can pass a callable to the scoring parameter. This can be done by:

3.4.3.2.1. Adapting predefined metrics via make_scorer

The following metric functions are not implemented as named scorers, sometimes because they require additional parameters, such as fbeta_score. They cannot be passed to the scoring parameters; instead their callable needs to be passed to make_scorer together with the value of the user-settable parameters.

Function

Parameter

Example usage

Classification

metrics.fbeta_score

beta

make_scorer(fbeta_score, beta=2)

Regression

metrics.mean_tweedie_deviance

power

make_scorer(mean_tweedie_deviance, power=1.5)

metrics.mean_pinball_loss

alpha

make_scorer(mean_pinball_loss, alpha=0.95)

metrics.d2_tweedie_score

power

make_scorer(d2_tweedie_score, power=1.5)

metrics.d2_pinball_score

alpha

make_scorer(d2_pinball_score, alpha=0.95)

One typical use case is to wrap an existing metric function from the library with non-default values for its parameters, such as the beta parameter for the fbeta_score function:

>>> from sklearn.metrics import fbeta_score, make_scorer
>>> ftwo_scorer = make_scorer(fbeta_score, beta=2)
>>> from sklearn.model_selection import GridSearchCV
>>> from sklearn.svm import LinearSVC
>>> grid = GridSearchCV(LinearSVC(), param_grid={'C': [1, 10]},
...                     scoring=ftwo_scorer, cv=5)

The module sklearn.metrics also exposes a set of simple functions measuring a prediction error given ground truth and prediction:

  • functions ending with _score return a value to maximize, the higher the better.

  • functions ending with _error, _loss, or _deviance return a value to minimize, the lower the better. When converting into a scorer object using make_scorer, set the greater_is_better parameter to False (True by default; see the parameter description below).

3.4.3.2.2. Creating a custom scorer object

You can create your own custom scorer object using make_scorer.

Custom scorer objects using make_scorer

You can build a completely custom scorer object from a simple python function using make_scorer, which can take several parameters:

  • the python function you want to use (my_custom_loss_func in the example below)

  • whether the python function returns a score (greater_is_better=True, the default) or a loss (greater_is_better=False). If a loss, the output of the python function is negated by the scorer object, conforming to the cross validation convention that scorers return higher values for better models.

  • for classification metrics only: whether the python function you provided requires continuous decision certainties. If the scoring function only accepts probability estimates (e.g. metrics.log_loss), then one needs to set the parameter response_method="predict_proba". Some scoring functions do not necessarily require probability estimates but rather non-thresholded decision values (e.g. metrics.roc_auc_score). In this case, one can provide a list (e.g., response_method=["decision_function", "predict_proba"]), and scorer will use the first available method, in the order given in the list, to compute the scores.

  • any additional parameters of the scoring function, such as beta or labels.

Here is an example of building custom scorers, and of using the greater_is_better parameter:

>>> import numpy as np
>>> def my_custom_loss_func(y_true, y_pred):
...     diff = np.abs(y_true - y_pred).max()
...     return float(np.log1p(diff))
...
>>> # score will negate the return value of my_custom_loss_func,
>>> # which will be np.log(2), 0.693, given the values for X
>>> # and y defined below.
>>> score = make_scorer(my_custom_loss_func, greater_is_better=False)
>>> X = [[1], [1]]
>>> y = [0, 1]
>>> from sklearn.dummy import DummyClassifier
>>> clf = DummyClassifier(strategy='most_frequent', random_state=0)
>>> clf = clf.fit(X, y)
>>> my_custom_loss_func(y, clf.predict(X))
0.69
>>> score(clf, X, y)
-0.69
Using custom scorers in functions where n_jobs > 1

While defining the custom scoring function alongside the calling function should work out of the box with the default joblib backend (loky), importing it from another module will be a more robust approach and work independently of the joblib backend.

For example, to use n_jobs greater than 1 in the example below, custom_scoring_function function is saved in a user-created module (custom_scorer_module.py) and imported:

>>> from custom_scorer_module import custom_scoring_function
>>> cross_val_score(model,
...  X_train,
...  y_train,
...  scoring=make_scorer(custom_scoring_function, greater_is_better=False),
...  cv=5,
...  n_jobs=-1)

3.4.3.3. Using multiple metric evaluation

Scikit-learn also permits evaluation of multiple metrics in GridSearchCV, RandomizedSearchCV and cross_validate.

There are three ways to specify multiple scoring metrics for the scoring parameter:

  • As an iterable of string metrics:

    >>> scoring = ['accuracy', 'precision']
    
  • As a dict mapping the scorer name to the scoring function:

    >>> from sklearn.metrics import accuracy_score
    >>> from sklearn.metrics import make_scorer
    >>> scoring = {'accuracy': make_scorer(accuracy_score),
    ...            'prec': 'precision'}
    

    Note that the dict values can either be scorer functions or one of the predefined metric strings.

  • As a callable that returns a dictionary of scores:

    >>> from sklearn.model_selection import cross_validate
    >>> from sklearn.metrics import confusion_matrix
    >>> # A sample toy binary classification dataset
    >>> X, y = datasets.make_classification(n_classes=2, random_state=0)
    >>> svm = LinearSVC(random_state=0)
    >>> def confusion_matrix_scorer(clf, X, y):
    ...      y_pred = clf.predict(X)
    ...      cm = confusion_matrix(y, y_pred)
    ...      return {'tn': cm[0, 0], 'fp': cm[0, 1],
    ...              'fn': cm[1, 0], 'tp': cm[1, 1]}
    >>> cv_results = cross_validate(svm, X, y, cv=5,
    ...                             scoring=confusion_matrix_scorer)
    >>> # Getting the test set true positive scores
    >>> print(cv_results['test_tp'])
    [10  9  8  7  8]
    >>> # Getting the test set false negative scores
    >>> print(cv_results['test_fn'])
    [0 1 2 3 2]
    

3.4.4. Classification metrics

The sklearn.metrics module implements several loss, score, and utility functions to measure classification performance. Some metrics might require probability estimates of the positive class or non-thresholded decision values (as returned by decision_function on some classifiers). Most implementations allow each sample to provide a weighted contribution to the overall score, through the sample_weight parameter.

Some of these are restricted to the binary classification case:

precision_recall_curve(y_true, y_score, *[, ...])

Compute precision-recall pairs for different probability thresholds.

roc_curve(y_true, y_score, *[, pos_label, ...])

Compute Receiver operating characteristic (ROC).

class_likelihood_ratios(y_true, y_pred, *[, ...])

Compute binary classification positive and negative likelihood ratios.

det_curve(y_true, y_score[, pos_label, ...])

Compute Detection Error Tradeoff (DET) for different probability thresholds.

confusion_matrix_at_thresholds(y_true, ...)

Calculate binary confusion matrix terms per classification threshold.

Others also work in the multiclass case:

balanced_accuracy_score(y_true, y_pred, *[, ...])

Compute the balanced accuracy.

cohen_kappa_score(y1, y2, *[, labels, ...])

Compute Cohen's kappa: a statistic that measures inter-annotator agreement.

confusion_matrix(y_true, y_pred, *[, ...])

Compute confusion matrix to evaluate the accuracy of a classification.

hinge_loss(y_true, pred_decision, *[, ...])

Average hinge loss (non-regularized).

matthews_corrcoef(y_true, y_pred, *[, ...])

Compute the Matthews correlation coefficient (MCC).

roc_auc_score(y_true, y_score, *[, average, ...])

Compute Area Under the Receiver Operating Characteristic Curve (ROC AUC) from prediction scores.

top_k_accuracy_score(y_true, y_score, *[, ...])

Top-k Accuracy classification score.

Some also work in the multilabel case:

accuracy_score(y_true, y_pred, *[, ...])

Accuracy classification score.

classification_report(y_true, y_pred, *[, ...])

Build a text report showing the main classification metrics.

f1_score(y_true, y_pred, *[, labels, ...])

Compute the F1 score, also known as balanced F-score or F-measure.

fbeta_score(y_true, y_pred, *, beta[, ...])

Compute the F-beta score.

hamming_loss(y_true, y_pred, *[, sample_weight])

Compute the average Hamming loss.

jaccard_score(y_true, y_pred, *[, labels, ...])

Jaccard similarity coefficient score.

log_loss(y_true[, y_proba, normalize, ...])

Log loss, aka logistic loss or cross-entropy loss.

multilabel_confusion_matrix(y_true, y_pred, *)

Compute a confusion matrix for each class or sample.

precision_recall_fscore_support(y_true, ...)

Compute precision, recall, F-measure and support for each class.

precision_score(y_true, y_pred, *[, labels, ...])

Compute the precision.

recall_score(y_true, y_pred, *[, labels, ...])

Compute the recall.

roc_auc_score(y_true, y_score, *[, average, ...])

Compute Area Under the Receiver Operating Characteristic Curve (ROC AUC) from prediction scores.

zero_one_loss(y_true, y_pred, *[, ...])

Zero-one classification loss.

d2_log_loss_score(y_true[, y_proba, ...])

\(D^2\) score function, fraction of log loss explained.

And some work with binary and multilabel (but not multiclass) problems:

average_precision_score(y_true, y_score, *)

Compute average precision (AP) from prediction scores.

In the following sub-sections, we will describe each of those functions, preceded by some notes on common API and metric definition.

3.4.4.1. From binary to multiclass and multilabel

Some metrics are essentially defined for binary classification tasks (e.g. f1_score, roc_auc_score). In these cases, by default only the positive label is evaluated, assuming by default that the positive class is labelled 1 (though this may be configurable through the pos_label parameter).

In extending a binary metric to multiclass or multilabel problems, the data is treated as a collection of binary problems, one for each class. There are then a number of ways to average binary metric calculations across the set of classes, each of which may be useful in some scenario. Where available, you should select among these using the average parameter.

  • "macro" simply calculates the mean of the binary metrics, giving equal weight to each class. In problems where infrequent classes are nonetheless important, macro-averaging may be a means of highlighting their performance. On the other hand, the assumption that all classes are equally important is often untrue, such that macro-averaging will over-emphasize the typically low performance on an infrequent class.

  • "weighted" accounts for class imbalance by computing the average of binary metrics in which each class’s score is weighted by its presence in the true data sample.

  • "micro" gives each sample-class pair an equal contribution to the overall metric (except as a result of sample-weight). Rather than summing the metric per class, this sums the dividends and divisors that make up the per-class metrics to calculate an overall quotient. Micro-averaging may be preferred in multilabel settings, including multiclass classification where a majority class is to be ignored.

  • "samples" applies only to multilabel problems. It does not calculate a per-class measure, instead calculating the metric over the true and predicted classes for each sample in the evaluation data, and returning their (sample_weight-weighted) average.

  • Selecting average=None will return an array with the score for each class.

While multiclass data is provided to the metric, like binary targets, as an array of class labels, multilabel data is specified as an indicator matrix, in which cell [i, j] has value 1 if sample i has label j and value 0 otherwise.

3.4.4.2. Accuracy score

The accuracy_score function computes the accuracy, either the fraction (default) or the count (normalize=False) of correct predictions.

In multilabel classification, the function returns the subset accuracy. If the entire set of predicted labels for a sample strictly match with the true set of labels, then the subset accuracy is 1.0; otherwise it is 0.0.

If \(\hat{y}_i\) is the predicted value of the \(i\)-th sample and \(y_i\) is the corresponding true value, then the fraction of correct predictions over \(n_\text{samples}\) is defined as

\[\texttt{accuracy}(y, \hat{y}) = \frac{1}{n_\text{samples}} \sum_{i=0}^{n_\text{samples}-1} 1(\hat{y}_i = y_i)\]

where \(1(x)\) is the indicator function.

>>> import numpy as np
>>> from sklearn.metrics import accuracy_score
>>> y_pred = [0, 2, 1, 3]
>>> y_true = [0, 1, 2, 3]
>>> accuracy_score(y_true, y_pred)
0.5
>>> accuracy_score(y_true, y_pred, normalize=False)
2.0

In the multilabel case with binary label indicators:

>>> accuracy_score(np.array([[0, 1], [1, 1]]), np.ones((2, 2)))
0.5

Examples

3.4.4.3. Top-k accuracy score

The top_k_accuracy_score function is a generalization of accuracy_score. The difference is that a prediction is considered correct as long as the true label is associated with one of the k highest predicted scores. accuracy_score is the special case of k = 1.

The function covers the binary and multiclass classification cases but not the multilabel case.

If \(\hat{f}_{i,j}\) is the predicted class for the \(i\)-th sample corresponding to the \(j\)-th largest predicted score and \(y_i\) is the corresponding true value, then the fraction of correct predictions over \(n_\text{samples}\) is defined as

\[\texttt{top-k accuracy}(y, \hat{f}) = \frac{1}{n_\text{samples}} \sum_{i=0}^{n_\text{samples}-1} \sum_{j=1}^{k} 1(\hat{f}_{i,j} = y_i)\]

where \(k\) is the number of guesses allowed and \(1(x)\) is the indicator function.

>>> import numpy as np
>>> from sklearn.metrics import top_k_accuracy_score
>>> y_true = np.array([0, 1, 2, 2])
>>> y_score = np.array([[0.5, 0.2, 0.2],
...                     [0.3, 0.4, 0.2],
...                     [0.2, 0.4, 0.3],
...                     [0.7, 0.2, 0.1]])
>>> top_k_accuracy_score(y_true, y_score, k=2)
0.75
>>> # Not normalizing gives the number of "correctly" classified samples
>>> top_k_accuracy_score(y_true, y_score, k=2, normalize=False)
3.0

3.4.4.4. Balanced accuracy score

The balanced_accuracy_score function computes the balanced accuracy, which avoids inflated performance estimates on imbalanced datasets. It is the macro-average of recall scores per class or, equivalently, raw accuracy where each sample is weighted according to the inverse prevalence of its true class. Thus for balanced datasets, the score is equal to accuracy.

In the binary case, balanced accuracy is equal to the arithmetic mean of sensitivity (true positive rate) and specificity (true negative rate), or the area under the ROC curve with binary predictions rather than scores:

\[\texttt{balanced-accuracy} = \frac{1}{2}\left( \frac{TP}{TP + FN} + \frac{TN}{TN + FP}\right )\]

If the classifier performs equally well on either class, this term reduces to the conventional accuracy (i.e., the number of correct predictions divided by the total number of predictions).

In contrast, if the conventional accuracy is above chance only because the classifier takes advantage of an imbalanced test set, then the balanced accuracy, as appropriate, will drop to \(\frac{1}{n\_classes}\).

The score ranges from 0 to 1, or when adjusted=True is used, it is rescaled to the range \(\frac{1}{1 - n\_classes}\) to 1, inclusive, with performance at random scoring 0.

If \(y_i\) is the true value of the \(i\)-th sample, and \(w_i\) is the corresponding sample weight, then we adjust the sample weight to:

\[\hat{w}_i = \frac{w_i}{\sum_j{1(y_j = y_i) w_j}}\]

where \(1(x)\) is the indicator function. Given predicted \(\hat{y}_i\) for sample \(i\), balanced accuracy is defined as:

\[\texttt{balanced-accuracy}(y, \hat{y}, w) = \frac{1}{\sum{\hat{w}_i}} \sum_i 1(\hat{y}_i = y_i) \hat{w}_i\]

With adjusted=True, balanced accuracy reports the relative increase from \(\texttt{balanced-accuracy}(y, \mathbf{0}, w) = \frac{1}{n\_classes}\). In the binary case, this is also known as Youden’s J statistic, or informedness.

Note

The multiclass definition here seems the most reasonable extension of the metric used in binary classification, though there is no certain consensus in the literature:

  • Our definition: [Mosley2013], [Kelleher2015] and [Guyon2015], where [Guyon2015] adopt the adjusted version to ensure that random predictions have a score of \(0\) and perfect predictions have a score of \(1\).

  • Class balanced accuracy as described in [Mosley2013]: the minimum between the precision and the recall for each class is computed. Those values are then averaged over the total number of classes to get the balanced accuracy.

  • Balanced Accuracy as described in [Urbanowicz2015]: the average of sensitivity and specificity is computed for each class and then averaged over total number of classes.

References

[Guyon2015] (1,2)

I. Guyon, K. Bennett, G. Cawley, H.J. Escalante, S. Escalera, T.K. Ho, N. Macià, B. Ray, M. Saeed, A.R. Statnikov, E. Viegas, Design of the 2015 ChaLearn AutoML Challenge, IJCNN 2015.

[Mosley2013] (1,2)

L. Mosley, A balanced approach to the multi-class imbalance problem, IJCV 2010.

3.4.4.5. Cohen’s kappa

The function cohen_kappa_score computes Cohen’s kappa statistic. This measure is intended to compare labelings by different human annotators, not a classifier versus a ground truth.

The kappa score is a number between -1 and 1. Scores above .8 are generally considered good agreement; zero or lower means no agreement (practically random labels).

Kappa scores can be computed for binary or multiclass problems, but not for multilabel problems (except by manually computing a per-label score) and not for more than two annotators.

>>> from sklearn.metrics import cohen_kappa_score
>>> labeling1 = [2, 0, 2, 2, 0, 1]
>>> labeling2 = [0, 0, 2, 2, 0, 2]
>>> cohen_kappa_score(labeling1, labeling2)
0.4285714285714286

3.4.4.6. Confusion matrix

The confusion_matrix function evaluates classification accuracy by computing the confusion matrix with each row corresponding to the true class (Wikipedia and other references may use different convention for axes).

By definition, entry \(i, j\) in a confusion matrix is the number of observations actually in group \(i\), but predicted to be in group \(j\). Here is an example:

>>> from sklearn.metrics import confusion_matrix
>>> y_true = [2, 0, 2, 2, 0, 1]
>>> y_pred = [0, 0, 2, 2, 0, 2]
>>> confusion_matrix(y_true, y_pred)
array([[2, 0, 0],
       [0, 0, 1],
       [1, 0, 2]])

ConfusionMatrixDisplay can be used to visually represent a confusion matrix as shown in the Evaluate the performance of a classifier with Confusion Matrix example, which creates the following figure:

../_images/sphx_glr_plot_confusion_matrix_001.png

The parameter normalize allows to report ratios instead of counts. The confusion matrix can be normalized in 3 different ways: 'pred', 'true', and 'all' which will divide the counts by the sum of each columns, rows, or the entire matrix, respectively.

>>> y_true = [0, 0, 0, 1, 1, 1, 1, 1]
>>> y_pred = [0, 1, 0, 1, 0, 1, 0, 1]
>>> confusion_matrix(y_true, y_pred, normalize='all')
array([[0.25 , 0.125],
       [0.25 , 0.375]])

For binary problems, we can get counts of true negatives, false positives, false negatives and true positives as follows:

>>> y_true = [0, 0, 0, 1, 1, 1, 1, 1]
>>> y_pred = [0, 1, 0, 1, 0, 1, 0, 1]
>>> tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel().tolist()
>>> tn, fp, fn, tp
(2, 1, 2, 3)

With confusion_matrix_at_thresholds we can get true negatives, false positives, false negatives and true positives for different thresholds:

>>> from sklearn.metrics import confusion_matrix_at_thresholds
>>> y_true = np.array([0., 0., 1., 1.])
>>> y_score = np.array([0.1, 0.4, 0.35, 0.8])
>>> tns, fps, fns, tps, thresholds = confusion_matrix_at_thresholds(y_true, y_score)
>>> tns
array([2., 1., 1., 0.])
>>> fps
array([0., 1., 1., 2.])
>>> fns
array([1., 1., 0., 0.])
>>> tps
array([1., 1., 2., 2.])
>>> thresholds
array([0.8, 0.4, 0.35, 0.1])

Note that the thresholds consist of distinct y_score values, in decreasing order.

Examples

3.4.4.7. Classification report

The classification_report function builds a text report showing the main classification metrics. Here is a small example with custom target_names and inferred labels:

>>> from sklearn.metrics import classification_report
>>> y_true = [0, 1, 2, 2, 0]
>>> y_pred = [0, 0, 2, 1, 0]
>>> target_names = ['class 0', 'class 1', 'class 2']
>>> print(classification_report(y_true, y_pred, target_names=target_names))
              precision    recall  f1-score   support

     class 0       0.67      1.00      0.80         2
     class 1       0.00      0.00      0.00         1
     class 2       1.00      0.50      0.67         2

    accuracy                           0.60         5
   macro avg       0.56      0.50      0.49         5
weighted avg       0.67      0.60      0.59         5

Examples

3.4.4.8. Hamming loss

The hamming_loss computes the average Hamming loss or Hamming distance between two sets of samples.

If \(\hat{y}_{i,j}\) is the predicted value for the \(j\)-th label of a given sample \(i\), \(y_{i,j}\) is the corresponding true value, \(n_\text{samples}\) is the number of samples and \(n_\text{labels}\) is the number of labels, then the Hamming loss \(L_{Hamming}\) is defined as:

\[L_{Hamming}(y, \hat{y}) = \frac{1}{n_\text{samples} * n_\text{labels}} \sum_{i=0}^{n_\text{samples}-1} \sum_{j=0}^{n_\text{labels} - 1} 1(\hat{y}_{i,j} \not= y_{i,j})\]

where \(1(x)\) is the indicator function.

The equation above does not hold true in the case of multiclass classification. Please refer to the note below for more information.

>>> from sklearn.metrics import hamming_loss
>>> y_pred = [1, 2, 3, 4]
>>> y_true = [2, 2, 3, 4]
>>> hamming_loss(y_true, y_pred)
0.25

In the multilabel case with binary label indicators:

>>> hamming_loss(np.array([[0, 1], [1, 1]]), np.zeros((2, 2)))
0.75

Note

In multiclass classification, the Hamming loss corresponds to the Hamming distance between y_true and y_pred which is similar to the Zero one loss function. However, while zero-one loss penalizes prediction sets that do not strictly match true sets, the Hamming loss penalizes individual labels. Thus the Hamming loss, upper bounded by the zero-one loss, is always between zero and one, inclusive; and predicting a proper subset or superset of the true labels will give a Hamming loss between zero and one, exclusive.

3.4.4.9. Precision, recall and F-measures

Intuitively, precision is the ability of the classifier not to label as positive a sample that is negative, and recall is the ability of the classifier to find all the positive samples.

The F-measure (\(F_\beta\) and \(F_1\) measures) can be interpreted as a weighted harmonic mean of the precision and recall. A \(F_\beta\) measure reaches its best value at 1 and its worst score at 0. With \(\beta = 1\), \(F_\beta\) and \(F_1\) are equivalent, and the recall and the precision are equally important.

The precision_recall_curve computes a precision-recall curve from the ground truth label and a score given by the classifier by varying a decision threshold.

The average_precision_score function computes the average precision (AP) from prediction scores. The value is between 0 and 1 and higher is better. AP is defined as

\[\text{AP} = \sum_n (R_n - R_{n-1}) P_n\]

where \(P_n\) and \(R_n\) are the precision and recall at the nth threshold. With random predictions, the AP is the fraction of positive samples.

References [Manning2008] and [Everingham2010] present alternative variants of AP that interpolate the precision-recall curve. Currently, average_precision_score does not implement any interpolated variant. References [Davis2006] and [Flach2015] describe why a linear interpolation of points on the precision-recall curve provides an overly-optimistic measure of classifier performance. This linear interpolation is used when computing area under the curve with the trapezoidal rule in auc. [Chen2024] benchmarks different interpolation strategies to demonstrate the effects.

Several functions allow you to analyze the precision, recall and F-measures score:

average_precision_score(y_true, y_score, *)

Compute average precision (AP) from prediction scores.

f1_score(y_true, y_pred, *[, labels, ...])

Compute the F1 score, also known as balanced F-score or F-measure.

fbeta_score(y_true, y_pred, *, beta[, ...])

Compute the F-beta score.

precision_recall_curve(y_true, y_score, *[, ...])

Compute precision-recall pairs for different probability thresholds.

precision_recall_fscore_support(y_true, ...)

Compute precision, recall, F-measure and support for each class.

precision_score(y_true, y_pred, *[, labels, ...])

Compute the precision.

recall_score(y_true, y_pred, *[, labels, ...])

Compute the recall.

Note that the precision_recall_curve function is restricted to the binary case. The average_precision_score function supports multiclass and multilabel formats by computing each class score in a One-vs-the-rest (OvR) fashion and averaging them or not depending of its average argument value.

The PrecisionRecallDisplay.from_estimator and PrecisionRecallDisplay.from_predictions functions will plot the precision-recall curve as follows.

../_images/sphx_glr_plot_precision_recall_001.png

Examples

References

[Manning2008]

C.D. Manning, P. Raghavan, H. Schütze, Introduction to Information Retrieval, 2008.

[Everingham2010]

M. Everingham, L. Van Gool, C.K.I. Williams, J. Winn, A. Zisserman, The Pascal Visual Object Classes (VOC) Challenge, IJCV 2010.

[Chen2024]

W. Chen, C. Miao, Z. Zhang, C.S. Fung, R. Wang, Y. Chen, Y. Qian, L. Cheng, K.Y. Yip, S.K Tsui, Q. Cao, Commonly used software tools produce conflicting and overly-optimistic AUPRC values, Genome Biology 2024.

3.4.4.9.1. Binary classification

In a binary classification task, the terms ‘’positive’’ and ‘’negative’’ refer to the classifier’s prediction, and the terms ‘’true’’ and ‘’false’’ refer to whether that prediction corresponds to the external judgment (sometimes known as the ‘’observation’’). Given these definitions, we can formulate the following table:

Actual class (observation)

Predicted class (expectation)

tp (true positive) Correct result

fp (false positive) Unexpected result

fn (false negative) Missing result

tn (true negative) Correct absence of result

In this context, we can define the notions of precision and recall:

\[\text{precision} = \frac{\text{tp}}{\text{tp} + \text{fp}},\]
\[\text{recall} = \frac{\text{tp}}{\text{tp} + \text{fn}},\]

(Sometimes recall is also called ‘’sensitivity’’)

F-measure is the weighted harmonic mean of precision and recall, with precision’s contribution to the mean weighted by some parameter \(\beta\):

\[F_\beta = (1 + \beta^2) \frac{\text{precision} \times \text{recall}}{\beta^2 \text{precision} + \text{recall}}\]

To avoid division by zero when precision and recall are zero, Scikit-Learn calculates F-measure with this otherwise-equivalent formula:

\[F_\beta = \frac{(1 + \beta^2) \text{tp}}{(1 + \beta^2) \text{tp} + \text{fp} + \beta^2 \text{fn}}\]

Note that this formula is still undefined when there are no true positives, false positives, or false negatives. By default, F-1 for a set of exclusively true negatives is calculated as 0, however this behavior can be changed using the zero_division parameter. Here are some small examples in binary classification:

>>> from sklearn import metrics
>>> y_pred = [0, 1, 0, 0]
>>> y_true = [0, 1, 0, 1]
>>> metrics.precision_score(y_true, y_pred)
1.0
>>> metrics.recall_score(y_true, y_pred)
0.5
>>> metrics.f1_score(y_true, y_pred)
0.66
>>> metrics.fbeta_score(y_true, y_pred, beta=0.5)
0.83
>>> metrics.fbeta_score(y_true, y_pred, beta=1)
0.66
>>> metrics.fbeta_score(y_true, y_pred, beta=2)
0.55
>>> metrics.precision_recall_fscore_support(y_true, y_pred, beta=0.5)
(array([0.66, 1.        ]), array([1. , 0.5]), array([0.71, 0.83]), array([2, 2]))


>>> import numpy as np
>>> from sklearn.metrics import precision_recall_curve
>>> from sklearn.metrics import average_precision_score
>>> y_true = np.array([0, 0, 1, 1])
>>> y_scores = np.array([0.1, 0.4, 0.35, 0.8])
>>> precision, recall, threshold = precision_recall_curve(y_true, y_scores)
>>> precision
array([0.5       , 0.66, 0.5       , 1.        , 1.        ])
>>> recall
array([1. , 1. , 0.5, 0.5, 0. ])
>>> threshold
array([0.1 , 0.35, 0.4 , 0.8 ])
>>> average_precision_score(y_true, y_scores)
0.83

3.4.4.9.2. Multiclass and multilabel classification

In a multiclass and multilabel classification task, the notions of precision, recall, and F-measures can be applied to each label independently. There are a few ways to combine results across labels, specified by the average argument to the average_precision_score, f1_score, fbeta_score, precision_recall_fscore_support, precision_score and recall_score functions, as described above.

Note the following behaviors when averaging:

  • If all labels are included, “micro”-averaging in a multiclass setting will produce precision, recall and \(F\) that are all identical to accuracy.

  • “weighted” averaging may produce an F-score that is not between precision and recall.

  • “macro” averaging for F-measures is calculated as the arithmetic mean over per-label/class F-measures, not the harmonic mean over the arithmetic precision and recall means. Both calculations can be seen in the literature but are not equivalent, see [OB2019] for details.

To make this more explicit, consider the following notation:

  • \(y\) the set of true \((sample, label)\) pairs

  • \(\hat{y}\) the set of predicted \((sample, label)\) pairs

  • \(L\) the set of labels

  • \(S\) the set of samples

  • \(y_s\) the subset of \(y\) with sample \(s\), i.e. \(y_s := \left\{(s', l) \in y | s' = s\right\}\)

  • \(y_l\) the subset of \(y\) with label \(l\)

  • similarly, \(\hat{y}_s\) and \(\hat{y}_l\) are subsets of \(\hat{y}\)

  • \(P(A, B) := \frac{\left| A \cap B \right|}{\left|B\right|}\) for some sets \(A\) and \(B\)

  • \(R(A, B) := \frac{\left| A \cap B \right|}{\left|A\right|}\) (Conventions vary on handling \(A = \emptyset\); this implementation uses \(R(A, B):=0\), and similar for \(P\).)

  • \(F_\beta(A, B) := \left(1 + \beta^2\right) \frac{P(A, B) \times R(A, B)}{\beta^2 P(A, B) + R(A, B)}\)

Then the metrics are defined as:

average

Precision

Recall

F_beta

"micro"

\(P(y, \hat{y})\)

\(R(y, \hat{y})\)

\(F_\beta(y, \hat{y})\)

"samples"

\(\frac{1}{\left|S\right|} \sum_{s \in S} P(y_s, \hat{y}_s)\)

\(\frac{1}{\left|S\right|} \sum_{s \in S} R(y_s, \hat{y}_s)\)

\(\frac{1}{\left|S\right|} \sum_{s \in S} F_\beta(y_s, \hat{y}_s)\)

"macro"

\(\frac{1}{\left|L\right|} \sum_{l \in L} P(y_l, \hat{y}_l)\)

\(\frac{1}{\left|L\right|} \sum_{l \in L} R(y_l, \hat{y}_l)\)

\(\frac{1}{\left|L\right|} \sum_{l \in L} F_\beta(y_l, \hat{y}_l)\)

"weighted"

\(\frac{1}{\sum_{l \in L} \left|y_l\right|} \sum_{l \in L} \left|y_l\right| P(y_l, \hat{y}_l)\)

\(\frac{1}{\sum_{l \in L} \left|y_l\right|} \sum_{l \in L} \left|y_l\right| R(y_l, \hat{y}_l)\)

\(\frac{1}{\sum_{l \in L} \left|y_l\right|} \sum_{l \in L} \left|y_l\right| F_\beta(y_l, \hat{y}_l)\)

None

\(\langle P(y_l, \hat{y}_l) | l \in L \rangle\)

\(\langle R(y_l, \hat{y}_l) | l \in L \rangle\)

\(\langle F_\beta(y_l, \hat{y}_l) | l \in L \rangle\)

>>> from sklearn import metrics
>>> y_true = [0, 1, 2, 0, 1, 2]
>>> y_pred = [0, 2, 1, 0, 0, 1]
>>> metrics.precision_score(y_true, y_pred, average='macro')
0.22
>>> metrics.recall_score(y_true, y_pred, average='micro')
0.33
>>> metrics.f1_score(y_true, y_pred, average='weighted')
0.267
>>> metrics.fbeta_score(y_true, y_pred, average='macro', beta=0.5)
0.238
>>> metrics.precision_recall_fscore_support(y_true, y_pred, beta=0.5, average=None)
(array([0.667, 0., 0.]), array([1., 0., 0.]), array([0.714, 0., 0.]), array([2, 2, 2]))

For multiclass classification with a “negative class”, it is possible to exclude some labels:

>>> metrics.recall_score(y_true, y_pred, labels=[1, 2], average='micro')
... # excluding 0, no labels were correctly recalled
0.0

Similarly, labels not present in the data sample may be accounted for in macro-averaging.

>>> metrics.precision_score(y_true, y_pred, labels=[0, 1, 2, 3], average='macro')
0.166

References

3.4.4.10. Jaccard similarity coefficient score

The jaccard_score function computes the average of Jaccard similarity coefficients, also called the Jaccard index, between pairs of label sets.

The Jaccard similarity coefficient with a ground truth label set \(y\) and predicted label set \(\hat{y}\), is defined as

\[J(y, \hat{y}) = \frac{|y \cap \hat{y}|}{|y \cup \hat{y}|}.\]

The jaccard_score (like precision_recall_fscore_support) applies natively to binary targets. By computing it set-wise it can be extended to apply to multilabel and multiclass through the use of average (see above).

In the binary case:

>>> import numpy as np
>>> from sklearn.metrics import jaccard_score
>>> y_true = np.array([[0, 1, 1],
...                    [1, 1, 0]])
>>> y_pred = np.array([[1, 1, 1],
...                    [1, 0, 0]])
>>> jaccard_score(y_true[0], y_pred[0])
0.6666

In the 2D comparison case (e.g. image similarity):

>>> jaccard_score(y_true, y_pred, average="micro")
0.6

In the multilabel case with binary label indicators:

>>> jaccard_score(y_true, y_pred, average='samples')
0.5833
>>> jaccard_score(y_true, y_pred, average='macro')
0.6666
>>> jaccard_score(y_true, y_pred, average=None)
array([0.5, 0.5, 1. ])

Multiclass problems are binarized and treated like the corresponding multilabel problem:

>>> y_pred = [0, 2, 1, 2]
>>> y_true = [0, 1, 2, 2]
>>> jaccard_score(y_true, y_pred, average=None)
array([1. , 0. , 0.33])
>>> jaccard_score(y_true, y_pred, average='macro')
0.44
>>> jaccard_score(y_true, y_pred, average='micro')
0.33

3.4.4.11. Hinge loss

The hinge_loss function computes the average distance between the model and the data using hinge loss, a one-sided metric that considers only prediction errors. (Hinge loss is used in maximal margin classifiers such as support vector machines.)

If the true label \(y_i\) of a binary classification task is encoded as \(y_i=\left\{-1, +1\right\}\) for every sample \(i\); and \(w_i\) is the corresponding predicted decision (an array of shape (n_samples,) as output by the decision_function method), then the hinge loss is defined as:

\[L_\text{Hinge}(y, w) = \frac{1}{n_\text{samples}} \sum_{i=0}^{n_\text{samples}-1} \max\left\{1 - w_i y_i, 0\right\}\]

If there are more than two labels, hinge_loss uses a multiclass variant due to Crammer & Singer. Here is the paper describing it.

In this case the predicted decision is an array of shape (n_samples, n_labels). If \(w_{i, y_i}\) is the predicted decision for the true label \(y_i\) of the \(i\)-th sample; and \(\hat{w}_{i, y_i} = \max\left\{w_{i, y_j}~|~y_j \ne y_i \right\}\) is the maximum of the predicted decisions for all the other labels, then the multi-class hinge loss is defined by:

\[L_\text{Hinge}(y, w) = \frac{1}{n_\text{samples}} \sum_{i=0}^{n_\text{samples}-1} \max\left\{1 + \hat{w}_{i, y_i} - w_{i, y_i}, 0\right\}\]

Here is a small example demonstrating the use of the hinge_loss function with an svm classifier in a binary class problem:

>>> from sklearn import svm
>>> from sklearn.metrics import hinge_loss
>>> X = [[0], [1]]
>>> y = [-1, 1]
>>> est = svm.LinearSVC(random_state=0)
>>> est.fit(X, y)
LinearSVC(random_state=0)
>>> pred_decision = est.decision_function([[-2], [3], [0.5]])
>>> pred_decision
array([-2.18,  2.36,  0.09])
>>> hinge_loss([-1, 1, 1], pred_decision)
0.3

Here is an example demonstrating the use of the hinge_loss function with an svm classifier in a multiclass problem:

>>> X = np.array([[0], [1], [2], [3]])
>>> Y = np.array([0, 1, 2, 3])
>>> labels = np.array([0, 1, 2, 3])
>>> est = svm.LinearSVC()
>>> est.fit(X, Y)
LinearSVC()
>>> pred_decision = est.decision_function([[-1], [2], [3]])
>>> y_true = [0, 2, 3]
>>> hinge_loss(y_true, pred_decision, labels=labels)
0.56

3.4.4.12. Log loss

Log loss, also called logistic regression loss or cross-entropy loss, is defined on probability estimates. It is commonly used in (multinomial) logistic regression and neural networks, as well as in some variants of expectation-maximization, and can be used to evaluate the probability outputs (predict_proba) of a classifier instead of its discrete predictions.

For binary classification with a true label \(y \in \{0,1\}\) and a probability estimate \(\hat{p} \approx \operatorname{Pr}(y = 1)\), the log loss per sample is the negative log-likelihood of the classifier given the true label:

\[L_{\log}(y, \hat{p}) = -\log \operatorname{Pr}(y|\hat{p}) = -(y \log (\hat{p}) + (1 - y) \log (1 - \hat{p}))\]

This extends to the multiclass case as follows. Let the true labels for a set of samples be encoded as a 1-of-K binary indicator matrix \(Y\), i.e., \(y_{i,k} = 1\) if sample \(i\) has label \(k\) taken from a set of \(K\) labels. Let \(\hat{P}\) be a matrix of probability estimates, with elements \(\hat{p}_{i,k} \approx \operatorname{Pr}(y_{i,k} = 1)\). Then the log loss of the whole set is

\[L_{\log}(Y, \hat{P}) = -\log \operatorname{Pr}(Y|\hat{P}) = - \frac{1}{N} \sum_{i=0}^{N-1} \sum_{k=0}^{K-1} y_{i,k} \log \hat{p}_{i,k}\]

To see how this generalizes the binary log loss given above, note that in the binary case, \(\hat{p}_{i,0} = 1 - \hat{p}_{i,1}\) and \(y_{i,0} = 1 - y_{i,1}\), so expanding the inner sum over \(y_{i,k} \in \{0,1\}\) gives the binary log loss.

The log_loss function computes log loss given a list of ground-truth labels and a probability matrix, as returned by an estimator’s predict_proba method.

>>> from sklearn.metrics import log_loss
>>> y_true = [0, 0, 1, 1]
>>> y_proba = [[.9, .1], [.8, .2], [.3, .7], [.01, .99]]
>>> log_loss(y_true, y_proba)
0.1738

The first [.9, .1] in y_proba denotes 90% probability that the first sample has label 0. The log loss is non-negative.

3.4.4.13. Matthews correlation coefficient

The matthews_corrcoef function computes the Matthew’s correlation coefficient (MCC) for binary classes. Quoting Wikipedia:

“The Matthews correlation coefficient is used in machine learning as a measure of the quality of binary (two-class) classifications. It takes into account true and false positives and negatives and is generally regarded as a balanced measure which can be used even if the classes are of very different sizes. The MCC is in essence a correlation coefficient value between -1 and +1. A coefficient of +1 represents a perfect prediction, 0 an average random prediction and -1 an inverse prediction. The statistic is also known as the phi coefficient.”

In the binary (two-class) case, \(tp\), \(tn\), \(fp\) and \(fn\) are respectively the number of true positives, true negatives, false positives and false negatives, the MCC is defined as

\[MCC = \frac{tp \times tn - fp \times fn}{\sqrt{(tp + fp)(tp + fn)(tn + fp)(tn + fn)}}.\]

In the multiclass case, the Matthews correlation coefficient can be defined in terms of a confusion_matrix \(C\) for \(K\) classes. To simplify the definition consider the following intermediate variables:

  • \(t_k=\sum_{i}^{K} C_{ik}\) the number of times class \(k\) truly occurred,

  • \(p_k=\sum_{i}^{K} C_{ki}\) the number of times class \(k\) was predicted,

  • \(c=\sum_{k}^{K} C_{kk}\) the total number of samples correctly predicted,

  • \(s=\sum_{i}^{K} \sum_{j}^{K} C_{ij}\) the total number of samples.

Then the multiclass MCC is defined as:

\[MCC = \frac{ c \times s - \sum_{k}^{K} p_k \times t_k }{\sqrt{ (s^2 - \sum_{k}^{K} p_k^2) \times (s^2 - \sum_{k}^{K} t_k^2) }}\]

When there are more than two labels, the value of the MCC will no longer range between -1 and +1. Instead the minimum value will be somewhere between -1 and 0 depending on the number and distribution of ground truth labels. The maximum value is always +1. For additional information, see [WikipediaMCC2021].

Here is a small example illustrating the usage of the matthews_corrcoef function:

>>> from sklearn.metrics import matthews_corrcoef
>>> y_true = [+1, +1, +1, -1]
>>> y_pred = [+1, -1, +1, +1]
>>> matthews_corrcoef(y_true, y_pred)
-0.33

References

[WikipediaMCC2021]

Wikipedia contributors. Phi coefficient. Wikipedia, The Free Encyclopedia. April 21, 2021, 12:21 CEST. Available at: https://en.wikipedia.org/wiki/Phi_coefficient Accessed April 21, 2021.

3.4.4.14. Multi-label confusion matrix

The multilabel_confusion_matrix function computes class-wise (default) or sample-wise (samplewise=True) multilabel confusion matrix to evaluate the accuracy of a classification. multilabel_confusion_matrix also treats multiclass data as if it were multilabel, as this is a transformation commonly applied to evaluate multiclass problems with binary classification metrics (such as precision, recall, etc.).

When calculating class-wise multilabel confusion matrix \(C\), the count of true negatives for class \(i\) is \(C_{i,0,0}\), false negatives is \(C_{i,1,0}\), true positives is \(C_{i,1,1}\) and false positives is \(C_{i,0,1}\).

Here is an example demonstrating the use of the multilabel_confusion_matrix function with multilabel indicator matrix input:

>>> import numpy as np
>>> from sklearn.metrics import multilabel_confusion_matrix
>>> y_true = np.array([[1, 0, 1],
...                    [0, 1, 0]])
>>> y_pred = np.array([[1, 0, 0],
...                    [0, 1, 1]])
>>> multilabel_confusion_matrix(y_true, y_pred)
array([[[1, 0],
        [0, 1]],

       [[1, 0],
        [0, 1]],

       [[0, 1],
        [1, 0]]])

Or a confusion matrix can be constructed for each sample’s labels:

>>> multilabel_confusion_matrix(y_true, y_pred, samplewise=True)
array([[[1, 0],
        [1, 1]],

       [[1, 1],
        [0, 1]]])

Here is an example demonstrating the use of the multilabel_confusion_matrix function with multiclass input:

>>> y_true = ["cat", "ant", "cat", "cat", "ant", "bird"]
>>> y_pred = ["ant", "ant", "cat", "cat", "ant", "cat"]
>>> multilabel_confusion_matrix(y_true, y_pred,
...                             labels=["ant", "bird", "cat"])
array([[[3, 1],
        [0, 2]],

       [[5, 0],
        [1, 0]],

       [[2, 1],
        [1, 2]]])

Here are some examples demonstrating the use of the multilabel_confusion_matrix function to calculate recall (or sensitivity), specificity, fall out and miss rate for each class in a problem with multilabel indicator matrix input.

Calculating recall (also called the true positive rate or the sensitivity) for each class:

>>> y_true = np.array([[0, 0, 1],
...                    [0, 1, 0],
...                    [1, 1, 0]])
>>> y_pred = np.array([[0, 1, 0],
...                    [0, 0, 1],
...                    [1, 1, 0]])
>>> mcm = multilabel_confusion_matrix(y_true, y_pred)
>>> tn = mcm[:, 0, 0]
>>> tp = mcm[:, 1, 1]
>>> fn = mcm[:, 1, 0]
>>> fp = mcm[:, 0, 1]
>>> tp / (tp + fn)
array([1. , 0.5, 0. ])

Calculating specificity (also called the true negative rate) for each class:

>>> tn / (tn + fp)
array([1. , 0. , 0.5])

Calculating fall out (also called the false positive rate) for each class:

>>> fp / (fp + tn)
array([0. , 1. , 0.5])

Calculating miss rate (also called the false negative rate) for each class:

>>> fn / (fn + tp)
array([0. , 0.5, 1. ])

3.4.4.15. Receiver operating characteristic (ROC)

The function roc_curve computes the receiver operating characteristic curve, or ROC curve. Quoting Wikipedia :

“A receiver operating characteristic (ROC), or simply ROC curve, is a graphical plot which illustrates the performance of a binary classifier system as its discrimination threshold is varied. It is created by plotting the fraction of true positives out of the positives (TPR = true positive rate) vs. the fraction of false positives out of the negatives (FPR = false positive rate), at various threshold settings. TPR is also known as sensitivity, and FPR is one minus the specificity or true negative rate.”

This function requires the true binary value and the target scores, which can either be probability estimates of the positive class or non-thresholded decision values (as returned by decision_function on some classifiers). Here is a small example of how to use the roc_curve function:

>>> import numpy as np
>>> from sklearn.metrics import roc_curve
>>> y = np.array([1, 1, 2, 2])
>>> scores = np.array([0.1, 0.4, 0.35, 0.8])
>>> fpr, tpr, thresholds = roc_curve(y, scores, pos_label=2)
>>> fpr
array([0. , 0. , 0.5, 0.5, 1. ])
>>> tpr
array([0. , 0.5, 0.5, 1. , 1. ])
>>> thresholds
array([ inf, 0.8 , 0.4 , 0.35, 0.1 ])

Compared to metrics such as the subset accuracy, the Hamming loss, or the F1 score, ROC doesn’t require optimizing a threshold for each label.

The roc_auc_score function, denoted by ROC-AUC or AUROC, computes the area under the ROC curve. By doing so, the curve information is summarized in one number.

The following figure shows the ROC curve and ROC-AUC score for a classifier aimed to distinguish the virginica flower from the rest of the species in the Iris plants dataset:

../_images/sphx_glr_plot_roc_001.png

For more information see the Wikipedia article on AUC.

3.4.4.15.1. Binary case

In the binary case, you can either provide the probability estimates, using the classifier.predict_proba() method, or the non-thresholded decision values given by the classifier.decision_function() method. In the case of providing the probability estimates, the probability of the class with the “greater label” should be provided. The “greater label” corresponds to classifier.classes_[1] and thus classifier.predict_proba(X)[:, 1]. Therefore, the y_score parameter is of size (n_samples,).

>>> from sklearn.datasets import load_breast_cancer
>>> from sklearn.linear_model import LogisticRegression
>>> from sklearn.metrics import roc_auc_score
>>> X, y = load_breast_cancer(return_X_y=True)
>>> clf = LogisticRegression().fit(X, y)
>>> clf.classes_
array([0, 1])

We can use the probability estimates corresponding to clf.classes_[1].

>>> y_score = clf.predict_proba(X)[:, 1]
>>> roc_auc_score(y, y_score)
0.99

Otherwise, we can use the non-thresholded decision values

>>> roc_auc_score(y, clf.decision_function(X))
0.99

3.4.4.15.2. Multi-class case

The roc_auc_score function can also be used in multi-class classification. Two averaging strategies are currently supported: the one-vs-one algorithm computes the average of the pairwise ROC AUC scores, and the one-vs-rest algorithm computes the average of the ROC AUC scores for each class against all other classes. In both cases, the predicted labels are provided in an array with values from 0 to n_classes, and the scores correspond to the probability estimates that a sample belongs to a particular class. The OvO and OvR algorithms support weighting uniformly (average='macro') and by prevalence (average='weighted').

One-vs-one Algorithm

Computes the average AUC of all possible pairwise combinations of classes. [HT2001] defines a multiclass AUC metric weighted uniformly:

\[\frac{1}{c(c-1)}\sum_{j=1}^{c}\sum_{k > j}^c (\text{AUC}(j | k) + \text{AUC}(k | j))\]

where \(c\) is the number of classes and \(\text{AUC}(j | k)\) is the AUC with class \(j\) as the positive class and class \(k\) as the negative class. In general, \(\text{AUC}(j | k) \neq \text{AUC}(k | j)\) in the multiclass case. This algorithm is used by setting the keyword argument multiclass to 'ovo' and average to 'macro'.

The [HT2001] multiclass AUC metric can be extended to be weighted by the prevalence:

\[\frac{1}{c(c-1)}\sum_{j=1}^{c}\sum_{k > j}^c p(j \cup k)( \text{AUC}(j | k) + \text{AUC}(k | j))\]

where \(c\) is the number of classes. This algorithm is used by setting the keyword argument multiclass to 'ovo' and average to 'weighted'. The 'weighted' option returns a prevalence-weighted average as described in [FC2009].

One-vs-rest Algorithm

Computes the AUC of each class against the rest [PD2000]. The algorithm is functionally the same as the multilabel case. To enable this algorithm set the keyword argument multiclass to 'ovr'. Additionally to 'macro' [F2006] and 'weighted' [F2001] averaging, OvR supports 'micro' averaging.

In applications where a high false positive rate is not tolerable the parameter max_fpr of roc_auc_score can be used to summarize the ROC curve up to the given limit.

The following figure shows the micro-averaged ROC curve and its corresponding ROC-AUC score for a classifier aimed to distinguish the different species in the Iris plants dataset:

../_images/sphx_glr_plot_roc_002.png

3.4.4.15.3. Multi-label case

In multi-label classification, the roc_auc_score function is extended by averaging over the labels as above. In this case, you should provide a y_score of shape (n_samples, n_classes). Thus, when using the probability estimates, one needs to select the probability of the class with the greater label for each output.

>>> from sklearn.datasets import make_multilabel_classification
>>> from sklearn.multioutput import MultiOutputClassifier
>>> X, y = make_multilabel_classification(random_state=0)
>>> inner_clf = LogisticRegression(random_state=0)
>>> clf = MultiOutputClassifier(inner_clf).fit(X, y)
>>> y_score = np.transpose([y_pred[:, 1] for y_pred in clf.predict_proba(X)])
>>> roc_auc_score(y, y_score, average=None)
array([0.828, 0.851, 0.94, 0.87, 0.95])

And the decision values do not require such processing.

>>> from sklearn.linear_model import RidgeClassifierCV
>>> clf = RidgeClassifierCV().fit(X, y)
>>> y_score = clf.decision_function(X)
>>> roc_auc_score(y, y_score, average=None)
array([0.82, 0.85, 0.93, 0.87, 0.94])

Examples

References

[HT2001] (1,2)

Hand, D.J. and Till, R.J., (2001). A simple generalisation of the area under the ROC curve for multiple class classification problems. Machine learning, 45(2), pp. 171-186.

[FC2009]

Ferri, Cèsar & Hernandez-Orallo, Jose & Modroiu, R. (2009). An Experimental Comparison of Performance Measures for Classification. Pattern Recognition Letters. 30. 27-38.

[PD2000]

Provost, F., Domingos, P. (2000). Well-trained PETs: Improving probability estimation trees (Section 6.2), CeDER Working Paper #IS-00-04, Stern School of Business, New York University.

[F2006]

Fawcett, T., 2006. An introduction to ROC analysis. Pattern Recognition Letters, 27(8), pp. 861-874.

[F2001]

Fawcett, T., 2001. Using rule sets to maximize ROC performance In Data Mining, 2001. Proceedings IEEE International Conference, pp. 131-138.

3.4.4.16. Detection error tradeoff (DET)

The function det_curve computes the detection error tradeoff curve (DET) curve [WikipediaDET2017]. Quoting Wikipedia:

“A detection error tradeoff (DET) graph is a graphical plot of error rates for binary classification systems, plotting false reject rate vs. false accept rate. The x- and y-axes are scaled non-linearly by their standard normal deviates (or just by logarithmic transformation), yielding tradeoff curves that are more linear than ROC curves, and use most of the image area to highlight the differences of importance in the critical operating region.”

DET curves are a variation of receiver operating characteristic (ROC) curves where False Negative Rate is plotted on the y-axis instead of True Positive Rate. DET curves are commonly plotted in normal deviate scale by transformation with \(\phi^{-1}\) (with \(\phi\) being the cumulative distribution function). The resulting performance curves explicitly visualize the tradeoff of error types for given classification algorithms. See [Martin1997] for examples and further motivation.

This figure compares the ROC and DET curves of two example classifiers on the same classification task:

../_images/sphx_glr_plot_det_001.png
Properties
  • DET curves form a linear curve in normal deviate scale if the detection scores are normally (or close-to normally) distributed. It was shown by [Navratil2007] that the reverse is not necessarily true and even more general distributions are able to produce linear DET curves.

  • The normal deviate scale transformation spreads out the points such that a comparatively larger space of plot is occupied. Therefore curves with similar classification performance might be easier to distinguish on a DET plot.

  • With False Negative Rate being “inverse” to True Positive Rate the point of perfection for DET curves is the origin (in contrast to the top left corner for ROC curves).

Applications and limitations

DET curves are intuitive to read and hence allow quick visual assessment of a classifier’s performance. Additionally DET curves can be consulted for threshold analysis and operating point selection. This is particularly helpful if a comparison of error types is required.

On the other hand DET curves do not provide their metric as a single number. Therefore for either automated evaluation or comparison to other classification tasks metrics like the derived area under ROC curve might be better suited.

Examples

References

[WikipediaDET2017]

Wikipedia contributors. Detection error tradeoff. Wikipedia, The Free Encyclopedia. September 4, 2017, 23:33 UTC. Available at: https://en.wikipedia.org/w/index.php?title=Detection_error_tradeoff&oldid=798982054. Accessed February 19, 2018.

[Martin1997]

A. Martin, G. Doddington, T. Kamm, M. Ordowski, and M. Przybocki, The DET Curve in Assessment of Detection Task Performance, NIST 1997.

[Navratil2007]

J. Navratil and D. Klusacek, “On Linear DETs”, 2007 IEEE International Conference on Acoustics, Speech and Signal Processing - ICASSP ‘07, Honolulu, HI, 2007, pp. IV-229-IV-232.

3.4.4.17. Zero one loss

The zero_one_loss function computes the sum or the average of the 0-1 classification loss (\(L_{0-1}\)) over \(n_{\text{samples}}\). By default, the function normalizes over the sample. To get the sum of the \(L_{0-1}\), set normalize to False.

In multilabel classification, the zero_one_loss scores a subset as one if its labels strictly match the predictions, and as a zero if there are any errors. By default, the function returns the percentage of imperfectly predicted subsets. To get the count of such subsets instead, set normalize to False.

If \(\hat{y}_i\) is the predicted value of the \(i\)-th sample and \(y_i\) is the corresponding true value, then the 0-1 loss \(L_{0-1}\) is defined as:

\[L_{0-1}(y, \hat{y}) = \frac{1}{n_\text{samples}} \sum_{i=0}^{n_\text{samples}-1} 1(\hat{y}_i \not= y_i)\]

where \(1(x)\) is the indicator function. The zero-one loss can also be computed as \(\text{zero-one loss} = 1 - \text{accuracy}\).

>>> from sklearn.metrics import zero_one_loss
>>> y_pred = [1, 2, 3, 4]
>>> y_true = [2, 2, 3, 4]
>>> zero_one_loss(y_true, y_pred)
0.25
>>> zero_one_loss(y_true, y_pred, normalize=False)
1.0

In the multilabel case with binary label indicators, where the first label set [0,1] has an error:

>>> zero_one_loss(np.array([[0, 1], [1, 1]]), np.ones((2, 2)))
0.5

>>> zero_one_loss(np.array([[0, 1], [1, 1]]), np.ones((2, 2)),  normalize=False)
1.0

Examples

3.4.4.18. Brier score loss

The brier_score_loss function computes the Brier score for binary and multiclass probabilistic predictions and is equivalent to the mean squared error. Quoting Wikipedia:

“The Brier score is a strictly proper scoring rule that measures the accuracy of probabilistic predictions. […] [It] is applicable to tasks in which predictions must assign probabilities to a set of mutually exclusive discrete outcomes or classes.”

Let the true labels for a set of \(N\) data points be encoded as a 1-of-K binary indicator matrix \(Y\), i.e., \(y_{i,k} = 1\) if sample \(i\) has label \(k\) taken from a set of \(K\) labels. Let \(\hat{P}\) be a matrix of probability estimates with elements \(\hat{p}_{i,k} \approx \operatorname{Pr}(y_{i,k} = 1)\). Following the original definition by [Brier1950], the Brier score is given by:

\[BS(Y, \hat{P}) = \frac{1}{N}\sum_{i=0}^{N-1}\sum_{k=0}^{K-1}(y_{i,k} - \hat{p}_{i,k})^{2}\]

The Brier score lies in the interval \([0, 2]\) and the lower the value the better the probability estimates are (the mean squared difference is smaller). Actually, the Brier score is a strictly proper scoring rule, meaning that it achieves the best score only when the estimated probabilities equal the true ones.

Note that in the binary case, the Brier score is usually divided by two and ranges between \([0,1]\). For binary targets \(y_i \in \{0, 1\}\) and probability estimates \(\hat{p}_i \approx \operatorname{Pr}(y_i = 1)\) for the positive class, the Brier score is then equal to:

\[BS(y, \hat{p}) = \frac{1}{N} \sum_{i=0}^{N - 1}(y_i - \hat{p}_i)^2\]

The brier_score_loss function computes the Brier score given the ground-truth labels and predicted probabilities, as returned by an estimator’s predict_proba method. The scale_by_half parameter controls which of the two above definitions to follow.

>>> import numpy as np
>>> from sklearn.metrics import brier_score_loss
>>> y_true = np.array([0, 1, 1, 0])
>>> y_true_categorical = np.array(["spam", "ham", "ham", "spam"])
>>> y_prob = np.array([0.1, 0.9, 0.8, 0.4])
>>> brier_score_loss(y_true, y_prob)
0.055
>>> brier_score_loss(y_true, 1 - y_prob, pos_label=0)
0.055
>>> brier_score_loss(y_true_categorical, y_prob, pos_label="ham")
0.055
>>> brier_score_loss(
...    ["eggs", "ham", "spam"],
...    [[0.8, 0.1, 0.1], [0.2, 0.7, 0.1], [0.2, 0.2, 0.6]],
...    labels=["eggs", "ham", "spam"],
... )
0.146

Note

As a strictly proper scoring rules for probabilistic predictions, the Brier score assesses calibration (reliability) and discriminative power (resolution) of a model, as well as the randomness of the data (uncertainty) at the same time. This follows from the well-known Brier score decomposition of Murphy [Murphy1973]. As it is not clear which term dominates, the score is of limited use for assessing calibration alone (unless one computes each term of the decomposition). A lower Brier loss, for instance, does not necessarily mean a better calibrated model, it could also mean a worse calibrated model with much more discriminatory power, e.g. using many more features.

Examples

References

[Brier1950]

G. Brier (1950). “Verification of forecasts expressed in terms of probability”. Monthly Weather Review 78(1), 1-3

[Murphy1973]

Allan H. Murphy (1973). “A New Vector Partition of the Probability Score” Journal of Applied Meteorology and Climatology, 12(4), 595-600

3.4.4.19. Class likelihood ratios

The class_likelihood_ratios function computes the positive and negative likelihood ratios \(LR_\pm\) for binary classes, which can be interpreted as the ratio of post-test to pre-test odds as explained below. As a consequence, this metric is invariant w.r.t. the class prevalence (the number of samples in the positive class divided by the total number of samples) and can be extrapolated between populations regardless of any possible class imbalance.

The \(LR_\pm\) metrics are therefore very useful in settings where the data available to learn and evaluate a classifier is a study population with nearly balanced classes, such as a case-control study, while the target application, i.e. the general population, has very low prevalence.

The positive likelihood ratio \(LR_+\) is the probability of a classifier to correctly predict that a sample belongs to the positive class divided by the probability of predicting the positive class for a sample belonging to the negative class:

\[LR_+ = \frac{\text{PR}(P+|T+)}{\text{PR}(P+|T-)}.\]

The notation here refers to predicted (\(P\)) or true (\(T\)) label and the sign \(+\) and \(-\) refer to the positive and negative class, respectively, e.g. \(P+\) stands for “predicted positive”.

Analogously, the negative likelihood ratio \(LR_-\) is the probability of a sample of the positive class being classified as belonging to the negative class divided by the probability of a sample of the negative class being correctly classified:

\[LR_- = \frac{\text{PR}(P-|T+)}{\text{PR}(P-|T-)}.\]

For classifiers above chance \(LR_+\) above 1 higher is better, while \(LR_-\) ranges from 0 to 1 and lower is better. Values of \(LR_\pm\approx 1\) correspond to chance level.

Notice that probabilities differ from counts, for instance \(\operatorname{PR}(P+|T+)\) is not equal to the number of true positive counts tp (see the wikipedia page for the actual formulas).

Examples

Interpretation across varying prevalence

Both class likelihood ratios are interpretable in terms of an odds ratio (pre-test and post-tests):

\[\text{post-test odds} = \text{Likelihood ratio} \times \text{pre-test odds}.\]

Odds are in general related to probabilities via

\[\text{odds} = \frac{\text{probability}}{1 - \text{probability}},\]

or equivalently

\[\text{probability} = \frac{\text{odds}}{1 + \text{odds}}.\]

On a given population, the pre-test probability is given by the prevalence. By converting odds to probabilities, the likelihood ratios can be translated into a probability of truly belonging to either class before and after a classifier prediction:

\[\text{post-test odds} = \text{Likelihood ratio} \times \frac{\text{pre-test probability}}{1 - \text{pre-test probability}},\]
\[\text{post-test probability} = \frac{\text{post-test odds}}{1 + \text{post-test odds}}.\]
Mathematical divergences

The positive likelihood ratio (LR+) is undefined when \(fp=0\), meaning the classifier does not misclassify any negative labels as positives. This condition can either indicate a perfect identification of all the negative cases or, if there are also no true positive predictions (\(tp=0\)), that the classifier does not predict the positive class at all. In the first case, LR+ can be interpreted as np.inf, in the second case (for instance, with highly imbalanced data) it can be interpreted as np.nan.

The negative likelihood ratio (LR-) is undefined when \(tn=0\). Such divergence is invalid, as \(LR_- > 1.0\) would indicate an increase in the odds of a sample belonging to the positive class after being classified as negative, as if the act of classifying caused the positive condition. This includes the case of a DummyClassifier that always predicts the positive class (i.e. when \(tn=fn=0\)).

Both class likelihood ratios (LR+ and LR-) are undefined when \(tp=fn=0\), which means that no samples of the positive class were present in the test set. This can happen when cross-validating on highly imbalanced data and also leads to a division by zero.

If a division by zero occurs and raise_warning is set to True (default), class_likelihood_ratios raises an UndefinedMetricWarning and returns np.nan by default to avoid pollution when averaging over cross-validation folds. Users can set return values in case of a division by zero with the replace_undefined_by param.

For a worked-out demonstration of the class_likelihood_ratios function, see the example below.

References

3.4.4.20. D² score for classification

The D² score computes the fraction of deviance explained. It is a generalization of R², where the squared error is generalized and replaced by a classification deviance of choice \(\text{dev}(y, \hat{y})\) (e.g., Log loss, Brier score,). D² is a form of a skill score. It is calculated as

\[D^2(y, \hat{y}) = 1 - \frac{\text{dev}(y, \hat{y})}{\text{dev}(y, y_{\text{null}})} \,.\]

Where \(y_{\text{null}}\) is the optimal prediction of an intercept-only model (e.g., the per-class proportion of y_true in the case of the Log loss and Brier score).

Like R², the best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts \(y_{\text{null}}\), disregarding the input features, would get a D² score of 0.0.

D2 log loss score

The d2_log_loss_score function implements the special case of D² with the log loss, see Log loss, i.e.:

\[\text{dev}(y, \hat{y}) = \text{log_loss}(y, \hat{y}).\]

Here are some usage examples of the d2_log_loss_score function:

>>> from sklearn.metrics import d2_log_loss_score
>>> y_true = [1, 1, 2, 3]
>>> y_proba = [
...    [0.5, 0.25, 0.25],
...    [0.5, 0.25, 0.25],
...    [0.5, 0.25, 0.25],
...    [0.5, 0.25, 0.25],
... ]
>>> d2_log_loss_score(y_true, y_proba)
0.0
>>> y_true = [1, 2, 3]
>>> y_proba = [
...     [0.98, 0.01, 0.01],
...     [0.01, 0.98, 0.01],
...     [0.01, 0.01, 0.98],
... ]
>>> d2_log_loss_score(y_true, y_proba)
0.981
>>> y_true = [1, 2, 3]
>>> y_proba = [
...     [0.1, 0.6, 0.3],
...     [0.1, 0.6, 0.3],
...     [0.4, 0.5, 0.1],
... ]
>>> d2_log_loss_score(y_true, y_proba)
-0.552
D2 Brier score

The d2_brier_score function implements the special case of D² with the Brier score, see Brier score loss, i.e.:

\[\text{dev}(y, \hat{y}) = \text{brier_score_loss}(y, \hat{y}).\]

This is also referred to as the Brier Skill Score (BSS) and scaled Brier score.

Here are some usage examples of the d2_brier_score function:

>>> from sklearn.metrics import d2_brier_score
>>> y_true = [1, 1, 2, 3]
>>> y_pred = [
...    [0.5, 0.25, 0.25],
...    [0.5, 0.25, 0.25],
...    [0.5, 0.25, 0.25],
...    [0.5, 0.25, 0.25],
... ]
>>> d2_brier_score(y_true, y_pred)
0.0
>>> y_true = [1, 2, 3]
>>> y_pred = [
...    [0.98, 0.01, 0.01],
...    [0.01, 0.98, 0.01],
...    [0.01, 0.01, 0.98],
... ]
>>> d2_brier_score(y_true, y_pred)
0.9991
>>> y_true = [1, 2, 3]
>>> y_pred = [
...    [0.1, 0.6, 0.3],
...    [0.1, 0.6, 0.3],
...    [0.4, 0.5, 0.1],
... ]
>>> d2_brier_score(y_true, y_pred)
-0.370...

3.4.5. Multilabel ranking metrics

In multilabel learning, each sample can have any number of ground truth labels associated with it. The goal is to give high scores and better rank to the ground truth labels.

3.4.5.1. Coverage error

The coverage_error function computes the average number of labels that have to be included in the final prediction such that all true labels are predicted. This is useful if you want to know how many top-scored-labels you have to predict in average without missing any true one. The best value of this metric is thus the average number of true labels.

Note

Our implementation’s score is 1 greater than the one given in Tsoumakas et al., 2010. This extends it to handle the degenerate case in which an instance has 0 true labels.

Formally, given a binary indicator matrix of the ground truth labels \(y \in \left\{0, 1\right\}^{n_\text{samples} \times n_\text{labels}}\) and the score associated with each label \(\hat{f} \in \mathbb{R}^{n_\text{samples} \times n_\text{labels}}\), the coverage is defined as

\[coverage(y, \hat{f}) = \frac{1}{n_{\text{samples}}} \sum_{i=0}^{n_{\text{samples}} - 1} \max_{j:y_{ij} = 1} \text{rank}_{ij}\]

with \(\text{rank}_{ij} = \left|\left\{k: \hat{f}_{ik} \geq \hat{f}_{ij} \right\}\right|\). Given the rank definition, ties in y_scores are broken by giving the maximal rank that would have been assigned to all tied values.

Here is a small example of usage of this function:

>>> import numpy as np
>>> from sklearn.metrics import coverage_error
>>> y_true = np.array([[1, 0, 0], [0, 0, 1]])
>>> y_score = np.array([[0.75, 0.5, 1], [1, 0.2, 0.1]])
>>> coverage_error(y_true, y_score)
2.5

3.4.5.2. Label ranking average precision

The label_ranking_average_precision_score function implements label ranking average precision (LRAP). This metric is linked to the average_precision_score function, but is based on the notion of label ranking instead of precision and recall.

Label ranking average precision (LRAP) averages over the samples the answer to the following question: for each ground truth label, what fraction of higher-ranked labels were true labels? This performance measure will be higher if you are able to give better rank to the labels associated with each sample. The obtained score is always strictly greater than 0, and the best value is 1. If there is exactly one relevant label per sample, label ranking average precision is equivalent to the mean reciprocal rank.

Formally, given a binary indicator matrix of the ground truth labels \(y \in \left\{0, 1\right\}^{n_\text{samples} \times n_\text{labels}}\) and the score associated with each label \(\hat{f} \in \mathbb{R}^{n_\text{samples} \times n_\text{labels}}\), the average precision is defined as

\[LRAP(y, \hat{f}) = \frac{1}{n_{\text{samples}}} \sum_{i=0}^{n_{\text{samples}} - 1} \frac{1}{||y_i||_0} \sum_{j:y_{ij} = 1} \frac{|\mathcal{L}_{ij}|}{\text{rank}_{ij}}\]

where \(\mathcal{L}_{ij} = \left\{k: y_{ik} = 1, \hat{f}_{ik} \geq \hat{f}_{ij} \right\}\), \(\text{rank}_{ij} = \left|\left\{k: \hat{f}_{ik} \geq \hat{f}_{ij} \right\}\right|\), \(|\cdot|\) computes the cardinality of the set (i.e., the number of elements in the set), and \(||\cdot||_0\) is the \(\ell_0\) “norm” (which computes the number of nonzero elements in a vector).

Here is a small example of usage of this function:

>>> import numpy as np
>>> from sklearn.metrics import label_ranking_average_precision_score
>>> y_true = np.array([[1, 0, 0], [0, 0, 1]])
>>> y_score = np.array([[0.75, 0.5, 1], [1, 0.2, 0.1]])
>>> label_ranking_average_precision_score(y_true, y_score)
0.416

3.4.5.3. Ranking loss

The label_ranking_loss function computes the ranking loss which averages over the samples the number of label pairs that are incorrectly ordered, i.e. true labels have a lower score than false labels, weighted by the inverse of the number of ordered pairs of false and true labels. The lowest achievable ranking loss is zero.

Formally, given a binary indicator matrix of the ground truth labels \(y \in \left\{0, 1\right\}^{n_\text{samples} \times n_\text{labels}}\) and the score associated with each label \(\hat{f} \in \mathbb{R}^{n_\text{samples} \times n_\text{labels}}\), the ranking loss is defined as

\[ranking\_loss(y, \hat{f}) = \frac{1}{n_{\text{samples}}} \sum_{i=0}^{n_{\text{samples}} - 1} \frac{1}{||y_i||_0(n_\text{labels} - ||y_i||_0)} \left|\left\{(k, l): \hat{f}_{ik} \leq \hat{f}_{il}, y_{ik} = 1, y_{il} = 0 \right\}\right|\]

where \(|\cdot|\) computes the cardinality of the set (i.e., the number of elements in the set) and \(||\cdot||_0\) is the \(\ell_0\) “norm” (which computes the number of nonzero elements in a vector).

Here is a small example of usage of this function:

>>> import numpy as np
>>> from sklearn.metrics import label_ranking_loss
>>> y_true = np.array([[1, 0, 0], [0, 0, 1]])
>>> y_score = np.array([[0.75, 0.5, 1], [1, 0.2, 0.1]])
>>> label_ranking_loss(y_true, y_score)
0.75
>>> # With the following prediction, we have perfect and minimal loss
>>> y_score = np.array([[1.0, 0.1, 0.2], [0.1, 0.2, 0.9]])
>>> label_ranking_loss(y_true, y_score)
0.0
References
  • Tsoumakas, G., Katakis, I., & Vlahavas, I. (2010). Mining multi-label data. In Data mining and knowledge discovery handbook (pp. 667-685). Springer US.

3.4.5.4. Normalized Discounted Cumulative Gain

Discounted Cumulative Gain (DCG) and Normalized Discounted Cumulative Gain (NDCG) are ranking metrics implemented in dcg_score and ndcg_score ; they compare a predicted order to ground-truth scores, such as the relevance of answers to a query.

From the Wikipedia page for Discounted Cumulative Gain:

“Discounted cumulative gain (DCG) is a measure of ranking quality. In information retrieval, it is often used to measure effectiveness of web search engine algorithms or related applications. Using a graded relevance scale of documents in a search-engine result set, DCG measures the usefulness, or gain, of a document based on its position in the result list. The gain is accumulated from the top of the result list to the bottom, with the gain of each result discounted at lower ranks.”

DCG orders the true targets (e.g. relevance of query answers) in the predicted order, then multiplies them by a logarithmic decay and sums the result. The sum can be truncated after the first \(K\) results, in which case we call it DCG@K. NDCG, or NDCG@K is DCG divided by the DCG obtained by a perfect prediction, so that it is always between 0 and 1. Usually, NDCG is preferred to DCG.

Compared with the ranking loss, NDCG can take into account relevance scores, rather than a ground-truth ranking. So if the ground-truth consists only of an ordering, the ranking loss should be preferred; if the ground-truth consists of actual usefulness scores (e.g. 0 for irrelevant, 1 for relevant, 2 for very relevant), NDCG can be used.

For one sample, given the vector of continuous ground-truth values for each target \(y \in \mathbb{R}^{M}\), where \(M\) is the number of outputs, and the prediction \(\hat{y}\), which induces the ranking function \(f\), the DCG score is

\[\sum_{r=1}^{\min(K, M)}\frac{y_{f(r)}}{\log(1 + r)}\]

and the NDCG score is the DCG score divided by the DCG score obtained for \(y\).

References
  • Wikipedia entry for Discounted Cumulative Gain

  • Jarvelin, K., & Kekalainen, J. (2002). Cumulated gain-based evaluation of IR techniques. ACM Transactions on Information Systems (TOIS), 20(4), 422-446.

  • Wang, Y., Wang, L., Li, Y., He, D., Chen, W., & Liu, T. Y. (2013, May). A theoretical analysis of NDCG ranking measures. In Proceedings of the 26th Annual Conference on Learning Theory (COLT 2013)

  • McSherry, F., & Najork, M. (2008, March). Computing information retrieval performance measures efficiently in the presence of tied scores. In European conference on information retrieval (pp. 414-421). Springer, Berlin, Heidelberg.

3.4.6. Regression metrics

The sklearn.metrics module implements several loss, score, and utility functions to measure regression performance. Some of those have been enhanced to handle the multioutput case: mean_squared_error, mean_absolute_error, r2_score, explained_variance_score, mean_pinball_loss, d2_pinball_score and d2_absolute_error_score.

These functions have a multioutput keyword argument which specifies the way the scores or losses for each individual target should be averaged. The default is 'uniform_average', which specifies a uniformly weighted mean over outputs. If an ndarray of shape (n_outputs,) is passed, then its entries are interpreted as weights and an according weighted average is returned. If multioutput is 'raw_values', then all unaltered individual scores or losses will be returned in an array of shape (n_outputs,).

The r2_score and explained_variance_score accept an additional value 'variance_weighted' for the multioutput parameter. This option leads to a weighting of each individual score by the variance of the corresponding target variable. This setting quantifies the globally captured unscaled variance. If the target variables are of different scale, then this score puts more importance on explaining the higher variance variables.

3.4.6.1. R² score, the coefficient of determination

The r2_score function computes the coefficient of determination, usually denoted as \(R^2\).

It represents the proportion of variance (of y) that has been explained by the independent variables in the model. It provides an indication of goodness of fit and therefore a measure of how well unseen samples are likely to be predicted by the model, through the proportion of explained variance.

As such variance is dataset dependent, \(R^2\) may not be meaningfully comparable across different datasets. Best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected (average) value of y, disregarding the input features, would get an \(R^2\) score of 0.0.

Note: when the prediction residuals have zero mean, the \(R^2\) score and the Explained variance score are identical.

If \(\hat{y}_i\) is the predicted value of the \(i\)-th sample and \(y_i\) is the corresponding true value for total \(n\) samples, the estimated \(R^2\) is defined as:

\[R^2(y, \hat{y}) = 1 - \frac{\sum_{i=1}^{n} (y_i - \hat{y}_i)^2}{\sum_{i=1}^{n} (y_i - \bar{y})^2}\]

where \(\bar{y} = \frac{1}{n} \sum_{i=1}^{n} y_i\) and \(\sum_{i=1}^{n} (y_i - \hat{y}_i)^2 = \sum_{i=1}^{n} \epsilon_i^2\).

Note that r2_score calculates unadjusted \(R^2\) without correcting for bias in sample variance of y.

In the particular case where the true target is constant, the \(R^2\) score is not finite: it is either NaN (perfect predictions) or -Inf (imperfect predictions). Such non-finite scores may prevent correct model optimization such as grid-search cross-validation to be performed correctly. For this reason the default behaviour of r2_score is to replace them with 1.0 (perfect predictions) or 0.0 (imperfect predictions). If force_finite is set to False, this score falls back on the original \(R^2\) definition.

Here is a small example of usage of the r2_score function:

>>> from sklearn.metrics import r2_score
>>> y_true = [3, -0.5, 2, 7]
>>> y_pred = [2.5, 0.0, 2, 8]
>>> r2_score(y_true, y_pred)
0.948
>>> y_true = [[0.5, 1], [-1, 1], [7, -6]]
>>> y_pred = [[0, 2], [-1, 2], [8, -5]]
>>> r2_score(y_true, y_pred, multioutput='variance_weighted')
0.938
>>> y_true = [[0.5, 1], [-1, 1], [7, -6]]
>>> y_pred = [[0, 2], [-1, 2], [8, -5]]
>>> r2_score(y_true, y_pred, multioutput='uniform_average')
0.936
>>> r2_score(y_true, y_pred, multioutput='raw_values')
array([0.965, 0.908])
>>> r2_score(y_true, y_pred, multioutput=[0.3, 0.7])
0.925
>>> y_true = [-2, -2, -2]
>>> y_pred = [-2, -2, -2]
>>> r2_score(y_true, y_pred)
1.0
>>> r2_score(y_true, y_pred, force_finite=False)
nan
>>> y_true = [-2, -2, -2]
>>> y_pred = [-2, -2, -2 + 1e-8]
>>> r2_score(y_true, y_pred)
0.0
>>> r2_score(y_true, y_pred, force_finite=False)
-inf

Examples

3.4.6.2. Mean absolute error

The mean_absolute_error function computes mean absolute error, a risk metric corresponding to the expected value of the absolute error loss or \(l1\)-norm loss.

If \(\hat{y}_i\) is the predicted value of the \(i\)-th sample, and \(y_i\) is the corresponding true value, then the mean absolute error (MAE) estimated over \(n_{\text{samples}}\) is defined as

\[\text{MAE}(y, \hat{y}) = \frac{1}{n_{\text{samples}}} \sum_{i=0}^{n_{\text{samples}}-1} \left| y_i - \hat{y}_i \right|.\]

Here is a small example of usage of the mean_absolute_error function:

>>> from sklearn.metrics import mean_absolute_error
>>> y_true = [3, -0.5, 2, 7]
>>> y_pred = [2.5, 0.0, 2, 8]
>>> mean_absolute_error(y_true, y_pred)
0.5
>>> y_true = [[0.5, 1], [-1, 1], [7, -6]]
>>> y_pred = [[0, 2], [-1, 2], [8, -5]]
>>> mean_absolute_error(y_true, y_pred)
0.75
>>> mean_absolute_error(y_true, y_pred, multioutput='raw_values')
array([0.5, 1. ])
>>> mean_absolute_error(y_true, y_pred, multioutput=[0.3, 0.7])
0.85

3.4.6.3. Mean squared error

The mean_squared_error function computes mean squared error, a risk metric corresponding to the expected value of the squared (quadratic) error or loss.

If \(\hat{y}_i\) is the predicted value of the \(i\)-th sample, and \(y_i\) is the corresponding true value, then the mean squared error (MSE) estimated over \(n_{\text{samples}}\) is defined as

\[\text{MSE}(y, \hat{y}) = \frac{1}{n_\text{samples}} \sum_{i=0}^{n_\text{samples} - 1} (y_i - \hat{y}_i)^2.\]

Here is a small example of usage of the mean_squared_error function:

>>> from sklearn.metrics import mean_squared_error
>>> y_true = [3, -0.5, 2, 7]
>>> y_pred = [2.5, 0.0, 2, 8]
>>> mean_squared_error(y_true, y_pred)
0.375
>>> y_true = [[0.5, 1], [-1, 1], [7, -6]]
>>> y_pred = [[0, 2], [-1, 2], [8, -5]]
>>> mean_squared_error(y_true, y_pred)
0.7083

Examples

Taking the square root of the MSE, called the root mean squared error (RMSE), is another common metric that provides a measure in the same units as the target variable. RMSE is available through the root_mean_squared_error function.

3.4.6.4. Mean squared logarithmic error

The mean_squared_log_error function computes a risk metric corresponding to the expected value of the squared logarithmic (quadratic) error or loss.

If \(\hat{y}_i\) is the predicted value of the \(i\)-th sample, and \(y_i\) is the corresponding true value, then the mean squared logarithmic error (MSLE) estimated over \(n_{\text{samples}}\) is defined as

\[\text{MSLE}(y, \hat{y}) = \frac{1}{n_\text{samples}} \sum_{i=0}^{n_\text{samples} - 1} (\log_e (1 + y_i) - \log_e (1 + \hat{y}_i) )^2.\]

Where \(\log_e (x)\) means the natural logarithm of \(x\). This metric is best to use when targets having exponential growth, such as population counts, average sales of a commodity over a span of years etc. Note that this metric penalizes an under-predicted estimate greater than an over-predicted estimate.

Here is a small example of usage of the mean_squared_log_error function:

>>> from sklearn.metrics import mean_squared_log_error
>>> y_true = [3, 5, 2.5, 7]
>>> y_pred = [2.5, 5, 4, 8]
>>> mean_squared_log_error(y_true, y_pred)
0.0397
>>> y_true = [[0.5, 1], [1, 2], [7, 6]]
>>> y_pred = [[0.5, 2], [1, 2.5], [8, 8]]
>>> mean_squared_log_error(y_true, y_pred)
0.044

The root mean squared logarithmic error (RMSLE) is available through the root_mean_squared_log_error function.

3.4.6.5. Mean absolute percentage error

The mean_absolute_percentage_error (MAPE), also known as mean absolute percentage deviation (MAPD), is an evaluation metric for regression problems. The idea of this metric is to be sensitive to relative errors. It is for example not changed by a global scaling of the target variable.

If \(\hat{y}_i\) is the predicted value of the \(i\)-th sample and \(y_i\) is the corresponding true value, then the mean absolute percentage error (MAPE) estimated over \(n_{\text{samples}}\) is defined as

\[\text{MAPE}(y, \hat{y}) = \frac{1}{n_{\text{samples}}} \sum_{i=0}^{n_{\text{samples}}-1} \frac{{}\left| y_i - \hat{y}_i \right|}{\max(\epsilon, \left| y_i \right|)}\]

where \(\epsilon\) is an arbitrary small yet strictly positive number to avoid undefined results when y is zero.

The mean_absolute_percentage_error function supports multioutput.

Here is a small example of usage of the mean_absolute_percentage_error function:

>>> from sklearn.metrics import mean_absolute_percentage_error
>>> y_true = [1, 10, 1e6]
>>> y_pred = [0.9, 15, 1.2e6]
>>> mean_absolute_percentage_error(y_true, y_pred)
0.2666

In above example, if we had used mean_absolute_error, it would have ignored the small magnitude values and only reflected the error in prediction of highest magnitude value. But that problem is resolved in case of MAPE because it calculates relative percentage error with respect to actual output.

Note

The MAPE formula here does not represent the common “percentage” definition: the percentage in the range [0, 100] is converted to a relative value in the range [0, 1] by dividing by 100. Thus, an error of 200% corresponds to a relative error of 2. The motivation here is to have a range of values that is more consistent with other error metrics in scikit-learn, such as accuracy_score.

To obtain the mean absolute percentage error as per the Wikipedia formula, multiply the mean_absolute_percentage_error computed here by 100.

References

3.4.6.6. Median absolute error

The median_absolute_error is particularly interesting because it is robust to outliers. The loss is calculated by taking the median of all absolute differences between the target and the prediction.

If \(\hat{y}_i\) is the predicted value of the \(i\)-th sample and \(y_i\) is the corresponding true value, then the median absolute error (MedAE) estimated over \(n_{\text{samples}}\) is defined as

\[\text{MedAE}(y, \hat{y}) = \text{median}(\mid y_1 - \hat{y}_1 \mid, \ldots, \mid y_n - \hat{y}_n \mid).\]

The median_absolute_error does not support multioutput.

Here is a small example of usage of the median_absolute_error function:

>>> from sklearn.metrics import median_absolute_error
>>> y_true = [3, -0.5, 2, 7]
>>> y_pred = [2.5, 0.0, 2, 8]
>>> median_absolute_error(y_true, y_pred)
0.5

3.4.6.7. Max error

The max_error function computes the maximum residual error , a metric that captures the worst case error between the predicted value and the true value. In a perfectly fitted single output regression model, max_error would be 0 on the training set and though this would be highly unlikely in the real world, this metric shows the extent of error that the model had when it was fitted.

If \(\hat{y}_i\) is the predicted value of the \(i\)-th sample, and \(y_i\) is the corresponding true value, then the max error is defined as

\[\text{Max Error}(y, \hat{y}) = \max(| y_i - \hat{y}_i |)\]

Here is a small example of usage of the max_error function:

>>> from sklearn.metrics import max_error
>>> y_true = [3, 2, 7, 1]
>>> y_pred = [9, 2, 7, 1]
>>> max_error(y_true, y_pred)
6.0

The max_error does not support multioutput.

3.4.6.8. Explained variance score

The explained_variance_score computes the explained variance regression score.

If \(\hat{y}\) is the estimated target output, \(y\) the corresponding (correct) target output, and \(Var\) is Variance, the square of the standard deviation, then the explained variance is estimated as follow:

\[explained\_{}variance(y, \hat{y}) = 1 - \frac{Var\{ y - \hat{y}\}}{Var\{y\}}\]

The best possible score is 1.0, lower values are worse.

In the particular case where the true target is constant, the Explained Variance score is not finite: it is either NaN (perfect predictions) or -Inf (imperfect predictions). Such non-finite scores may prevent correct model optimization such as grid-search cross-validation to be performed correctly. For this reason the default behaviour of explained_variance_score is to replace them with 1.0 (perfect predictions) or 0.0 (imperfect predictions). You can set the force_finite parameter to False to prevent this fix from happening and fallback on the original Explained Variance score.

Here is a small example of usage of the explained_variance_score function:

>>> from sklearn.metrics import explained_variance_score
>>> y_true = [3, -0.5, 2, 7]
>>> y_pred = [2.5, 0.0, 2, 8]
>>> explained_variance_score(y_true, y_pred)
0.957
>>> y_true = [[0.5, 1], [-1, 1], [7, -6]]
>>> y_pred = [[0, 2], [-1, 2], [8, -5]]
>>> explained_variance_score(y_true, y_pred, multioutput='raw_values')
array([0.967, 1.        ])
>>> explained_variance_score(y_true, y_pred, multioutput=[0.3, 0.7])
0.990
>>> y_true = [-2, -2, -2]
>>> y_pred = [-2, -2, -2]
>>> explained_variance_score(y_true, y_pred)
1.0
>>> explained_variance_score(y_true, y_pred, force_finite=False)
nan
>>> y_true = [-2, -2, -2]
>>> y_pred = [-2, -2, -2 + 1e-8]
>>> explained_variance_score(y_true, y_pred)
0.0
>>> explained_variance_score(y_true, y_pred, force_finite=False)
-inf

3.4.6.9. Mean Poisson, Gamma, and Tweedie deviances

The mean_tweedie_deviance function computes the mean Tweedie deviance error with a power parameter (\(p\)). This is a metric that elicits predicted expectation values of regression targets.

Following special cases exist,

If \(\hat{y}_i\) is the predicted value of the \(i\)-th sample, and \(y_i\) is the corresponding true value, then the mean Tweedie deviance error (D) for power \(p\), estimated over \(n_{\text{samples}}\) is defined as

\[\begin{split}\text{D}(y, \hat{y}) = \frac{1}{n_\text{samples}} \sum_{i=0}^{n_\text{samples} - 1} \begin{cases} (y_i-\hat{y}_i)^2, & \text{for }p=0\text{ (Normal)}\\ 2(y_i \log(y_i/\hat{y}_i) + \hat{y}_i - y_i), & \text{for }p=1\text{ (Poisson)}\\ 2(\log(\hat{y}_i/y_i) + y_i/\hat{y}_i - 1), & \text{for }p=2\text{ (Gamma)}\\ 2\left(\frac{\max(y_i,0)^{2-p}}{(1-p)(2-p)}- \frac{y_i\,\hat{y}_i^{1-p}}{1-p}+\frac{\hat{y}_i^{2-p}}{2-p}\right), & \text{otherwise} \end{cases}\end{split}\]

Tweedie deviance is a homogeneous function of degree 2-power. Thus, Gamma distribution with power=2 means that simultaneously scaling y_true and y_pred has no effect on the deviance. For Poisson distribution power=1 the deviance scales linearly, and for Normal distribution (power=0), quadratically. In general, the higher power the less weight is given to extreme deviations between true and predicted targets.

For instance, let’s compare the two predictions 1.5 and 150 that are both 50% larger than their corresponding true value.

The mean squared error (power=0) is very sensitive to the prediction difference of the second point,:

>>> from sklearn.metrics import mean_tweedie_deviance
>>> mean_tweedie_deviance([1.0], [1.5], power=0)
0.25
>>> mean_tweedie_deviance([100.], [150.], power=0)
2500.0

If we increase power to 1,:

>>> mean_tweedie_deviance([1.0], [1.5], power=1)
0.189
>>> mean_tweedie_deviance([100.], [150.], power=1)
18.9

the difference in errors decreases. Finally, by setting, power=2:

>>> mean_tweedie_deviance([1.0], [1.5], power=2)
0.144
>>> mean_tweedie_deviance([100.], [150.], power=2)
0.144

we would get identical errors. The deviance when power=2 is thus only sensitive to relative errors.

3.4.6.10. Pinball loss

The mean_pinball_loss function is used to evaluate the predictive performance of quantile regression models.

\[\text{pinball}(y, \hat{y}) = \frac{1}{n_{\text{samples}}} \sum_{i=0}^{n_{\text{samples}}-1} \alpha \max(y_i - \hat{y}_i, 0) + (1 - \alpha) \max(\hat{y}_i - y_i, 0)\]

The value of pinball loss is equivalent to half of mean_absolute_error when the quantile parameter alpha is set to 0.5.

Here is a small example of usage of the mean_pinball_loss function:

>>> from sklearn.metrics import mean_pinball_loss
>>> y_true = [1, 2, 3]
>>> mean_pinball_loss(y_true, [0, 2, 3], alpha=0.1)
0.033
>>> mean_pinball_loss(y_true, [1, 2, 4], alpha=0.1)
0.3
>>> mean_pinball_loss(y_true, [0, 2, 3], alpha=0.9)
0.3
>>> mean_pinball_loss(y_true, [1, 2, 4], alpha=0.9)
0.033
>>> mean_pinball_loss(y_true, y_true, alpha=0.1)
0.0
>>> mean_pinball_loss(y_true, y_true, alpha=0.9)
0.0

It is possible to build a scorer object with a specific choice of alpha:

>>> from sklearn.metrics import make_scorer
>>> mean_pinball_loss_95p = make_scorer(mean_pinball_loss, alpha=0.95)

Such a scorer can be used to evaluate the generalization performance of a quantile regressor via cross-validation:

>>> from sklearn.datasets import make_regression
>>> from sklearn.model_selection import cross_val_score
>>> from sklearn.ensemble import GradientBoostingRegressor
>>>
>>> X, y = make_regression(n_samples=100, random_state=0)
>>> estimator = GradientBoostingRegressor(
...     loss="quantile",
...     alpha=0.95,
...     random_state=0,
... )
>>> cross_val_score(estimator, X, y, cv=5, scoring=mean_pinball_loss_95p)
array([14.3,  9.8, 23.9,  9.4, 10.8])

It is also possible to build scorer objects for hyper-parameter tuning. The sign of the loss must be switched to ensure that greater means better as explained in the example linked below.

Examples

3.4.6.11. D² score

The D² score computes the fraction of deviance explained. It is a generalization of R², where the squared error is generalized and replaced by a deviance of choice \(\text{dev}(y, \hat{y})\) (e.g., Tweedie, pinball or mean absolute error). D² is a form of a skill score. It is calculated as

\[D^2(y, \hat{y}) = 1 - \frac{\text{dev}(y, \hat{y})}{\text{dev}(y, y_{\text{null}})} \,.\]

Where \(y_{\text{null}}\) is the optimal prediction of an intercept-only model (e.g., the mean of y_true for the Tweedie case, the median for absolute error and the alpha-quantile for pinball loss).

Like R², the best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts \(y_{\text{null}}\), disregarding the input features, would get a D² score of 0.0.

D² Tweedie score

The d2_tweedie_score function implements the special case of D² where \(\text{dev}(y, \hat{y})\) is the Tweedie deviance, see Mean Poisson, Gamma, and Tweedie deviances. It is also known as D² Tweedie and is related to McFadden’s likelihood ratio index.

The argument power defines the Tweedie power as for mean_tweedie_deviance. Note that for power=0, d2_tweedie_score equals r2_score (for single targets).

A scorer object with a specific choice of power can be built by:

>>> from sklearn.metrics import d2_tweedie_score, make_scorer
>>> d2_tweedie_score_15 = make_scorer(d2_tweedie_score, power=1.5)
D² pinball score

The d2_pinball_score function implements the special case of D² with the pinball loss, see Pinball loss, i.e.:

\[\text{dev}(y, \hat{y}) = \text{pinball}(y, \hat{y}).\]

The argument alpha defines the slope of the pinball loss as for mean_pinball_loss (Pinball loss). It determines the quantile level alpha for which the pinball loss and also D² are optimal. Note that for alpha=0.5 (the default) d2_pinball_score equals d2_absolute_error_score.

A scorer object with a specific choice of alpha can be built by:

>>> from sklearn.metrics import d2_pinball_score, make_scorer
>>> d2_pinball_score_08 = make_scorer(d2_pinball_score, alpha=0.8)
D² absolute error score

The d2_absolute_error_score function implements the special case of the Mean absolute error:

\[\text{dev}(y, \hat{y}) = \text{MAE}(y, \hat{y}).\]

Here are some usage examples of the d2_absolute_error_score function:

>>> from sklearn.metrics import d2_absolute_error_score
>>> y_true = [3, -0.5, 2, 7]
>>> y_pred = [2.5, 0.0, 2, 8]
>>> d2_absolute_error_score(y_true, y_pred)
0.764
>>> y_true = [1, 2, 3]
>>> y_pred = [1, 2, 3]
>>> d2_absolute_error_score(y_true, y_pred)
1.0
>>> y_true = [1, 2, 3]
>>> y_pred = [2, 2, 2]
>>> d2_absolute_error_score(y_true, y_pred)
0.0

3.4.6.12. Visual evaluation of regression models

Among methods to assess the quality of regression models, scikit-learn provides the PredictionErrorDisplay class. It allows to visually inspect the prediction errors of a model in two different manners.

../_images/sphx_glr_plot_cv_predict_001.png

The plot on the left shows the actual values vs predicted values. For a noise-free regression task aiming to predict the (conditional) expectation of y, a perfect regression model would display data points on the diagonal defined by predicted equal to actual values. The further away from this optimal line, the larger the error of the model. In a more realistic setting with irreducible noise, that is, when not all the variations of y can be explained by features in X, then the best model would lead to a cloud of points densely arranged around the diagonal.

Note that the above only holds when the predicted values is the expected value of y given X. This is typically the case for regression models that minimize the mean squared error objective function or more generally the mean Tweedie deviance for any value of its “power” parameter.

When plotting the predictions of an estimator that predicts a quantile of y given X, e.g. QuantileRegressor or any other model minimizing the pinball loss, a fraction of the points are either expected to lie above or below the diagonal depending on the estimated quantile level.

All in all, while intuitive to read, this plot does not really inform us on what to do to obtain a better model.

The right-hand side plot shows the residuals (i.e. the difference between the actual and the predicted values) vs. the predicted values.

This plot makes it easier to visualize if the residuals follow and homoscedastic or heteroschedastic distribution.

In particular, if the true distribution of y|X is Poisson or Gamma distributed, it is expected that the variance of the residuals of the optimal model would grow with the predicted value of E[y|X] (either linearly for Poisson or quadratically for Gamma).

When fitting a linear least squares regression model (see LinearRegression and Ridge), we can use this plot to check if some of the model assumptions are met, in particular that the residuals should be uncorrelated, their expected value should be null and that their variance should be constant (homoschedasticity).

If this is not the case, and in particular if the residuals plot show some banana-shaped structure, this is a hint that the model is likely misspecified and that non-linear feature engineering or switching to a non-linear regression model might be useful.

Refer to the example below to see a model evaluation that makes use of this display.

Examples

3.4.7. Clustering metrics

The sklearn.metrics module implements several loss, score, and utility functions to measure clustering performance. For more information see the Clustering performance evaluation section for instance clustering, and Biclustering evaluation for biclustering.

3.4.8. Dummy estimators

When doing supervised learning, a simple sanity check consists of comparing one’s estimator against simple rules of thumb. DummyClassifier implements several such simple strategies for classification:

  • stratified generates random predictions by respecting the training set class distribution.

  • most_frequent always predicts the most frequent label in the training set.

  • prior always predicts the class that maximizes the class prior (like most_frequent) and predict_proba returns the class prior.

  • uniform generates predictions uniformly at random.

  • constant always predicts a constant label that is provided by the user.

    A major motivation of this method is F1-scoring, when the positive class is in the minority.

Note that with all these strategies, the predict method completely ignores the input data!

To illustrate DummyClassifier, first let’s create an imbalanced dataset:

>>> from sklearn.datasets import load_iris
>>> from sklearn.model_selection import train_test_split
>>> X, y = load_iris(return_X_y=True)
>>> y[y != 1] = -1
>>> X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)

Next, let’s compare the accuracy of SVC and most_frequent:

>>> from sklearn.dummy import DummyClassifier
>>> from sklearn.svm import SVC
>>> clf = SVC(kernel='linear', C=1).fit(X_train, y_train)
>>> clf.score(X_test, y_test)
0.63
>>> clf = DummyClassifier(strategy='most_frequent', random_state=0)
>>> clf.fit(X_train, y_train)
DummyClassifier(random_state=0, strategy='most_frequent')
>>> clf.score(X_test, y_test)
0.579

We see that SVC doesn’t do much better than a dummy classifier. Now, let’s change the kernel:

>>> clf = SVC(kernel='rbf', C=1).fit(X_train, y_train)
>>> clf.score(X_test, y_test)
0.94

We see that the accuracy was boosted to almost 100%. A cross validation strategy is recommended for a better estimate of the accuracy, if it is not too CPU costly. For more information see the Cross-validation: evaluating estimator performance section. Moreover if you want to optimize over the parameter space, it is highly recommended to use an appropriate methodology; see the Tuning the hyper-parameters of an estimator section for details.

More generally, when the accuracy of a classifier is too close to random, it probably means that something went wrong: features are not helpful, a hyperparameter is not correctly tuned, the classifier is suffering from class imbalance, etc…

DummyRegressor also implements four simple rules of thumb for regression:

  • mean always predicts the mean of the training targets.

  • median always predicts the median of the training targets.

  • quantile always predicts a user provided quantile of the training targets.

  • constant always predicts a constant value that is provided by the user.

In all these strategies, the predict method completely ignores the input data.

dataclasses — Data Classes

Assigned source reading · Python Software Foundation and Python documentation contributors

Copyright © 2001 Python Software Foundation; All Rights Reserved

Original source · Python Software Foundation License Version 2 · Retrieved October 25, 2026.

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

Full license and notices
PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
¶
1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and
   the Individual or Organization ("Licensee") accessing and otherwise using this
   software ("Python") in source or binary form and its associated documentation.

2. Subject to the terms and conditions of this License Agreement, PSF hereby
   grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
   analyze, test, perform and/or display publicly, prepare derivative works,
   distribute, and otherwise use Python alone or in any derivative
   version, provided, however, that PSF's License Agreement and PSF's notice of
   copyright, i.e., "Copyright © 2001 Python Software Foundation; All Rights
   Reserved" are retained in Python alone or in any derivative version
   prepared by Licensee.

3. In the event Licensee prepares a derivative work that is based on or
   incorporates Python or any part thereof, and wants to make the
   derivative work available to others as provided herein, then Licensee hereby
   agrees to include in any such work a brief summary of the changes made to Python.

4. PSF is making Python available to Licensee on an "AS IS" basis.
   PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.  BY WAY OF
   EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
   WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE
   USE OF PYTHON WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
   FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
   MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, OR ANY DERIVATIVE
   THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.

6. This License Agreement will automatically terminate upon a material breach of
   its terms and conditions.

7. Nothing in this License Agreement shall be deemed to create any relationship
   of agency, partnership, or joint venture between PSF and Licensee.  This License
   Agreement does not grant permission to use PSF trademarks or trade name in a
   trademark sense to endorse or promote products or services of Licensee, or any
   third party.

8. By copying, installing or otherwise using Python, Licensee agrees
   to be bound by the terms and conditions of this License Agreement.

dataclasses — Data Classes

Source code: Lib/dataclasses.py


This module provides a decorator and functions for automatically adding generated special methods such as __init__() and __repr__() to user-defined classes. It was originally described in PEP 557.

The member variables to use in these generated methods are defined using PEP 526 type annotations. For example, this code:

from dataclasses import dataclass

@dataclass
class InventoryItem:
    """Class for keeping track of an item in inventory."""
    name: str
    unit_price: float
    quantity_on_hand: int = 0

    def total_cost(self) -> float:
        return self.unit_price * self.quantity_on_hand

will add, among other things, a __init__() that looks like:

def __init__(self, name: str, unit_price: float, quantity_on_hand: int = 0):
    self.name = name
    self.unit_price = unit_price
    self.quantity_on_hand = quantity_on_hand

Note that this method is automatically added to the class: it is not directly specified in the InventoryItem definition shown above.

Added in version 3.7.

Module contents

@dataclasses.dataclass(*, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)

This function is a decorator that is used to add generated special methods to classes, as described below.

The @dataclass decorator examines the class to find fields. A field is defined as a class variable that has a type annotation. With two exceptions described below, nothing in @dataclass examines the type specified in the variable annotation.

The order of the fields in all of the generated methods is the order in which they appear in the class definition.

The @dataclass decorator will add various “dunder” methods to the class, described below. If any of the added methods already exist in the class, the behavior depends on the parameter, as documented below. The decorator returns the same class that it is called on; no new class is created.

If @dataclass is used just as a simple decorator with no parameters, it acts as if it has the default values documented in this signature. That is, these three uses of @dataclass are equivalent:

@dataclass
class C:
    ...

@dataclass()
class C:
    ...

@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False,
           match_args=True, kw_only=False, slots=False, weakref_slot=False)
class C:
    ...

The parameters to @dataclass are:

  • init: If true (the default), a __init__() method will be generated.

    If the class already defines __init__(), this parameter is ignored.

  • repr: If true (the default), a __repr__() method will be generated. The generated repr string will have the class name and the name and repr of each field, in the order they are defined in the class. Fields that are marked as being excluded from the repr are not included. For example: InventoryItem(name='widget', unit_price=3.0, quantity_on_hand=10).

    If the class already defines __repr__(), this parameter is ignored.

  • eq: If true (the default), an __eq__() method will be generated.

    This method compares the class by comparing each field in order. Both instances in the comparison must be of the identical type.

    If the class already defines __eq__(), this parameter is ignored.

    Changed in version 3.13: The generated __eq__ method now compares each field individually (for example, self.a == other.a and self.b == other.b), rather than comparing tuples of fields as in previous versions.

    This change makes the comparison faster but it may alter results in cases where attributes compare equal by identity but not by value (such as float('nan')).

    In Python 3.12 and earlier, the comparison was performed by creating tuples of the fields and comparing them (for example, (self.a, self.b) == (other.a, other.b)).

  • order: If true (the default is False), __lt__(), __le__(), __gt__(), and __ge__() methods will be generated. These compare the class as if it were a tuple of its fields, in order. Both instances in the comparison must be of the identical type. If order is true and eq is false, a ValueError is raised.

    If the class already defines any of __lt__(), __le__(), __gt__(), or __ge__(), then TypeError is raised.

  • unsafe_hash: If true, force dataclasses to create a __hash__() method, even though it may not be safe to do so. Otherwise, generate a __hash__() method according to how eq and frozen are set. The default value is False.

    __hash__() is used by built-in hash(), and when objects are added to hashed collections such as dictionaries and sets. Having a __hash__() implies that instances of the class are immutable. Mutability is a complicated property that depends on the programmer’s intent, the existence and behavior of __eq__(), and the values of the eq and frozen flags in the @dataclass decorator.

    By default, @dataclass will not implicitly add a __hash__() method unless it is safe to do so. Neither will it add or change an existing explicitly defined __hash__() method. Setting the class attribute __hash__ = None has a specific meaning to Python, as described in the __hash__() documentation.

    If __hash__() is not explicitly defined, or if it is set to None, then @dataclass may add an implicit __hash__() method. Although not recommended, you can force @dataclass to create a __hash__() method with unsafe_hash=True. This might be the case if your class is logically immutable but can still be mutated. This is a specialized use case and should be considered carefully.

    Here are the rules governing implicit creation of a __hash__() method. Note that you cannot both have an explicit __hash__() method in your dataclass and set unsafe_hash=True; this will result in a TypeError.

    If eq and frozen are both true, by default @dataclass will generate a __hash__() method for you. If eq is true and frozen is false, __hash__() will be set to None, marking it unhashable (which it is, since it is mutable). If eq is false, __hash__() will be left untouched meaning the __hash__() method of the superclass will be used (if the superclass is object, this means it will fall back to id-based hashing).

  • frozen: If true (the default is False), assigning to fields will generate an exception. This emulates read-only frozen instances. See the discussion below.

    If __setattr__() or __delattr__() is defined in the class and frozen is true, then TypeError is raised.

  • match_args: If true (the default is True), the __match_args__ tuple will be created from the list of non keyword-only parameters to the generated __init__() method (even if __init__() is not generated, see above). If false, or if __match_args__ is already defined in the class, then __match_args__ will not be generated.

Added in version 3.10.

  • kw_only: If true (the default value is False), then all fields will be marked as keyword-only. If a field is marked as keyword-only, then the only effect is that the __init__() parameter generated from a keyword-only field must be specified with a keyword when __init__() is called. See the parameter glossary entry for details. Also see the KW_ONLY section.

    Keyword-only fields are not included in __match_args__.

Added in version 3.10.

  • slots: If true (the default is False), __slots__ attribute will be generated and new class will be returned instead of the original one. If __slots__ is already defined in the class, then TypeError is raised.

Warning

Passing parameters to a base class __init_subclass__() when using slots=True will result in a TypeError. Either use __init_subclass__ with no parameters or use default values as a workaround. See gh-91126 for full details.

Added in version 3.10.

Changed in version 3.11: If a field name is already included in the __slots__ of a base class, it will not be included in the generated __slots__ to prevent overriding them. Therefore, do not use __slots__ to retrieve the field names of a dataclass. Use fields() instead. To be able to determine inherited slots, base class __slots__ may be any iterable, but not an iterator.

  • weakref_slot: If true (the default is False), add a slot named “__weakref__”, which is required to make an instance weakref-able. It is an error to specify weakref_slot=True without also specifying slots=True.

Added in version 3.11.

fields may optionally specify a default value, using normal Python syntax:

@dataclass
class C:
    a: int       # 'a' has no default value
    b: int = 0   # assign a default value for 'b'

In this example, both a and b will be included in the added __init__() method, which will be defined as:

def __init__(self, a: int, b: int = 0):

TypeError will be raised if a field without a default value follows a field with a default value. This is true whether this occurs in a single class, or as a result of class inheritance.

dataclasses.field(*, default=MISSING, default_factory=MISSING, init=True, repr=True, hash=None, compare=True, metadata=None, kw_only=MISSING, doc=None)

For common and simple use cases, no other functionality is required. There are, however, some dataclass features that require additional per-field information. To satisfy this need for additional information, you can replace the default field value with a call to the provided field() function. For example:

@dataclass
class C:
    mylist: list[int] = field(default_factory=list)

c = C()
c.mylist += [1, 2, 3]

As shown above, the MISSING value is a sentinel object used to detect if some parameters are provided by the user. This sentinel is used because None is a valid value for some parameters with a distinct meaning. No code should directly use the MISSING value.

The parameters to field() are:

  • default: If provided, this will be the default value for this field. This is needed because the field() call itself replaces the normal position of the default value.

  • default_factory: If provided, it must be a zero-argument callable that will be called when a default value is needed for this field. Among other purposes, this can be used to specify fields with mutable default values, as discussed below. It is an error to specify both default and default_factory.

  • init: If true (the default), this field is included as a parameter to the generated __init__() method.

  • repr: If true (the default), this field is included in the string returned by the generated __repr__() method.

  • hash: This can be a bool or None. If true, this field is included in the generated __hash__() method. If false, this field is excluded from the generated __hash__(). If None (the default), use the value of compare: this would normally be the expected behavior, since a field should be included in the hash if it’s used for comparisons. Setting this value to anything other than None is discouraged.

    One possible reason to set hash=False but compare=True would be if a field is expensive to compute a hash value for, that field is needed for equality testing, and there are other fields that contribute to the type’s hash value. Even if a field is excluded from the hash, it will still be used for comparisons.

  • compare: If true (the default), this field is included in the generated equality and comparison methods (__eq__(), __gt__(), et al.).

  • metadata: This can be a mapping or None. None is treated as an empty dict. This value is wrapped in MappingProxyType() to make it read-only, and exposed on the Field object. It is not used at all by Data Classes, and is provided as a third-party extension mechanism. Multiple third-parties can each have their own key, to use as a namespace in the metadata.

  • kw_only: If true, this field will be marked as keyword-only. This is used when the generated __init__() method’s parameters are computed.

    Keyword-only fields are also not included in __match_args__.

Added in version 3.10.

  • doc: optional docstring for this field.

Added in version 3.14.

If the default value of a field is specified by a call to field(), then the class attribute for this field will be replaced by the specified default value. If default is not provided, then the class attribute will be deleted. The intent is that after the @dataclass decorator runs, the class attributes will all contain the default values for the fields, just as if the default value itself were specified. For example, after:

@dataclass
class C:
    x: int
    y: int = field(repr=False)
    z: int = field(repr=False, default=10)
    t: int = 20

The class attribute C.z will be 10, the class attribute C.t will be 20, and the class attributes C.x and C.y will not be set.

Changed in version 3.15: If metadata is None, use an empty frozendict, instead of a MappingProxyType() of an empty dict.

class dataclasses.Field

Field objects describe each defined field. These objects are created internally, and are returned by the fields() module-level method (see below). Users should never instantiate a Field object directly. Its documented attributes are:

  • name: The name of the field.

  • type: The type of the field.

  • default, default_factory, init, repr, hash, compare, metadata, and kw_only have the identical meaning and values as they do in the field() function.

Other attributes may exist, but they are private and must not be inspected or relied on.

class dataclasses.InitVar

InitVar[T] type annotations describe variables that are init-only. Fields annotated with InitVar are considered pseudo-fields, and thus are neither returned by the fields() function nor used in any way except adding them as parameters to __init__() and an optional __post_init__().

dataclasses.fields(class_or_instance)

Returns a tuple of Field objects that define the fields for this dataclass. Accepts either a dataclass, or an instance of a dataclass. Raises TypeError if not passed a dataclass or instance of one. Does not return pseudo-fields which are ClassVar or InitVar.

dataclasses.asdict(obj, *, dict_factory=dict)

Converts the dataclass obj to a dict (by using the factory function dict_factory). Each dataclass is converted to a dict of its fields, as name: value pairs. dataclasses, dicts, frozendicts, lists, and tuples are recursed into. Other objects are copied with copy.deepcopy().

Example of using asdict() on nested dataclasses:

@dataclass
class Point:
     x: int
     y: int

@dataclass
class C:
     mylist: list[Point]

p = Point(10, 20)
assert asdict(p) == {'x': 10, 'y': 20}

c = C([Point(0, 0), Point(10, 4)])
assert asdict(c) == {'mylist': [{'x': 0, 'y': 0}, {'x': 10, 'y': 4}]}

To create a shallow copy, the following workaround may be used:

{field.name: getattr(obj, field.name) for field in fields(obj)}

asdict() raises TypeError if obj is not a dataclass instance.

dataclasses.astuple(obj, *, tuple_factory=tuple)

Converts the dataclass obj to a tuple (by using the factory function tuple_factory). Each dataclass is converted to a tuple of its field values. dataclasses, dicts, frozendicts, lists, and tuples are recursed into. Other objects are copied with copy.deepcopy().

Continuing from the previous example:

assert astuple(p) == (10, 20)
assert astuple(c) == ([(0, 0), (10, 4)],)

To create a shallow copy, the following workaround may be used:

tuple(getattr(obj, field.name) for field in dataclasses.fields(obj))

astuple() raises TypeError if obj is not a dataclass instance.

dataclasses.make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False, module=None, decorator=dataclass)

Creates a new dataclass with name cls_name, fields as defined in fields, base classes as given in bases, and initialized with a namespace as given in namespace. fields is an iterable whose elements are each either name, (name, type), or (name, type, Field). If just name is supplied, typing.Any is used for type. The values of init, repr, eq, order, unsafe_hash, frozen, match_args, kw_only, slots, and weakref_slot have the same meaning as they do in @dataclass.

If module is defined, the __module__ attribute of the dataclass is set to that value. By default, it is set to the module name of the caller.

The decorator parameter is a callable that will be used to create the dataclass. It should take the class object as a first argument and the same keyword arguments as @dataclass. By default, the @dataclass function is used.

This function is not strictly required, because any Python mechanism for creating a new class with __annotations__ can then apply the @dataclass function to convert that class to a dataclass. This function is provided as a convenience. For example:

C = make_dataclass('C',
                   [('x', int),
                     'y',
                    ('z', int, field(default=5))],
                   namespace={'add_one': lambda self: self.x + 1})

Is equivalent to:

@dataclass
class C:
    x: int
    y: 'typing.Any'
    z: int = 5

    def add_one(self):
        return self.x + 1

Added in version 3.14: Added the decorator parameter.

dataclasses.replace(obj, /, **changes)

Creates a new object of the same type as obj, replacing fields with values from changes. If obj is not a Data Class, raises TypeError. If keys in changes are not field names of the given dataclass, raises TypeError.

The newly returned object is created by calling the __init__() method of the dataclass. This ensures that __post_init__(), if present, is also called.

Init-only variables without default values, if any exist, must be specified on the call to replace() so that they can be passed to __init__() and __post_init__().

It is an error for changes to contain any fields that are defined as having init=False. A ValueError will be raised in this case.

Be forewarned about how init=False fields work during a call to replace(). They are not copied from the source object, but rather are initialized in __post_init__(), if they’re initialized at all. It is expected that init=False fields will be rarely and judiciously used. If they are used, it might be wise to have alternate class constructors, or perhaps a custom replace() (or similarly named) method which handles instance copying.

Dataclass instances are also supported by generic function copy.replace().

dataclasses.is_dataclass(obj)

Return True if its parameter is a dataclass (including subclasses of a dataclass, but not including generic aliases) or an instance of one, otherwise return False.

If you need to know if a class is an instance of a dataclass (and not a dataclass itself), then add a further check for not isinstance(obj, type):

def is_dataclass_instance(obj):
    return is_dataclass(obj) and not isinstance(obj, type)
dataclasses.MISSING

A sentinel object signifying a missing default or default_factory.

Changed in version 3.15: MISSING is now a sentinel object.

dataclasses.KW_ONLY

A sentinel object used as a type annotation. Any fields after a pseudo-field with the type of KW_ONLY are marked as keyword-only fields. Note that a pseudo-field of type KW_ONLY is otherwise completely ignored. This includes the name of such a field. By convention, a name of _ is used for a KW_ONLY field. Keyword-only fields signify __init__() parameters that must be specified as keywords when the class is instantiated.

In this example, the fields y and z will be marked as keyword-only fields:

@dataclass
class Point:
    x: float
    _: KW_ONLY
    y: float
    z: float

p = Point(0, y=1.5, z=2.0)

In a single dataclass, it is an error to specify more than one field whose type is KW_ONLY.

Added in version 3.10.

Changed in version 3.15: KW_ONLY is now a sentinel object.

exception dataclasses.FrozenInstanceError

Raised when an implicitly defined __setattr__() or __delattr__() is called on a dataclass which was defined with frozen=True. It is a subclass of AttributeError.

Post-init processing

dataclasses.__post_init__()

When defined on the class, it will be called by the generated __init__(), normally as self.__post_init__(). However, if any InitVar fields are defined, they will also be passed to __post_init__() in the order they were defined in the class. If no __init__() method is generated, then __post_init__() will not automatically be called.

Among other uses, this allows for initializing field values that depend on one or more other fields. For example:

@dataclass
class C:
    a: float
    b: float
    c: float = field(init=False)

    def __post_init__(self):
        self.c = self.a + self.b

The __init__() method generated by @dataclass does not call base class __init__() methods. If the base class has an __init__() method that has to be called, it is common to call this method in a __post_init__() method:

class Rectangle:
    def __init__(self, height, width):
        self.height = height
        self.width = width

@dataclass
class Square(Rectangle):
    side: float

    def __post_init__(self):
        super().__init__(self.side, self.side)

Note, however, that in general the dataclass-generated __init__() methods don’t need to be called, since the derived dataclass will take care of initializing all fields of any base class that is a dataclass itself.

See the section below on init-only variables for ways to pass parameters to __post_init__(). Also see the warning about how replace() handles init=False fields.

Class variables

One of the few places where @dataclass actually inspects the type of a field is to determine if a field is a class variable as defined in PEP 526. It does this by checking if the type of the field is typing.ClassVar. If a field is a ClassVar, it is excluded from consideration as a field and is ignored by the dataclass mechanisms. Such ClassVar pseudo-fields are not returned by the module-level fields() function.

Init-only variables

Another place where @dataclass inspects a type annotation is to determine if a field is an init-only variable. It does this by seeing if the type of a field is of type InitVar. If a field is an InitVar, it is considered a pseudo-field called an init-only field. As it is not a true field, it is not returned by the module-level fields() function. Init-only fields are added as parameters to the generated __init__() method, and are passed to the optional __post_init__() method. They are not otherwise used by dataclasses.

For example, suppose a field will be initialized from a database, if a value is not provided when creating the class:

@dataclass
class C:
    i: int
    j: int | None = None
    database: InitVar[DatabaseType | None] = None

    def __post_init__(self, database):
        if self.j is None and database is not None:
            self.j = database.lookup('j')

c = C(10, database=my_database)

In this case, fields() will return Field objects for i and j, but not for database.

Frozen instances

It is not possible to create truly immutable Python objects. However, by passing frozen=True to the @dataclass decorator you can emulate immutability. In that case, dataclasses will add __setattr__() and __delattr__() methods to the class. These methods will raise a FrozenInstanceError when invoked.

There is a tiny performance penalty when using frozen=True: __init__() cannot use simple assignment to initialize fields, and must use object.__setattr__().

Inheritance

When the dataclass is being created by the @dataclass decorator, it looks through all of the class’s base classes in reverse MRO (that is, starting at object) and, for each dataclass that it finds, adds the fields from that base class to an ordered mapping of fields. After all of the base class fields are added, it adds its own fields to the ordered mapping. All of the generated methods will use this combined, calculated ordered mapping of fields. Because the fields are in insertion order, derived classes override base classes. An example:

@dataclass
class Base:
    x: Any = 15.0
    y: int = 0

@dataclass
class C(Base):
    z: int = 10
    x: int = 15

The final list of fields is, in order, x, y, z. The final type of x is int, as specified in class C.

The generated __init__() method for C will look like:

def __init__(self, x: int = 15, y: int = 0, z: int = 10):

Re-ordering of keyword-only parameters in __init__()

After the parameters needed for __init__() are computed, any keyword-only parameters are moved to come after all regular (non-keyword-only) parameters. This is a requirement of how keyword-only parameters are implemented in Python: they must come after non-keyword-only parameters.

In this example, Base.y, Base.w, and D.t are keyword-only fields, and Base.x and D.z are regular fields:

@dataclass
class Base:
    x: Any = 15.0
    _: KW_ONLY
    y: int = 0
    w: int = 1

@dataclass
class D(Base):
    z: int = 10
    t: int = field(kw_only=True, default=0)

The generated __init__() method for D will look like:

def __init__(self, x: Any = 15.0, z: int = 10, *, y: int = 0, w: int = 1, t: int = 0):

Note that the parameters have been re-ordered from how they appear in the list of fields: parameters derived from regular fields are followed by parameters derived from keyword-only fields.

The relative ordering of keyword-only parameters is maintained in the re-ordered __init__() parameter list.

Default factory functions

If a field() specifies a default_factory, it is called with zero arguments when a default value for the field is needed. For example, to create a new instance of a list, use:

mylist: list = field(default_factory=list)

If a field is excluded from __init__() (using init=False) and the field also specifies default_factory, then the default factory function will always be called from the generated __init__() function. This happens because there is no other way to give the field an initial value.

Mutable default values

Python stores default member variable values in class attributes. Consider this example, not using dataclasses:

class C:
    x = []
    def add(self, element):
        self.x.append(element)

o1 = C()
o2 = C()
o1.add(1)
o2.add(2)
assert o1.x == [1, 2]
assert o1.x is o2.x

Note that the two instances of class C share the same class variable x, as expected.

Using dataclasses, if this code was valid:

@dataclass
class D:
    x: list = []      # This code raises ValueError
    def add(self, element):
        self.x.append(element)

it would generate code similar to:

class D:
    x = []
    def __init__(self, x=x):
        self.x = x
    def add(self, element):
        self.x.append(element)

assert D().x is D().x

This has the same issue as the original example using class C. That is, two instances of class D that do not specify a value for x when creating a class instance will share the same copy of x. Because dataclasses just use normal Python class creation they also share this behavior. There is no general way for Data Classes to detect this condition. Instead, the @dataclass decorator will raise a ValueError if it detects an unhashable default parameter. The assumption is that if a value is unhashable, it is mutable. This is a partial solution, but it does protect against many common errors.

Using default factory functions is a way to create new instances of mutable types as default values for fields:

@dataclass
class D:
    x: list = field(default_factory=list)

assert D().x is not D().x

Changed in version 3.11: Instead of looking for and disallowing objects of type list, dict, or set, unhashable objects are now not allowed as default values. Unhashability is used to approximate mutability.

Descriptor-typed fields

Fields that are assigned descriptor objects as their default value have the following special behaviors:

  • The value for the field passed to the dataclass’s __init__() method is passed to the descriptor’s __set__() method rather than overwriting the descriptor object.

  • Similarly, when getting or setting the field, the descriptor’s __get__() or __set__() method is called rather than returning or overwriting the descriptor object.

  • To determine whether a field contains a default value, @dataclass will call the descriptor’s __get__() method using its class access form: descriptor.__get__(obj=None, type=cls). If the descriptor returns a value in this case, it will be used as the field’s default. On the other hand, if the descriptor raises AttributeError in this situation, no default value will be provided for the field.

class IntConversionDescriptor:
    def __init__(self, *, default):
        self._default = default

    def __set_name__(self, owner, name):
        self._name = "_" + name

    def __get__(self, obj, type):
        if obj is None:
            return self._default

        return getattr(obj, self._name, self._default)

    def __set__(self, obj, value):
        setattr(obj, self._name, int(value))

@dataclass
class InventoryItem:
    quantity_on_hand: IntConversionDescriptor = IntConversionDescriptor(default=100)

i = InventoryItem()
print(i.quantity_on_hand)   # 100
i.quantity_on_hand = 2.5    # calls __set__ with 2.5
print(i.quantity_on_hand)   # 2

Note that if a field is annotated with a descriptor type, but is not assigned a descriptor object as its default value, the field will act like a normal field.

LLM03:2025 Supply Chain

Assigned source reading · OWASP GenAI Security Project contributors

Copyright © 2025 OWASP Foundation, Inc. and contributors. OWASP trademarks are excluded.

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

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

LLM03:2025 Supply Chain

LLM supply chains are susceptible to various vulnerabilities, which can affect the integrity of training data, models, and deployment platforms. These risks can result in biased outputs, security breaches, or system failures. While traditional software vulnerabilities focus on issues like code flaws and dependencies, in ML the risks also extend to third-party pre-trained models and data.

These external elements can be manipulated through tampering or poisoning attacks.

Creating LLMs is a specialized task that often depends on third-party models. The rise of open-access LLMs and new fine-tuning methods like “LoRA” (Low-Rank Adaptation) and “PEFT” (Parameter-Efficient Fine-Tuning), especially on platforms like Hugging Face, introduce new supply-chain risks. Finally, the emergence of on-device LLMs increase the attack surface and supply-chain risks for LLM applications.

Some of the risks discussed here are also discussed in “LLM04 Data and Model Poisoning.” This entry focuses on the supply-chain aspect of the risks. A simple threat model can be found here.

Such as outdated or deprecated components, which attackers can exploit to compromise LLM applications. This is similar to “A06:2021 – Vulnerable and Outdated Components” with increased risks when components are used during model development or finetuning. (Ref. link: A06:2021 – Vulnerable and Outdated Components)

AI development often involves diverse software and dataset licenses, creating risks if not properly managed. Different open-source and proprietary licenses impose varying legal requirements. Dataset licenses may restrict usage, distribution, or commercialization.

Using outdated or deprecated models that are no longer maintained leads to security issues.

Models are binary black boxes and unlike open source, static inspection can offer little to security assurances. Vulnerable pre-trained models can contain hidden biases, backdoors, or other malicious features that have not been identified through the safety evaluations of model repository. Vulnerable models can be created by both poisoned datasets and direct model tampering using tehcniques such as ROME also known as lobotomisation.

Currently there are no strong provenance assurances in published models. Model Cards and associated documentation provide model information and relied upon users, but they offer no guarantees on the origin of the model. An attacker can compromise supplier account on a model repo or create a similar one and combine it with social engineering techniques to compromise the supply-chain of an LLM application.

LoRA is a popular fine-tuning technique that enhances modularity by allowing pre-trained layers to be bolted onto an existing LLM. The method increases efficiency but create new risks, where a malicious LorA adapter compromises the integrity and security of the pre-trained base model. This can happen both in collaborative model merge environments but also exploiting the support for LoRA from popular inference deployment platforms such as vLMM and OpenLLM where adapters can be downloaded and applied to a deployed model.

Collaborative model merge and model handling services (e.g. conversions) hosted in shared environments can be exploited to introduce vulnerabilities in shared models. Model merging is is very popular on Hugging Face with model-merged models topping the OpenLLM leaderboard and can be exploited to bypass reviews. Similarly, services such as conversation bot have been proved to be vulnerable to maniputalion and introduce malicious code in models.

LLM models on device increase the supply attack surface with compromised manufactured processes and exploitation of device OS or fimware vulnerabilities to compromise models. Attackers can reverse engineer and re-package applications with tampered models.

Unclear T&Cs and data privacy policies of the model operators lead to the application’s sensitive data being used for model training and subsequent sensitive information exposure. This may also apply to risks from using copyrighted material by the model supplier.

  1. Carefully vet data sources and suppliers, including T&Cs and their privacy policies, only using trusted suppliers. Regularly review and audit supplier Security and Access, ensuring no changes in their security posture or T&Cs.
  2. Understand and apply the mitigations found in the OWASP Top Ten’s “A06:2021 – Vulnerable and Outdated Components.” This includes vulnerability scanning, management, and patching components. For development environments with access to sensitive data, apply these controls in those environments, too. (Ref. link: A06:2021 – Vulnerable and Outdated Components)
  3. Apply comprehensive AI Red Teaming and Evaluations when selecting a third party model. Decoding Trust is an example of a Trustworthy AI benchmark for LLMs but models can finetuned to by pass published benchmarks. Use extensive AI Red Teaming to evaluate the model, especially in the use cases you are planning to use the model for.
  4. Maintain an up-to-date inventory of components using a Software Bill of Materials (SBOM) to ensure you have an up-to-date, accurate, and signed inventory, preventing tampering with deployed packages. SBOMs can be used to detect and alert for new, zero-date vulnerabilities quickly. AI BOMs and ML SBOMs are an emerging area and you should evaluate options starting with OWASP CycloneDX
  5. To mitigate AI licensing risks, create an inventory of all types of licenses involved using BOMs and conduct regular audits of all software, tools, and datasets, ensuring compliance and transparency through BOMs. Use automated license management tools for real-time monitoring and train teams on licensing models. Maintain detailed licensing documentation in BOMs.
  6. Only use models from verifiable sources and use third-party model integrity checks with signing and file hashes to compensate for the lack of strong model provenance. Similarly, use code signing for externally supplied code.
  7. Implement strict monitoring and auditing practices for collaborative model development environments to prevent and quickly detect any abuse. “HuggingFace SF_Convertbot Scanner” is an example of automated scripts to use. (Ref. link: HuggingFace SF_Convertbot Scanner)
  8. AAnomaly detection and adversarial robustness tests on supplied models and data can help detect tampering and poisoning as discussed in “LLM04 Data and Model Poisoning; ideally, this should be part of MLOps and LLM pipelines; however, these are emerging techniques and may be easier to implement as part of red teaming exercises.
  9. Implement a patching policy to mitigate vulnerable or outdated components. Ensure the application relies on a maintained version of APIs and underlying model.
  10. Encrypt models deployed at AI edge with integrity checks and use vendor attestation APIs to prevent tampered apps and models and terminate applications of unrecognized firmware.

An attacker exploits a vulnerable Python library to compromise an LLM app. This happened in the first Open AI data breach. Attacks on the PyPi package registry tricked model developers into downloading a compromised PyTorch dependency with malware in a model development environment. A more sophisticated example of this type of attack is Shadow Ray attack on the Ray AI framework used by many vendors to manage AI infrastructure. In this attack, five vulnerabilities are believed to have been exploited in the wild affecting many servers.

Scenario #2: Direct Tampering

Direct Tampering and publishing a model to spread misinformation. This is an actual attack with PoisonGPT bypassing Hugging Face safety features by directly changing model parameters.

An attacker finetunes a popular open access model to remove key safety features and perform high in a specific domain (insurance). The model is finetuned to score highly on safety benchmarks but has very targeted triggers. They deploy it on Hugging Face for victims to use it exploiting their trust on benchmark assurances.

Scenario #4: Pre-Trained Models

An LLM system deploys pre-trained models from a widely used repository without thorough verification. A compromised model introduces malicious code, causing biased outputs in certain contexts and leading to harmful or manipulated outcomes

A compromised third-party supplier provides a vulnerable LorA adapter that is being merged to an LLM using model merge on Hugging Face.

Scenario #6: Supplier Infiltration

An attacker infiltrates a third-party supplier and compromises the production of a LoRA (Low-Rank Adaptation) adapter intended for integration with an on-device LLM deployed using frameworks like vLLM or OpenLLM. The compromised LoRA adapter is subtly altered to include hidden vulnerabilities and malicious code. Once this adapter is merged with the LLM, it provides the attacker with a covert entry point into the system. The malicious code can activate during model operations, allowing the attacker to manipulate the LLM’s outputs.

These attacks target cloud infrastructures, leveraging shared resources and vulnerabilities in the virtualization layers. CloudBorne involves exploiting firmware vulnerabilities in shared cloud environments, compromising the physical servers hosting virtual instances. CloudJacking refers to malicious control or misuse of cloud instances, potentially leading to unauthorized access to critical LLM deployment platforms. Both attacks represent significant risks for supply chains reliant on cloud-based ML models, as compromised environments could expose sensitive data or facilitate further attacks.

LeftOvers exploitation of leaked GPU local memory to recover sensitive data. An attacker can use this attack to exfiltrate sensitive data in production servers and development workstations or laptops.

Scenario #9: WizardLM

Following the removal of WizardLM, an attacker exploits the interest in this model and publish a fake version of the model with the same name but containing malware and backdoors.

An attacker stages an attack with a model merge or format conversation service to compromise a publicly available access model to inject malware. This is an actual attack published by vendor HiddenLayer.

An attacker reverse-engineers an mobile app to replace the model with a tampered version that leads the user to scam sites. Users are encouraged to dowload the app directly via social engineering techniques. This is a “real attack on predictive AI” that affected 116 Google Play apps including popular security and safety-critical applications used for as cash recognition, parental control, face authentication, and financial service. (Ref. link: real attack on predictive AI)

Scenario #12: Dataset Poisoning

An attacker poisons publicly available datasets to help create a back door when fine-tuning models. The back door subtly favors certain companies in different markets.

Scenario #13: T&Cs and Privacy Policy

An LLM operator changes its T&Cs and Privacy Policy to require an explicit opt out from using application data for model training, leading to the memorization of sensitive data.

  1. PoisonGPT: How we hid a lobotomized LLM on Hugging Face to spread fake news
  2. Large Language Models On-Device with MediaPipe and TensorFlow Lite
  3. Hijacking Safetensors Conversion on Hugging Face
  4. ML Supply Chain Compromise
  5. Using LoRA Adapters with vLLM
  6. Removing RLHF Protections in GPT-4 via Fine-Tuning
  7. Model Merging with PEFT
  8. HuggingFace SF_Convertbot Scanner
  9. Thousands of servers hacked due to insecurely deployed Ray AI framework
  10. LeftoverLocals: Listening to LLM responses through leaked GPU local memory

Refer to this section for comprehensive information, scenarios strategies relating to infrastructure deployment, applied environment controls and other best practices.

    LLM Top 10

    LLM01:2025 Prompt Injection

    A Prompt Injection Vulnerability occurs when user prompts alter the LLM’s behavior or output in unintended ways. These inputs...

    LLM02:2025 Sensitive Information Disclosure

    Sensitive information can affect both the LLM and its application context. This includes personal identifiable information (PII), financial details,...

    LLM03:2025 Supply Chain

    LLM supply chains are susceptible to various vulnerabilities, which can affect the integrity of training data, models, and deployment...

    LLM04:2025 Data and Model Poisoning

    Data poisoning occurs when pre-training, fine-tuning, or embedding data is manipulated to introduce vulnerabilities, backdoors, or biases. This manipulation...

    LLM05:2025 Improper Output Handling

    Improper Output Handling refers specifically to insufficient validation, sanitization, and handling of the outputs generated by large language models...

    LLM06:2025 Excessive Agency

    An LLM-based system is often granted a degree of agency by its developer – the ability to call functions...

    LLM07:2025 System Prompt Leakage

    The system prompt leakage vulnerability in LLMs refers to the risk that the system prompts or instructions used to...

    LLM08:2025 Vector and Embedding Weaknesses

    Vectors and embeddings vulnerabilities present significant security risks in systems utilizing Retrieval Augmented Generation (RAG) with Large Language Models...

    LLM09:2025 Misinformation

    Misinformation from LLMs poses a core vulnerability for applications relying on these models. Misinformation occurs when LLMs produce false...

    LLM10:2025 Unbounded Consumption

    Unbounded Consumption refers to the process where a Large Language Model (LLM) generates outputs based on input queries or...