Complete Assigned Readings

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

json — JSON encoder and decoder

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.

json — JSON encoder and decoder

Source code: Lib/json/__init__.py


JSON (JavaScript Object Notation), specified by RFC 7159 (which obsoletes RFC 4627) and by ECMA-404, is a lightweight data interchange format inspired by JavaScript object literal syntax (although it is not a strict subset of JavaScript [1] ).

Note

The term “object” in the context of JSON processing in Python can be ambiguous. All values in Python are objects. In JSON, an object refers to any data wrapped in curly braces, similar to a Python dictionary.

Warning

Be cautious when parsing JSON data from untrusted sources. A malicious JSON string may cause the decoder to consume considerable CPU and memory resources. Limiting the size of data to be parsed is recommended.

This module exposes an API familiar to users of the standard library marshal and pickle modules.

Encoding basic Python object hierarchies:

>>> import json
>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'
>>> print(json.dumps("\"foo\bar"))
"\"foo\bar"
>>> print(json.dumps('\u1234'))
"\u1234"
>>> print(json.dumps('\\'))
"\\"
>>> print(json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True))
{"a": 0, "b": 0, "c": 0}
>>> from io import StringIO
>>> io = StringIO()
>>> json.dump(['streaming API'], io)
>>> io.getvalue()
'["streaming API"]'

Compact encoding:

>>> import json
>>> json.dumps([1, 2, 3, {'4': 5, '6': 7}], separators=(',', ':'))
'[1,2,3,{"4":5,"6":7}]'

Pretty printing:

>>> import json
>>> print(json.dumps({'6': 7, '4': 5}, sort_keys=True, indent=4))
{
    "4": 5,
    "6": 7
}

Customizing JSON object encoding:

>>> import json
>>> def custom_json(obj):
...     if isinstance(obj, complex):
...         return {'__complex__': True, 'real': obj.real, 'imag': obj.imag}
...     raise TypeError(f'Cannot serialize object of {type(obj)}')
...
>>> json.dumps(1 + 2j, default=custom_json)
'{"__complex__": true, "real": 1.0, "imag": 2.0}'

Decoding JSON:

>>> import json
>>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
['foo', {'bar': ['baz', None, 1.0, 2]}]
>>> json.loads('"\\"foo\\bar"')
'"foo\x08ar'
>>> from io import StringIO
>>> io = StringIO('["streaming API"]')
>>> json.load(io)
['streaming API']

Customizing JSON object decoding:

>>> import json
>>> def as_complex(dct):
...     if '__complex__' in dct:
...         return complex(dct['real'], dct['imag'])
...     return dct
...
>>> json.loads('{"__complex__": true, "real": 1, "imag": 2}',
...     object_hook=as_complex)
(1+2j)
>>> import decimal
>>> json.loads('1.1', parse_float=decimal.Decimal)
Decimal('1.1')
>>> json.loads('{"name": "point", "coords": [[1, 2], [3, 4]]}',
...     array_hook=tuple)
{'name': 'point', 'coords': ((1, 2), (3, 4))}
>>> json.loads('{"name": "point", "coords": [1, 2]}',
...     object_pairs_hook=frozendict, array_hook=tuple)
frozendict({'name': 'point', 'coords': (1, 2)})

Extending JSONEncoder:

>>> import json
>>> class ComplexEncoder(json.JSONEncoder):
...     def default(self, obj):
...         if isinstance(obj, complex):
...             return [obj.real, obj.imag]
...         # Let the base class default method raise the TypeError
...         return super().default(obj)
...
>>> json.dumps(2 + 1j, cls=ComplexEncoder)
'[2.0, 1.0]'
>>> ComplexEncoder().encode(2 + 1j)
'[2.0, 1.0]'
>>> list(ComplexEncoder().iterencode(2 + 1j))
['[2.0', ', 1.0', ']']

Using json from the shell to validate and pretty-print:

$ echo '{"json":"obj"}' | python -m json
{
    "json": "obj"
}
$ echo '{1.2:3.4}' | python -m json
Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

See Command-line interface for detailed documentation.

Note

JSON is a subset of YAML 1.2. The JSON produced by this module’s default settings (in particular, the default separators value) is also a subset of YAML 1.0 and 1.1. This module can thus also be used as a YAML serializer.

Note

This module’s encoders and decoders preserve input and output order by default. Order is only lost if the underlying containers are unordered.

Basic Usage

json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)

Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object) using this Python-to-JSON conversion table.

Note

Unlike pickle and marshal, JSON is not a framed protocol, so trying to serialize multiple objects with repeated calls to dump() using the same fp will result in an invalid JSON file.

Parameters:
  • obj (object) – The Python object to be serialized.

  • fp (file-like object) – The file-like object obj will be serialized to. The json module always produces str objects, not bytes objects, therefore fp.write() must support str input.

  • skipkeys (bool) – If True, keys that are not of a basic type (str, int, float, bool, None) will be skipped instead of raising a TypeError. Default False.

  • ensure_ascii (bool) – If True (the default), the output is guaranteed to have all incoming non-ASCII and non-printable characters escaped. If False, all characters will be outputted as-is, except for the characters that must be escaped: quotation mark, reverse solidus, and the control characters U+0000 through U+001F.

  • check_circular (bool) – If False, the circular reference check for container types is skipped and a circular reference will result in a RecursionError (or worse). Default True.

  • allow_nan (bool) – If False, serialization of out-of-range float values (nan, inf, -inf) will result in a ValueError, in strict compliance with the JSON specification. If True (the default), their JavaScript equivalents (NaN, Infinity, -Infinity) are used.

  • cls (a JSONEncoder subclass) – If set, a custom JSON encoder with the default() method overridden, for serializing into custom datatypes. If None (the default), JSONEncoder is used.

  • indent (int | str | None) – If a positive integer or string, JSON array elements and object members will be pretty-printed with that indent level. A positive integer indents that many spaces per level; a string (such as "\t") is used to indent each level. If zero, negative, or "" (the empty string), only newlines are inserted. If None (the default), no newlines are inserted.

  • separators (tuple | None) – A two-tuple: (item_separator, key_separator). If None (the default), separators defaults to (', ', ': ') if indent is None, and (',', ': ') otherwise. For the most compact JSON, specify (',', ':') to eliminate whitespace.

  • default (callable | None) – A function that is called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError. If None (the default), TypeError is raised.

  • sort_keys (bool) – If True, dictionaries will be outputted sorted by key. Default False.

Note

Keys in key/value pairs of JSON are always of the type str. When a dictionary is converted into JSON, all the keys of the dictionary are converted to strings. As a result of this, if a dictionary is converted into JSON and then back into a dictionary, the dictionary may not equal the original one. That is, loads(dumps(x)) != x if x has non-string keys. sort_keys sorts the keys before they are converted to strings, so numeric keys are sorted by value, not by their string representation.

Changed in version 3.2: Allow strings for indent in addition to integers.

Changed in version 3.4: Use (',', ': ') as default if indent is not None.

Changed in version 3.6: All optional parameters are now keyword-only.

json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)

Serialize obj to a JSON formatted str using this conversion table. The arguments have the same meaning as in dump().

json.load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, array_hook=None, **kw)

Deserialize fp to a Python object using the JSON-to-Python conversion table.

Parameters:
  • fp (file-like object) – A .read()-supporting text file or binary file containing the JSON document to be deserialized.

  • cls (a JSONDecoder subclass) – If set, a custom JSON decoder. Additional keyword arguments to load() will be passed to the constructor of cls. If None (the default), JSONDecoder is used.

  • object_hook (callable | None) – If set, a function that is called with the result of any JSON object literal decoded (a dict). The return value of this function will be used instead of the dict. This feature can be used to implement custom decoders, for example JSON-RPC class hinting. Default None.

  • object_pairs_hook (callable | None) – If set, a function that is called with the result of any JSON object literal decoded with an ordered list of pairs. The return value of this function will be used instead of the dict. This feature can be used to implement custom decoders. If object_hook is also set, object_pairs_hook takes priority. Default None.

  • array_hook (callable | None) – If set, a function that is called with the result of any JSON array literal decoded as a Python list. The return value of this function will be used instead of the list. This feature can be used to implement custom decoders. Default None.

  • parse_float (callable | None) – If set, a function that is called with the string of every JSON float to be decoded. If None (the default), it is equivalent to float(num_str). This can be used to parse JSON floats into custom datatypes, for example decimal.Decimal.

  • parse_int (callable | None) – If set, a function that is called with the string of every JSON int to be decoded. If None (the default), it is equivalent to int(num_str). This can be used to parse JSON integers into custom datatypes, for example float.

  • parse_constant (callable | None) – If set, a function that is called with one of the following strings: '-Infinity', 'Infinity', or 'NaN'. This can be used to raise an exception if invalid JSON numbers are encountered. Default None.

Raises:
  • JSONDecodeError – When the data being deserialized is not a valid JSON document.

  • UnicodeDecodeError – When the data being deserialized does not contain UTF-8, UTF-16 or UTF-32 encoded data.

Changed in version 3.1:

  • Added the optional object_pairs_hook parameter.

  • parse_constant doesn’t get called on ‘null’, ‘true’, ‘false’ anymore.

Changed in version 3.6:

  • All optional parameters are now keyword-only.

  • fp can now be a binary file. The input encoding should be UTF-8, UTF-16 or UTF-32.

Changed in version 3.11: The default parse_int of int() now limits the maximum length of the integer string via the interpreter’s integer string conversion length limitation to help avoid denial of service attacks.

Changed in version 3.15: Added the optional array_hook parameter.

json.loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, array_hook=None, **kw)

Identical to load(), but instead of a file-like object, deserialize s (a str, bytes or bytearray instance containing a JSON document) to a Python object using this conversion table.

Changed in version 3.6: s can now be of type bytes or bytearray. The input encoding should be UTF-8, UTF-16 or UTF-32.

Changed in version 3.9: The keyword argument encoding has been removed.

Encoders and Decoders

class json.JSONDecoder(*, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True, object_pairs_hook=None, array_hook=None)

Simple JSON decoder.

Performs the following translations in decoding by default:

JSON

Python

object

dict

array

list

string

str

number (int)

int

number (real)

float

true

True

false

False

null

None

It also understands NaN, Infinity, and -Infinity as their corresponding float values, which is outside the JSON spec.

object_hook is an optional function that will be called with the result of every JSON object decoded and its return value will be used in place of the given dict. This can be used to provide custom deserializations (e.g. to support JSON-RPC class hinting).

object_pairs_hook is an optional function that will be called with the result of every JSON object decoded with an ordered list of pairs. The return value of object_pairs_hook will be used instead of the dict. This feature can be used to implement custom decoders. If object_hook is also defined, the object_pairs_hook takes priority.

Changed in version 3.1: Added support for object_pairs_hook.

array_hook is an optional function that will be called with the result of every JSON array decoded as a list. The return value of array_hook will be used instead of the list. This feature can be used to implement custom decoders.

Changed in version 3.15: Added support for array_hook.

parse_float is an optional function that will be called with the string of every JSON float to be decoded. By default, this is equivalent to float(num_str). This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal).

parse_int is an optional function that will be called with the string of every JSON int to be decoded. By default, this is equivalent to int(num_str). This can be used to use another datatype or parser for JSON integers (e.g. float).

parse_constant is an optional function that will be called with one of the following strings: '-Infinity', 'Infinity', 'NaN'. This can be used to raise an exception if invalid JSON numbers are encountered.

If strict is false (True is the default), then control characters will be allowed inside strings. Control characters in this context are those with character codes in the 0–31 range, including '\t' (tab), '\n', '\r' and '\0'.

If the data being deserialized is not a valid JSON document, a JSONDecodeError will be raised.

Changed in version 3.6: All parameters are now keyword-only.

decode(s)

Return the Python representation of s (a str instance containing a JSON document).

JSONDecodeError will be raised if the given JSON document is not valid.

raw_decode(s)

Decode a JSON document from s (a str beginning with a JSON document) and return a 2-tuple of the Python representation and the index in s where the document ended.

This can be used to decode a JSON document from a string that may have extraneous data at the end.

class json.JSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)

Extensible JSON encoder for Python data structures.

Supports the following objects and types by default:

Python

JSON

dict, frozendict

object

list, tuple

array

str

string

int, float, int- & float-derived Enums

number

True

true

False

false

None

null

Changed in version 3.4: Added support for int- and float-derived Enum classes.

Changed in version 3.15: Added support for frozendict.

To extend this to recognize other objects, subclass and implement a default() method with another method that returns a serializable object for o if possible, otherwise it should call the superclass implementation (to raise TypeError).

If skipkeys is false (the default), a TypeError will be raised when trying to encode keys that are not str, int, float, bool or None. If skipkeys is true, such items are simply skipped.

If ensure_ascii is true (the default), the output is guaranteed to have all incoming non-ASCII and non-printable characters escaped. If ensure_ascii is false, all characters will be output as-is, except for the characters that must be escaped: quotation mark, reverse solidus, and the control characters U+0000 through U+001F.

If check_circular is true (the default), then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause a RecursionError). Otherwise, no such check takes place.

If allow_nan is true (the default), then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats.

If sort_keys is true (default: False), then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis.

If indent is a non-negative integer or string, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, negative, or "" will only insert newlines. None (the default) selects the most compact representation. Using a positive integer indent indents that many spaces per level. If indent is a string (such as "\t"), that string is used to indent each level.

Changed in version 3.2: Allow strings for indent in addition to integers.

If specified, separators should be an (item_separator, key_separator) tuple. The default is (', ', ': ') if indent is None and (',', ': ') otherwise. To get the most compact JSON representation, you should specify (',', ':') to eliminate whitespace.

Changed in version 3.4: Use (',', ': ') as default if indent is not None.

If specified, default should be a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError. If not specified, TypeError is raised.

Changed in version 3.6: All parameters are now keyword-only.

default(o)

Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a TypeError).

For example, to support arbitrary iterators, you could implement default() like this:

def default(self, o):
   try:
       iterable = iter(o)
   except TypeError:
       pass
   else:
       return list(iterable)
   # Let the base class default method raise the TypeError
   return super().default(o)
encode(o)

Return a JSON string representation of a Python data structure, o. For example:

>>> json.JSONEncoder().encode({"foo": ["bar", "baz"]})
'{"foo": ["bar", "baz"]}'
iterencode(o)

Encode the given object, o, and yield each string representation as available. For example:

for chunk in json.JSONEncoder().iterencode(bigobject):
    mysocket.write(chunk)

Exceptions

exception json.JSONDecodeError(msg, doc, pos)

Subclass of ValueError with the following additional attributes:

msg

The unformatted error message.

doc

The JSON document being parsed.

pos

The start index of doc where parsing failed.

lineno

The line corresponding to pos.

colno

The column corresponding to pos.

Added in version 3.5.

Standard Compliance and Interoperability

The JSON format is specified by RFC 7159 and by ECMA-404. This section details this module’s level of compliance with the RFC. For simplicity, JSONEncoder and JSONDecoder subclasses, and parameters other than those explicitly mentioned, are not considered.

This module does not comply with the RFC in a strict fashion, implementing some extensions that are valid JavaScript but not valid JSON. In particular:

  • Infinite and NaN number values are accepted and output;

  • Repeated names within an object are accepted, and only the value of the last name-value pair is used.

Since the RFC permits RFC-compliant parsers to accept input texts that are not RFC-compliant, this module’s deserializer is technically RFC-compliant under default settings.

Character Encodings

The RFC requires that JSON be represented using either UTF-8, UTF-16, or UTF-32, with UTF-8 being the recommended default for maximum interoperability.

As permitted, though not required, by the RFC, this module’s serializer sets ensure_ascii=True by default, thus escaping the output so that the resulting strings only contain printable ASCII characters.

Other than the ensure_ascii parameter, this module is defined strictly in terms of conversion between Python objects and Unicode strings, and thus does not otherwise directly address the issue of character encodings.

The RFC prohibits adding a byte order mark (BOM) to the start of a JSON text, and this module’s serializer does not add a BOM to its output. The RFC permits, but does not require, JSON deserializers to ignore an initial BOM in their input. This module’s deserializer raises a ValueError when an initial BOM is present.

The RFC does not explicitly forbid JSON strings which contain byte sequences that don’t correspond to valid Unicode characters (e.g. unpaired UTF-16 surrogates), but it does note that they may cause interoperability problems. By default, this module accepts and outputs (when present in the original str) code points for such sequences.

Infinite and NaN Number Values

The RFC does not permit the representation of infinite or NaN number values. Despite that, by default, this module accepts and outputs Infinity, -Infinity, and NaN as if they were valid JSON number literal values:

>>> # Neither of these calls raises an exception, but the results are not valid JSON
>>> json.dumps(float('-inf'))
'-Infinity'
>>> json.dumps(float('nan'))
'NaN'
>>> # Same when deserializing
>>> json.loads('-Infinity')
-inf
>>> json.loads('NaN')
nan

In the serializer, the allow_nan parameter can be used to alter this behavior. In the deserializer, the parse_constant parameter can be used to alter this behavior.

Repeated Names Within an Object

The RFC specifies that the names within a JSON object should be unique, but does not mandate how repeated names in JSON objects should be handled. By default, this module does not raise an exception; instead, it ignores all but the last name-value pair for a given name:

>>> weird_json = '{"x": 1, "x": 2, "x": 3}'
>>> json.loads(weird_json)
{'x': 3}

The object_pairs_hook parameter can be used to alter this behavior.

Top-level Non-Object, Non-Array Values

The old version of JSON specified by the obsolete RFC 4627 required that the top-level value of a JSON text must be either a JSON object or array (Python dict or list), and could not be a JSON null, boolean, number, or string value. RFC 7159 removed that restriction, and this module does not and has never implemented that restriction in either its serializer or its deserializer.

Regardless, for maximum interoperability, you may wish to voluntarily adhere to the restriction yourself.

Implementation Limitations

Some JSON deserializer implementations may set limits on:

  • the size of accepted JSON texts

  • the maximum level of nesting of JSON objects and arrays

  • the range and precision of JSON numbers

  • the content and maximum length of JSON strings

This module does not impose any such limits beyond those of the relevant Python datatypes themselves or the Python interpreter itself.

When serializing to JSON, beware any such limitations in applications that may consume your JSON. In particular, it is common for JSON numbers to be deserialized into IEEE 754 double precision numbers and thus subject to that representation’s range and precision limitations. This is especially relevant when serializing Python int values of extremely large magnitude, or when serializing instances of “exotic” numerical types such as decimal.Decimal.

Command-line interface

Source code: Lib/json/tool.py


The json module can be invoked as a script via python -m json to validate and pretty-print JSON objects. The json.tool submodule implements this interface.

If the optional infile and outfile arguments are not specified, sys.stdin and sys.stdout will be used respectively:

$ echo '{"json": "obj"}' | python -m json
{
    "json": "obj"
}
$ echo '{1.2:3.4}' | python -m json
Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

Changed in version 3.5: The output is now in the same order as the input. Use the --sort-keys option to sort the output of dictionaries alphabetically by key.

Changed in version 3.14: The json module may now be directly executed as python -m json. For backwards compatibility, invoking the CLI as python -m json.tool remains supported.

Command-line options

infile

The JSON file to be validated or pretty-printed:

$ python -m json mp_films.json
[
    {
        "title": "And Now for Something Completely Different",
        "year": 1971
    },
    {
        "title": "Monty Python and the Holy Grail",
        "year": 1975
    }
]

If infile is not specified, read from sys.stdin.

outfile

Write the output of the infile to the given outfile. Otherwise, write it to sys.stdout.

--sort-keys

Sort the output of dictionaries alphabetically by key.

Added in version 3.5.

--no-ensure-ascii

Disable escaping of non-ascii characters, see json.dumps() for more information.

Added in version 3.9.

--json-lines

Parse every input line as separate JSON object.

Added in version 3.8.

--indent, --tab, --no-indent, --compact

Mutually exclusive options for whitespace control.

Added in version 3.9.

-h, --help

Show the help message.

Footnotes

2 . 2 FastArrayStack: An Optimized ArrayStack

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.


2.2 FastArrayStack: An Optimized ArrayStack

Much of the work done by an ArrayStack involves shifting (by $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$) and copying (by $ \ensuremath{\mathrm{resize}()}$) of data. In a naive implementation, this would be done using $ {\color{black} \textbf{for}}$ loops. It turns out that many programming environments have specific functions that are very efficient at copying and moving blocks of data. In the C programming language, there are the $ \ensuremath{\mathrm{memcpy}(\ensuremath{\mathit{d}},\ensuremath{\mathit{s}},\ensuremath{\mathit{n}})}$ and $ \ensuremath{\mathrm{memmove}(\ensuremath{\mathit{d}},\ensuremath{\mathit{s}},\ensuremath{\mathit{n}})}$ functions. In the C++ language there is the $ \ensuremath{\mathrm{stdcopy}(\ensuremath{\mathit{a_0}},\ensuremath{\mathit{a_1}},\ensuremath{\mathit{b}})}$ algorithm. In Java there is the $ \ensuremath{\mathrm{System}.\mathrm{arraycopy}(\ensuremath{\mathit{s}},\ensure...
...t{i}},\ensuremath{\mathit{d}},\ensuremath{\mathit{j}},\ensuremath{\mathit{n}})}$ method.

These functions are usually highly optimized and may even use special machine instructions that can do this copying much faster than we could by using a $ {\color{black} \textbf{for}}$ loop. Although using these functions does not asymptotically decrease the running times, it can still be a worthwhile optimization.

In our C++ and Java implementations, the use of fast array copying functions resulted in speedups of a factor between 2 and 3, depending on the types of operations performed. Your mileage may vary.

opendatastructures.org

11 . Sorting Algorithms

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.


11. Sorting Algorithms

This chapter discusses algorithms for sorting a set of $ \ensuremath{\ensuremath{\mathit{n}}}$ items. This might seem like a strange topic for a book on data structures, but there are several good reasons for including it here. The most obvious reason is that two of these sorting algorithms (quicksort and heap-sort) are intimately related to two of the data structures we have already studied (random binary search trees and heaps, respectively).

The first part of this chapter discusses algorithms that sort using only comparisons and presents three algorithms that run in $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ time. As it turns out, all three algorithms are asymptotically optimal; no algorithm that uses only comparisons can avoid doing roughly $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}\log
\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$ comparisons in the worst case and even the average case.

Before continuing, we should note that any of the SSet or priority Queue implementations presented in previous chapters can also be used to obtain an $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ time sorting algorithm. For example, we can sort $ \ensuremath{\ensuremath{\mathit{n}}}$ items by performing $ \ensuremath{\ensuremath{\mathit{n}}}$ $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ operations followed by $ \ensuremath{\ensuremath{\mathit{n}}}$ $ \ensuremath{\mathrm{remove}()}$ operations on a BinaryHeap or MeldableHeap. Alternatively, we can use $ \ensuremath{\ensuremath{\mathit{n}}}$ $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ operations on any of the binary search tree data structures and then perform an in-order traversal (Exercise 6.8) to extract the elements in sorted order. However, in both cases we go through a lot of overhead to build a structure that is never fully used. Sorting is such an important problem that it is worthwhile developing direct methods that are as fast, simple, and space-efficient as possible.

The second part of this chapter shows that, if we allow other operations besides comparisons, then all bets are off. Indeed, by using array-indexing, it is possible to sort a set of $ \ensuremath{\ensuremath{\mathit{n}}}$ integers in the range $ \{0,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}^c-1\}$ in $ O(c\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ time.



Subsections
opendatastructures.org

8 . 1 ScapegoatTree: A Binary Search Tree with Partial Rebuilding

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


8.1 ScapegoatTree: A Binary Search Tree with Partial Rebuilding

A ScapegoatTree is a BinarySearchTree that, in addition to keeping track of the number, $ \ensuremath{\ensuremath{\mathit{n}}}$, of nodes in the tree also keeps a counter, $ \ensuremath{\ensuremath{\mathit{q}}}$, that maintains an upper-bound on the number of nodes.
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{initialize}(...
...th{\ensuremath{\mathit{q}} \gets \ensuremath{0}}\\
\end{flushleft}\end{leftbar}
At all times, $ \ensuremath{\ensuremath{\mathit{n}}}$ and $ \ensuremath{\ensuremath{\mathit{q}}}$ obey the following inequalities:

$\displaystyle \ensuremath{\ensuremath{\ensuremath{\mathit{q}}}}/2 \le \ensurema...
...\mathit{n}}}} \le \ensuremath{\ensuremath{\ensuremath{\mathit{q}}}} \enspace .
$

In addition, a ScapegoatTree has logarithmic height; at all times, the height of the scapegoat tree does not exceed

$\displaystyle \log_{3/2} \ensuremath{\ensuremath{\ensuremath{\mathit{q}}}} \le ...
...}} < \log_{3/2} \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}} + 2\enspace .$ (8.1)

Even with this constraint, a ScapegoatTree can look surprisingly unbalanced. The tree in Figure 8.1 has $ \ensuremath{\ensuremath{\ensuremath{\mathit{q}}}}=\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}=10$ and height $ 5<\log_{3/2}10 \approx 5.679$.

Figure 8.1: A ScapegoatTree with 10 nodes and height 5.
\includegraphics[scale=0.90909]{figs-python/scapegoat-insert-1}

Implementing the $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$ operation in a ScapegoatTree is done using the standard algorithm for searching in a BinarySearchTree (see Section 6.2). This takes time proportional to the height of the tree which, by (8.1) is $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$.

To implement the $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ operation, we first increment $ \ensuremath{\ensuremath{\mathit{n}}}$ and $ \ensuremath{\ensuremath{\mathit{q}}}$ and then use the usual algorithm for adding $ \ensuremath{\ensuremath{\mathit{x}}}$ to a binary search tree; we search for $ \ensuremath{\ensuremath{\mathit{x}}}$ and then add a new leaf $ \ensuremath{\ensuremath{\mathit{u}}}$ with $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{x}}}}=\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}$. At this point, we may get lucky and the depth of $ \ensuremath{\ensuremath{\mathit{u}}}$ might not exceed $ \log_{3/2}\ensuremath{\ensuremath{\ensuremath{\mathit{q}}}}$. If so, then we leave well enough alone and don't do anything else.

Unfortunately, it will sometimes happen that $ \ensuremath{\ensuremath{\mathrm{depth}(\ensuremath{\mathit{u}})}} > \log_{3/2}
\ensuremath{\ensuremath{\ensuremath{\mathit{q}}}}$. In this case, we need to reduce the height. This isn't a big job; there is only one node, namely $ \ensuremath{\ensuremath{\mathit{u}}}$, whose depth exceeds $ \log_{3/2}
\ensuremath{\ensuremath{\ensuremath{\mathit{q}}}}$. To fix $ \ensuremath{\ensuremath{\mathit{u}}}$, we walk from $ \ensuremath{\ensuremath{\mathit{u}}}$ back up to the root looking for a scapegoat, $ \ensuremath{\ensuremath{\mathit{w}}}$. The scapegoat, $ \ensuremath{\ensuremath{\mathit{w}}}$, is a very unbalanced node. It has the property that

$\displaystyle \frac{\ensuremath{\ensuremath{\mathrm{size}(\ensuremath{\mathit{w...
...{\ensuremath{\mathrm{size}(\ensuremath{\mathit{w}})}}} > \frac{2}{3} \enspace ,$ (8.2)

where $ \ensuremath{\ensuremath{\mathit{w}}.\ensuremath{\mathit{child}}}$ is the child of $ \ensuremath{\ensuremath{\mathit{w}}}$ on the path from the root to $ \ensuremath{\ensuremath{\mathit{u}}}$. We'll very shortly prove that a scapegoat exists. For now, we can take it for granted. Once we've found the scapegoat $ \ensuremath{\ensuremath{\mathit{w}}}$, we completely destroy the subtree rooted at $ \ensuremath{\ensuremath{\mathit{w}}}$ and rebuild it into a perfectly balanced binary search tree. We know, from (8.2), that, even before the addition of $ \ensuremath{\ensuremath{\mathit{u}}}$, $ \ensuremath{\ensuremath{\mathit{w}}}$'s subtree was not a complete binary tree. Therefore, when we rebuild $ \ensuremath{\ensuremath{\mathit{w}}}$, the height decreases by at least 1 so that the height of the ScapegoatTree is once again at most $ \log_{3/2}\ensuremath{\ensuremath{\ensuremath{\mathit{q}}}}$.


\begin{leftbar}
% latex2html id marker 40162\begin{flushleft}
\hspace*{1em} \e...
...urn}} \ensuremath{\ensuremath{\mathit{d}} \ge 0}\\
\end{flushleft}\end{leftbar}

Figure 8.2: Inserting 3.5 into a ScapegoatTree increases its height to 6, which violates (8.1) since $ 6 > \log_{3/2} 11 \approx 5.914$. A scapegoat is found at the node containing 5.
\includegraphics[scale=0.90909]{figs-python/scapegoat-insert-3} \includegraphics[scale=0.90909]{figs-python/scapegoat-insert-4}
If we ignore the cost of finding the scapegoat $ \ensuremath{\ensuremath{\mathit{w}}}$ and rebuilding the subtree rooted at $ \ensuremath{\ensuremath{\mathit{w}}}$, then the running time of $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ is dominated by the initial search, which takes $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{q}}}}) = O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ time. We will account for the cost of finding the scapegoat and rebuilding using amortized analysis in the next section.

The implementation of $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ in a ScapegoatTree is very simple. We search for $ \ensuremath{\ensuremath{\mathit{x}}}$ and remove it using the usual algorithm for removing a node from a BinarySearchTree. (Note that this can never increase the height of the tree.) Next, we decrement $ \ensuremath{\ensuremath{\mathit{n}}}$, but leave $ \ensuremath{\ensuremath{\mathit{q}}}$ unchanged. Finally, we check if $ \ensuremath{\ensuremath{\ensuremath{\mathit{q}}}} > 2\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$ and, if so, then we rebuild the entire tree into a perfectly balanced binary search tree and set $ \ensuremath{\ensuremath{\ensuremath{\mathit{q}}}}=\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$.
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{remove}(\ens...
...eturn}} \ensuremath{\ensuremath{\mathit{false}}}\\
\end{flushleft}\end{leftbar}
Again, if we ignore the cost of rebuilding, the running time of the $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ operation is proportional to the height of the tree, and is therefore $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$.

8.1.1 Analysis of Correctness and Running-Time

In this section, we analyze the correctness and amortized running time of operations on a ScapegoatTree. We first prove the correctness by showing that, when the $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ operation results in a node that violates Condition (8.1), then we can always find a scapegoat:

Lemma 8..1   Let $ \ensuremath{\ensuremath{\mathit{u}}}$ be a node of depth $ h>\log_{3/2} \ensuremath{\ensuremath{\ensuremath{\mathit{q}}}}$ in a ScapegoatTree. Then there exists a node $ \ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}$ on the path from $ \ensuremath{\ensuremath{\mathit{u}}}$ to the root such that

$\displaystyle \frac{\ensuremath{\ensuremath{\mathrm{size}(\ensuremath{\mathit{w...
...h{\mathrm{size}(\mathrm{parent}(\ensuremath{\mathit{w}})})}} > 2/3 \enspace .
$

Proof. Suppose, for the sake of contradiction, that this is not the case, and

$\displaystyle \frac{\ensuremath{\ensuremath{\mathrm{size}(\ensuremath{\mathit{w...
...\mathrm{size}(\mathrm{parent}(\ensuremath{\mathit{w}})})}} \le 2/3 \enspace .
$

for all nodes $ \ensuremath{\ensuremath{\mathit{w}}}$ on the path from $ \ensuremath{\ensuremath{\mathit{u}}}$ to the root. Denote the path from the root to $ \ensuremath{\ensuremath{\mathit{u}}}$ as $ \ensuremath{\ensuremath{\ensuremath{\mathit{r}}}}=\ensuremath{\ensuremath{\ens...
...h{\ensuremath{\mathit{u}}}}_h=\ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}$. Then, we have $ \ensuremath{\ensuremath{size}(\ensuremath{\ensuremath{\mathit{u}}}}_0\ensuremath{)}=\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$, $ \ensuremath{\ensuremath{size}(\ensuremath{\ensuremath{\mathit{u}}}}_1\ensuremath{)}\le\frac{2}{3}\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$, $ \ensuremath{\ensuremath{size}(\ensuremath{\ensuremath{\mathit{u}}}}_2\ensuremath{)}\le\frac{4}{9}\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$ and, more generally,

$\displaystyle \ensuremath{\ensuremath{size}(\ensuremath{\ensuremath{\mathit{u}}...
...ac{2}{3}\right)^i\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}} \enspace .
$

But this gives a contradiction, since $ \ensuremath{\ensuremath{\mathrm{size}(\ensuremath{\mathit{u}})}}\ge 1$, hence

$\displaystyle 1 \le \ensuremath{\ensuremath{\mathrm{size}(\ensuremath{\mathit{u...
...t) \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}
= 1 \enspace . \qedhere
$

$ \qedsymbol$

Next, we analyze the parts of the running time that are not yet accounted for. There are two parts: The cost of calls to $ \ensuremath{\mathrm{size}(\ensuremath{\mathit{u}})}$ when searching for scapegoat nodes, and the cost of calls to $ \ensuremath{\mathrm{rebuild}(\ensuremath{\mathit{w}})}$ when we find a scapegoat $ \ensuremath{\ensuremath{\mathit{w}}}$. The cost of calls to $ \ensuremath{\mathrm{size}(\ensuremath{\mathit{u}})}$ can be related to the cost of calls to $ \ensuremath{\mathrm{rebuild}(\ensuremath{\mathit{w}})}$, as follows:

Lemma 8..2   During a call to $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ in a ScapegoatTree, the cost of finding the scapegoat $ \ensuremath{\ensuremath{\mathit{w}}}$ and rebuilding the subtree rooted at $ \ensuremath{\ensuremath{\mathit{w}}}$ is $ O(\ensuremath{\ensuremath{\mathrm{size}(\ensuremath{\mathit{w}})}})$.

Proof. The cost of rebuilding the scapegoat node $ \ensuremath{\ensuremath{\mathit{w}}}$, once we find it, is $ O(\ensuremath{\ensuremath{\mathrm{size}(\ensuremath{\mathit{w}})}})$. When searching for the scapegoat node, we call $ \ensuremath{\mathrm{size}(\ensuremath{\mathit{u}})}$ on a sequence of nodes $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}_0,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}_k$ until we find the scapegoat $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}_k=\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}$. However, since $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}_k$ is the first node in this sequence that is a scapegoat, we know that

$\displaystyle \ensuremath{\ensuremath{size}(\ensuremath{\ensuremath{\mathit{u}}...
...th{\ensuremath{size}(\ensuremath{\ensuremath{\mathit{u}}}}_{i+1}\ensuremath{)}
$

for all $ i\in\{0,\ldots,k-2\}$. Therefore, the cost of all calls to $ \ensuremath{\mathrm{size}(\ensuremath{\mathit{u}})}$ is
$\displaystyle O\left( \sum_{i=0}^k \ensuremath{\ensuremath{size}(\ensuremath{\ensuremath{\mathit{u}}}}_{k-i}\ensuremath{)} \right)$ $\displaystyle =$ $\displaystyle O\left(
\ensuremath{\ensuremath{size}(\ensuremath{\ensuremath{\ma...
...emath{size}(\ensuremath{\ensuremath{\mathit{u}}}}_{k-i-1}\ensuremath{)}
\right)$  
  $\displaystyle =$ $\displaystyle O\left(
\ensuremath{\ensuremath{size}(\ensuremath{\ensuremath{\ma...
...nsuremath{size}(\ensuremath{\ensuremath{\mathit{u}}}}_{k}\ensuremath{)}
\right)$  
  $\displaystyle =$ $\displaystyle O\left(
\ensuremath{\ensuremath{size}(\ensuremath{\ensuremath{\ma...
...nsuremath{)}\left(1+
\sum_{i=0}^{k-1} \left(\frac{2}{3}\right)^i
\right)\right)$  
  $\displaystyle =$ $\displaystyle O(\ensuremath{\ensuremath{size}(\ensuremath{\ensuremath{\mathit{u...
... O(\ensuremath{\ensuremath{\mathrm{size}(\ensuremath{\mathit{w}})}}) \enspace ,$  

where the last line follows from the fact that the sum is a geometrically decreasing series. $ \qedsymbol$

All that remains is to prove an upper-bound on the cost of all calls to $ \ensuremath{\mathrm{rebuild}(\ensuremath{\mathit{u}})}$ during a sequence of $ m$ operations:

Lemma 8..3   Starting with an empty ScapegoatTree any sequence of $ m$ $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ operations causes at most $ O(m\log m)$ time to be used by $ \ensuremath{\mathrm{rebuild}(\ensuremath{\mathit{u}})}$ operations.

Proof. To prove this, we will use a credit scheme. We imagine that each node stores a number of credits. Each credit can pay for some constant, $ c$, units of time spent rebuilding. The scheme gives out a total of $ O(m\log m)$ credits and every call to $ \ensuremath{\mathrm{rebuild}(\ensuremath{\mathit{u}})}$ is paid for with credits stored at $ \ensuremath{\ensuremath{\mathit{u}}}$.

During an insertion or deletion, we give one credit to each node on the path to the inserted node, or deleted node, $ \ensuremath{\ensuremath{\mathit{u}}}$. In this way we hand out at most $ \log_{3/2}\ensuremath{\ensuremath{\ensuremath{\mathit{q}}}}\le \log_{3/2}m$ credits per operation. During a deletion we also store an additional credit ``on the side.'' Thus, in total we give out at most $ O(m\log m)$ credits. All that remains is to show that these credits are sufficient to pay for all calls to $ \ensuremath{\mathrm{rebuild}(\ensuremath{\mathit{u}})}$.

If we call $ \ensuremath{\mathrm{rebuild}(\ensuremath{\mathit{u}})}$ during an insertion, it is because $ \ensuremath{\ensuremath{\mathit{u}}}$ is a scapegoat. Suppose, without loss of generality, that

$\displaystyle \frac{\ensuremath{\ensuremath{\mathrm{size}(\ensuremath{\mathit{u...
...ensuremath{\mathrm{size}(\ensuremath{\mathit{u}})}}} > \frac{2}{3} \enspace .
$

Using the fact that

$\displaystyle \ensuremath{\ensuremath{\mathrm{size}(\ensuremath{\mathit{u}})}} ...
...uremath{\mathrm{size}(\ensuremath{\mathit{u}}.\ensuremath{\mathit{right}})}}
$

we deduce that

$\displaystyle \frac{1}{2}\ensuremath{\ensuremath{\mathrm{size}(\ensuremath{\mat...
...mathrm{size}(\ensuremath{\mathit{u}}.\ensuremath{\mathit{right}})}} \enspace
$

and therefore

$\displaystyle \ensuremath{\ensuremath{\mathrm{size}(\ensuremath{\mathit{u}}.\en...
...3}\ensuremath{\ensuremath{\mathrm{size}(\ensuremath{\mathit{u}})}} \enspace .
$

Now, the last time a subtree containing $ \ensuremath{\ensuremath{\mathit{u}}}$ was rebuilt (or when $ \ensuremath{\ensuremath{\mathit{u}}}$ was inserted, if a subtree containing $ \ensuremath{\ensuremath{\mathit{u}}}$ was never rebuilt), we had

$\displaystyle \ensuremath{\ensuremath{\mathrm{size}(\ensuremath{\mathit{u}}.\en...
...size}(\ensuremath{\mathit{u}}.\ensuremath{\mathit{right}})}} \le 1 \enspace .
$

Therefore, the number of $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ or $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ operations that have affected $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{left}}}$ or $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{right}}}$ since then is at least

$\displaystyle \frac{1}{3}\ensuremath{\ensuremath{\mathrm{size}(\ensuremath{\mathit{u}})}} - 1 \enspace .
$

and there are therefore at least this many credits stored at $ \ensuremath{\ensuremath{\mathit{u}}}$ that are available to pay for the $ O(\ensuremath{\ensuremath{\mathrm{size}(\ensuremath{\mathit{u}})}})$ time it takes to call $ \ensuremath{\mathrm{rebuild}(\ensuremath{\mathit{u}})}$.

If we call $ \ensuremath{\mathrm{rebuild}(\ensuremath{\mathit{u}})}$ during a deletion, it is because $ \ensuremath{\ensuremath{\ensuremath{\mathit{q}}}} > 2\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$. In this case, we have $ \ensuremath{\ensuremath{\ensuremath{\mathit{q}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}> \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$ credits stored ``on the side,'' and we use these to pay for the $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ time it takes to rebuild the root. This completes the proof. $ \qedsymbol$

8.1.2 Summary

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

Theorem 8..1   A ScapegoatTree implements the SSet interface. Ignoring the cost of $ \ensuremath{\mathrm{rebuild}(\ensuremath{\mathit{u}})}$ operations, a ScapegoatTree 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}}}})$ time per operation.

Furthermore, beginning with an empty ScapegoatTree, any sequence of $ m$ $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ operations results in a total of $ O(m\log m)$ time spent during all calls to $ \ensuremath{\mathrm{rebuild}(\ensuremath{\mathit{u}})}$.

opendatastructures.org

14 . External Memory Searching

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.


14. External Memory Searching

Throughout this book, we have been using the $ \ensuremath{\ensuremath{\mathit{w}}}$-bit word-RAM model of computation defined in Section 1.4. An implicit assumption of this model is that our computer has a large enough random access memory to store all of the data in the data structure. In some situations, this assumption is not valid. There exist collections of data so large that no computer has enough memory to store them. In such cases, the application must resort to storing the data on some external storage medium such as a hard disk, a solid state disk, or even a network file server (which has its own external storage).

Accessing an item from external storage is extremely slow. The hard disk attached to the computer on which this book was written has an average access time of 19ms and the solid state drive attached to the computer has an average access time of 0.3ms. In contrast, the random access memory in the computer has an average access time of less than 0.000113ms. Accessing RAM is more than 2500 times faster than accessing the solid state drive and more than 160000 times faster than accessing the hard drive.

These speeds are fairly typical; accessing a random byte from RAM is thousands of times faster than accessing a random byte from a hard disk or solid-state drive. Access time, however, does not tell the whole story. When we access a byte from a hard disk or solid state disk, an entire block of the disk is read. Each of the drives attached to the computer has a block size of 4096; each time we read one byte, the drive gives us a block containing 4096 bytes. If we organize our data structure carefully, this means that each disk access could yield 4096 bytes that are helpful in completing whatever operation we are doing.

This is the idea behind the external memory model of computation, illustrated schematically in Figure 14.1. In this model, the computer has access to a large external memory in which all of the data resides. This memory is divided into memory blocks each containing $ B$ words. The computer also has limited internal memory on which it can perform computations. Transferring a block between internal memory and external memory takes constant time. Computations performed within the internal memory are free; they take no time at all. The fact that internal memory computations are free may seem a bit strange, but it simply emphasizes the fact that external memory is so much slower than RAM.

Figure 14.1: In the external memory model, accessing an individual item, $ \ensuremath{\ensuremath{\mathit{x}}}$, in the external memory requires reading the entire block containing $ \ensuremath{\ensuremath{\mathit{x}}}$ into RAM.
\includegraphics[width=\textwidth ]{figs-python/em}

In the full-blown external memory model, the size of the internal memory is also a parameter. However, for the data structures described in this chapter, it is sufficient to have an internal memory of size $ O(B+\log_B \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$. That is, the memory needs to be capable of storing a constant number of blocks and a recursion stack of height $ O(\log_B
\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$. In most cases, the $ O(B)$ term dominates the memory requirement. For example, even with the relatively small value $ B=32$, $ B\ge \log_B
\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$ for all $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}\le 2^{160}$. In decimal, $ B\ge \log_B \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$ for any

$\displaystyle \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}} \le 1\,461\,501...
...7\,330\,902\,918\,203\,684\,832\,716\,283\,019\,655\,932\,542\,976 \enspace
. $



Subsections
opendatastructures.org

HTML: A good basis for accessibility

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.

HTML: A good basis for accessibility

A great deal of web content can be made accessible just by making sure the correct Hypertext Markup Language elements are used for the correct purpose at all times. This article looks in detail at how HTML can be used to ensure maximum accessibility.

Prerequisites: Familiarity with HTML, CSS, a basic understanding of accessibility concepts.
Learning outcomes:
  • Use semantic HTML, aka "The right element for the right job", because the browser provides so many built-in accessibility hooks.
  • Accessible best practices such as alt text, good link text, form labels, and table row and column headings and scoping.
  • Using simple plain language, steering clear of slang and abbreviations where possible, and providing definitions where it is not possible.
  • The concept and practice of keyboard accessibility.
  • The importance of source order.

HTML and accessibility

As you learn more about HTML — read more resources, look at more examples, etc. — you'll keep seeing a common theme: the importance of using semantic HTML (sometimes called POSH, or Plain Old Semantic HTML). This means using the correct HTML elements for their intended purpose as much as possible.

You might wonder why this is so important. After all, you can use a combination of CSS and JavaScript to make just about any HTML element behave in whatever way you want. For example, a control button to play a video on your site could be marked up like this:

html
<div>Play video</div>

But as you'll see in greater detail later on, it makes sense to use the correct element for the job:

html
<button>Play video</button>

Not only do HTML <button>s have some suitable styling applied by default (which you will probably want to override), they also have built-in keyboard accessibility — users can navigate between buttons using the Tab key and activate their selection using Space, Return or Enter.

Semantic HTML doesn't take any longer to write than non-semantic (bad) markup if you do it consistently from the start of your project. Even better, semantic markup has other benefits beyond accessibility:

  1. Easier to develop with — as mentioned above, you get some functionality for free, plus it is arguably easier to understand.
  2. Better on mobile — semantic HTML is arguably lighter in file size than non-semantic spaghetti code, and easier to make responsive.
  3. Good for SEO — search engines give more importance to keywords inside headings, links, etc. than keywords included in non-semantic <div>s, etc., so your documents will be more findable by customers.

Let's get on and look at accessible HTML in more detail.

Good semantics

We've already talked about the importance of proper semantics, and why we should use the right HTML element for the job. This cannot be ignored, as it is one of the main places that accessibility is badly broken if not handled properly.

Out there on the web, the truth is that people do some very strange things with HTML markup. Often, misuse of HTML is because of legacy practices that haven't gone away yet, but sometimes it occurs because authors don't know any better. Whatever the case, you should replace bad code with good semantic markup wherever possible, in both static HTML pages and dynamically-generated HTML from server-side code or client-side JavaScript frameworks such as React.

Sometimes you are not in a position to get rid of lousy markup — your pages might be dependent on server-side code or web/framework components that you have no control over, or you might have third-party content on your page (such as ad banners).

The goal isn't "all or nothing"; every improvement you can make will help the cause of accessibility.

Use well-structured text content

One of the best accessibility aids a screen reader user can have is an excellent text structure with headings, paragraphs, lists, etc. A good semantic example might look something like the following:

html
<h1>My heading</h1>

<p>This is the first section of my document.</p>

<p>I'll add another paragraph here too.</p>

<ol>
  <li>Here is</li>
  <li>a list for</li>
  <li>you to read</li>
</ol>

<h2>My subheading</h2>

<p>
  This is the first subsection of my document. I'd love people to be able to
  find this content!
</p>

<h2>My 2nd subheading</h2>

<p>
  This is the second subsection of my content, which I think is more interesting
  than the last one.
</p>

We've prepared a version with longer text for you to try out with a screen reader (see good-semantics.html). If you try navigating through this, you'll see that this is pretty easy to navigate:

  1. The screen reader reads each header out as you progress through the content, notifying you what a heading is, what is a paragraph, etc.
  2. It stops after each element, letting you go at whatever pace is comfortable for you.
  3. You can jump to the next/previous heading in many screen readers.
  4. You can also bring up a list of all headings in many screen readers, allowing you to use them as a handy table of contents to find specific content.

People sometimes write headings, paragraphs, etc. using line breaks and adding HTML elements purely for styling, something like the following:

html
<span style="font-size: 3em">My heading</span> <br /><br />
This is the first section of my document.
<br /><br />
I'll add another paragraph here too.
<br /><br />
1. Here is
<br /><br />
2. a list for
<br /><br />
3. you to read
<br /><br />
<span style="font-size: 2.5em">My subheading</span>
<br /><br />
This is the first subsection of my document. I'd love people to be able to find
this content!
<br /><br />
<span style="font-size: 2.5em">My 2nd subheading</span>
<br /><br />
This is the second subsection of my content. I think is more interesting than
the last one.

If you try our longer version out with a screen reader (see bad-semantics.html), you'll not have a very good experience — the screen reader hasn't got anything to use as signposts, so you can't retrieve a useful table of contents, and the whole page is seen as a single giant block, so it is just read out in one go, all at once.

There are other issues too beyond accessibility — it is harder to style the content using CSS, or manipulate it with JavaScript, for example, because there are no elements to use as selectors.

Use clear language

The language you use can also affect accessibility. In general, you should use clear language that is not overly complex and doesn't use unnecessary jargon or slang terms. This not only benefits people with cognitive or other disabilities; it benefits readers for whom the text is not written in their first language, younger people…, everyone, in fact! Apart from this, you should try to avoid using language and characters that don't get read out clearly by the screen reader. For example:

  • Don't use dashes if you can avoid it. Instead of writing 5–7, write 5 to 7.
  • Expand abbreviations — instead of writing Jan, write January.
  • Expand acronyms, at least once or twice, then use the <abbr> tag to describe them.

Structure page sections logically

You should use appropriate sectioning elements to structure your webpages, for example navigation (<nav>), footer (<footer>), and repeating content units (<article>). These provide extra semantics for screen readers (and other tools) to give users extra clues about the content they are navigating.

For example, a modern content structure could look something like this:

html
<header>
  <h1>Header</h1>
</header>

<nav>
  <!-- main navigation in here -->
</nav>

<!-- Here is our page's main content -->
<main>
  <!-- It contains an article -->
  <article>
    <h2>Article heading</h2>

    <!-- article content in here -->
  </article>

  <aside>
    <h2>Related</h2>

    <!-- aside content in here -->
  </aside>
</main>

<!-- And here is our main footer that is used across all the pages of our website -->

<footer>
  <!-- footer content in here -->
</footer>

You can find a full example here.

In addition to having good semantics and an attractive layout, your content should make logical sense in its source order — you can always place it where you want using CSS later on, but you should get the source order right to start with, so what screen reader users get read out to them will make sense.

Use semantic UI controls where possible

By UI controls, we mean the main parts of web documents that users interact with — most commonly buttons, links, and form controls. In this section, we'll look at the basic accessibility concerns to be aware of when creating such controls. Later articles on WAI-ARIA and multimedia will look at other aspects of UI accessibility.

One key aspect of the accessibility of UI controls is that by default, browsers allow them to be manipulated by the keyboard. You can try this out using our native-keyboard-accessibility.html example (see the source code). Open this in a new tab, and try pressing the tab key; after a few presses, you should see the tab focus start to move through the different focusable elements. The focused elements are given a highlighted default style in every browser (it differs slightly between different browsers) so that you can tell what element is focused.

Three buttons with the text "Click me!", "Click me too!", and "And me!" inside them respectively. The third button has a blue outline around it to indicate current tab focus.

Note: You can enable an overlay that shows the page tabbing order in your developer tools. For more information see: Accessibility Inspector > Show web page tabbing order.

You can then press Enter/Return to follow a focused link or press a button (we've included some JavaScript to make the buttons alert a message), or start typing to enter text in a text input. Other form elements have different controls; for example, the <select> element can have its options displayed and cycled between using the up and down arrow keys.

You essentially get this behavior for free, just by using the appropriate elements, for example:

html
<h1>Links</h1>

<p>This is a link to <a href="https://www.mozilla.org">Mozilla</a>.</p>

<p>
  Another link, to the
  <a href="https://developer.mozilla.org">Mozilla Developer Network</a>.
</p>

<h2>Buttons</h2>

<p>
  <button data-message="This is from the first button">Click me!</button>
  <button data-message="This is from the second button">Click me too!</button>
  <button data-message="This is from the third button">And me!</button>
</p>

<h2>Form</h2>

<form>
  <div>
    <label for="name">Fill in your name:</label>
    <input type="text" id="name" name="name" />
  </div>
  <div>
    <label for="age">Enter your age:</label>
    <input type="text" id="age" name="age" />
  </div>
  <div>
    <label for="mood">Choose your mood:</label>
    <select id="mood" name="mood">
      <option>Happy</option>
      <option>Sad</option>
      <option>Angry</option>
      <option>Worried</option>
    </select>
  </div>
</form>

This means using links, buttons, form elements, and labels appropriately (including the <label> element for form controls).

However, this is another case where people sometimes do strange things with HTML. For example, you sometimes see buttons marked up using <div>s, for example:

html
<div data-message="This is from the first button">Click me!</div>
<div data-message="This is from the second button">Click me too!</div>
<div data-message="This is from the third button">And me!</div>

But using such code is not advised — you immediately lose the native keyboard accessibility you would have had if you'd just used <button> elements, plus you don't get any of the default CSS styling that buttons get. In the rare to non-existent case when you need to use a non-button element for a button, use the button role and implement all the default button behaviors, including keyboard and mouse button support.

Building keyboard accessibility back in

Adding such advantages back in takes a bit of work (you can see an example in our fake-div-buttons.html example — also see the source code). Here we've given our fake <div> buttons the ability to be focused (including via tab) by giving each one the attribute tabindex="0". We also include role="button" so screen reader users know they can focus on and interact with the element:

html
<div data-message="This is from the first button" tabindex="0" role="button">
  Click me!
</div>
<div data-message="This is from the second button" tabindex="0" role="button">
  Click me too!
</div>
<div data-message="This is from the third button" tabindex="0" role="button">
  And me!
</div>

Basically, the tabindex attribute is primarily intended to allow tabbable elements to have a custom tab order (specified in positive numerical order), instead of just being tabbed through in their default source order. This is nearly always a bad idea, as it can cause major confusion. Use it only if you really need to, for example, if the layout shows things in a very different visual order to the source code, and you want to make things work more logically. There are two other options for tabindex:

  • tabindex="0" — as indicated above, this value allows elements that are not normally tabbable to become tabbable. This is the most useful value of tabindex.
  • tabindex="-1" — this allows not normally tabbable elements to receive focus programmatically, e.g., via JavaScript, or as the target of links.

While the above addition allows us to tab to the buttons, it does not allow us to activate them via the Enter/Return key. To do that, we had to add the following bit of JavaScript:

js
document.onkeydown = (e) => {
  // The Enter/Return key
  if (e.key === "Enter") {
    document.activeElement.click();
  }
};

Here we add a listener to the document object to detect when a button has been pressed on the keyboard. We check what button was pressed via the event object's key property; if the key pressed is Enter/Return, we run the function stored in the button's onclick handler using document.activeElement.click(). activeElement which gives us the element that is currently focused on the page.

This is a lot of extra hassle to build the functionality back in. And there's bound to be other problems with it. Better to just use the right element for the right job in the first place.

Use meaningful text labels

UI control text labels are very useful to all users, but getting them right is particularly important to users with disabilities.

You should make sure that your button and link text labels are understandable and distinctive. Don't just use "Click here" for your labels, as screen reader users sometimes get up a list of buttons and form controls. The following screenshot shows our controls being listed by VoiceOver on Mac.

List of form input labels being listed by VoiceOver software on Mac. This list contains meaningless labels like 'happy menu button' given to various form controls like button, textfield and link

Make sure your labels make sense out of context, read on their own, as well as in the context of the paragraph they are in. For example, the following shows an example of good link text:

html
<p>
  Whales are really awesome creatures.
  <a href="whales.html">Find out more about whales</a>.
</p>

but this is bad link text:

html
<p>
  Whales are really awesome creatures. To find out more about whales,
  <a href="whales.html">click here</a>.
</p>

Note: You can find a lot more about link implementation and best practices in our Creating links article. You can also see some good and bad examples at good-links.html and bad-links.html.

Form labels are also important for giving you a clue about what you need to enter into each form input. The following seems like a reasonable enough example:

html
Fill in your name: <input type="text" id="name" name="name" />

However, this is not so useful for disabled users. There is nothing in the above example to associate the label unambiguously with the form input and make it clear how to fill it in if you cannot see it. If you access this with some screen readers, you may only be given a description along the lines of "edit text."

The following is a much better example:

html
<div>
  <label for="name">Fill in your name:</label>
  <input type="text" id="name" name="name" />
</div>

With code like this, the label will be clearly associated with the input; the description will be more like "Fill in your name: edit text."

A good form label that reads 'Fill in your name' is given to a text input form control.

As an added bonus, in most browsers associating a label with a form input means that you can click the label to select or activate the form element. This gives the input a bigger hit area, making it easier to select.

Note: You can see some good and bad form examples in good-form.html and bad-form.html.

You can find a nice explanation of the importance of proper text labels, and how to investigate text label issues using the Firefox Accessibility Inspector, in the following video:

Accessible data tables

A basic data table can be written with very simple markup, for example:

html
<table>
  <tr>
    <td>Name</td>
    <td>Age</td>
    <td>Pronouns</td>
  </tr>
  <tr>
    <td>Xavier</td>
    <td>23</td>
    <td>he/him</td>
  </tr>
  <tr>
    <td>Tina</td>
    <td>8</td>
    <td>she/her</td>
  </tr>
  <tr>
    <td>Sam</td>
    <td>17</td>
    <td>she/her</td>
  </tr>
</table>

But this has problems — there is no way for a screen reader user to associate rows or columns together as groupings of data. To do this, you need to know what the header rows are and if they are heading up rows, columns, etc. This can only be done visually for the above table (see bad-table.html and try the example out yourself).

Now have a look at our punk bands table example — you can see a few accessibility aids at work here:

  • Table headers are defined using <th> elements — you can also specify if they are headers for rows or columns using the scope attribute. This gives you complete groups of data that can be consumed by screen readers as single units.
  • The <caption> element and the <table> element's summary attribute both do similar jobs — they act as alt text for a table, giving a screen reader user a useful quick summary of the table's contents. The <caption> element is generally preferred as it makes its content accessible to sighted users too, who might also find it useful. You don't really need both.

Note: See our HTML table accessibility article for more details about accessible data tables.

Text alternatives

Whereas textual content is inherently accessible, the same cannot necessarily be said for multimedia content — image and video content cannot be seen by visually-impaired people, and audio content cannot be heard by hearing-impaired people. We cover video and audio content in detail in the Accessible multimedia, but for this article we'll look at accessibility for the humble <img> element.

We have a simple example written up, accessible-image.html, which features four copies of the same image:

html
<img src="dinosaur.png" />

<img
  src="dinosaur.png"
  alt="A red Tyrannosaurus Rex: A two legged dinosaur standing upright like a human, with small arms, and a large head with lots of sharp teeth." />

<img
  src="dinosaur.png"
  alt="A red Tyrannosaurus Rex: A two legged dinosaur standing upright like a human, with small arms, and a large head with lots of sharp teeth."
  title="The Mozilla red dinosaur" />

<img src="dinosaur.png" aria-labelledby="dino-label" />

<p id="dino-label">
  The Mozilla red Tyrannosaurus Rex: A two legged dinosaur standing upright like
  a human, with small arms, and a large head with lots of sharp teeth.
</p>

The first image, when viewed by a screen reader, doesn't really offer the user much help — VoiceOver for example reads out "/dinosaur.png, image". It reads out the filename to try to provide some help. In this example the user will at least know it is a dinosaur of some kind, but often files may be uploaded with machine-generated file names (e.g., from a digital camera) and these file names would likely provide no context to the image's content.

Note: This is why you should never include text content inside an image — screen readers can't access it. There are other disadvantages too — you can't select it and copy/paste it. Just don't do it!

When a screen reader encounters the second image, it reads out the full alt attribute — "A red Tyrannosaurus Rex: A two legged dinosaur standing upright like a human, with small arms, and a large head with lots of sharp teeth.".

This highlights the importance of not only using meaningful file names in case so-called alt text is not available, but also making sure that alt text is provided in alt attributes wherever possible.

Note that the contents of the alt attribute should always provide a direct representation of the image and what it conveys visually. The alt should be brief and concise and include all the information conveyed in the image that is not duplicated in the surrounding text.

The content of the alt attribute for a single image differs based on the context. For example, if the photo of Fluffy is an avatar next to a review for Yuckymeat dog food, alt="Fluffy" is appropriate. If the photo is part of Fluffy's adoption page for the animal rescue society, information conveyed in the image that is relevant for a prospective dog parent that is not duplicated in the surrounding text should be included. A longer description, such as alt="Fluffy, a tri-color terrier with very short hair, with a tennis ball in her mouth." is appropriate. As the surrounding text likely has Fluffy's size and breed, that is not included in the alt. However, as the dog's biography likely doesn't include hair length, colors, or toy preferences, which the potential parent needs to know, it is included. Is the image outdoors, or does Fluffy have a red collar with a blue leash? Not important in terms of adopting the pet and therefore not included. All information image conveys that a sighted user can access and is relevant to the context is what needs to be conveyed; nothing more. Keep it short, precise, and useful.

Any personal knowledge or extra description shouldn't be included here, as it is not useful for people who have not seen the image before. If the ball is Fluffy's favorite toy or if a sighted user can't know that from the image, then don't include it.

One thing to consider is whether your images have meaning inside your content, or whether they are purely for visual decoration, and thus have no meaning. If they are decorative, it is better to write an empty text as a value for alt attribute (see Empty alt attributes) or to just include them in the page as CSS background images.

Note: Read HTML images and Responsive images for a lot more information about image implementation and best practices. You can also check An alt Decision Tree to learn how to use an alt attribute for images in various situations.

If you do want to provide extra contextual information, you should put it in the text surrounding the image, or inside a title attribute, as shown above. In this case, most screen readers will read out the alt text, the title attribute, and the filename. In addition, browsers display title text as tooltips when moused over.

Screenshot of a red Tyrannosaurus Rex with the text "The mozilla red dinosaur" displayed as tooltip on mouseover.

Let's have another quick look at the fourth method:

html
<img src="dinosaur.png" aria-labelledby="dino-label" />

<p id="dino-label">The Mozilla red Tyrannosaurus…</p>

In this case, we are not using the alt attribute at all — instead, we have presented our description of the image as a regular text paragraph, given it an id, and then used the aria-labelledby attribute to refer to that id, which causes screen readers to use that paragraph as the alt text/label for that image. This is especially useful if you want to use the same text as a label for multiple images — something that isn't possible with alt.

Note: aria-labelledby is part of the WAI-ARIA spec, which allows developers to add in extra semantics to their markup to improve screen reader accessibility where needed.

Figures and figure captions

HTML includes two elements — <figure> and <figcaption> — which associate a figure of some kind (it could be anything, not necessarily an image) with a figure caption:

html
<figure>
  <img
    src="dinosaur.png"
    alt="The Mozilla Tyrannosaurus"
    aria-describedby="dinodescr" />
  <figcaption id="dinodescr">
    A red Tyrannosaurus Rex: A two legged dinosaur standing upright like a
    human, with small arms, and a large head with lots of sharp teeth.
  </figcaption>
</figure>

While there is mixed screen reader support of associating figure captions with their figures, including aria-labelledby or aria-describedby creates the association if none is present. That said, the element structure is useful for CSS styling, plus it provides a way to place a description of the image next to it in the source.

Empty alt attributes

html
<h3>
  <img src="article-icon.png" alt="" />
  Tyrannosaurus Rex: the king of the dinosaurs
</h3>

There may be times where an image is included in a page's design, but its primary purpose is for visual decoration. You'll notice in the code example above that the image's alt attribute is empty — this is to make screen readers recognize the image, but not attempt to describe the image (instead they'd just say "image", or similar).

The reason to use an empty alt instead of not including it is because many screen readers announce the whole image URL if no alt is provided. In the above example, the image is acting as a visual decoration to the heading it's associated with. In cases like this, and in cases where an image is only decoration and has no content value, you should include an empty alt in your img elements. Another alternative is to use the aria role attribute role="presentation" as this also stops screen readers from reading out alternative text.

Note: If possible you should use CSS to display images that are only decorative.

Links (the <a> element with an href attribute), depending on how they are used, can help or harm accessibility. By default, links are accessible in appearance. They can improve accessibility by helping a user quickly navigate to different sections of a document. They can also harm accessibility if their accessible styling is removed or if JavaScript causes them to behave in unexpected ways.

By default, links are visually different from other text in both color and text-decoration, with links being blue and underlined by default, purple and underlined if visited, and with a focus-ring when they receive keyboard focus.

Color should not be used as the sole method of distinguishing links from non-linking content. Link text color, like all text, has to be significantly different from the background color (a 4.5:1 contrast). In addition, links should visually be significantly different from non-linking text, with a minimum contrast requirement of 3:1 between link text and surrounding text and between default, visited, and focus/active states and a 4.5:1 contrast between all those state colors and the background color.

onclick events

Anchor tags are often abused with the onclick event to create pseudo-buttons by setting href to "#" or "javascript:void(0)" to prevent the page from refreshing.

These values cause unexpected behavior when copying or dragging links, opening links in a new tab or window, bookmarking, and when JavaScript is still downloading, errors out, or is disabled. This also conveys incorrect semantics to assistive technologies (e.g., screen readers). In these cases, it is recommended to use a <button> instead. In general you should only use an anchor for navigation using a proper URL.

Links that open in a new tab or window via the target="_blank" declaration and links to whose href value points to a file resource should include an indicator about the behavior that will occur when the link is activated.

People experiencing low vision conditions, who are navigating with the aid of screen reading technology, or who have cognitive concerns may become confused when the new tab, window, or application is opened unexpectedly. Older versions of screen reading software may not even announce the behavior.

html
<a target="_blank" href="https://www.wikipedia.org/"
  >Wikipedia (opens in a new window)</a
>
html
<a target="_blank" href="2017-annual-report.ppt"
  >2017 Annual Report (PowerPoint)</a
>

If an icon is used in place of text to signify this kind of links behavior, make sure it includes an alternate description.

A skip link, also known as skipnav, is an a element placed as close as possible to the opening <body> element that links to the beginning of the page's main content. This link allows people to bypass content repeated throughout multiple pages on a website, such as a website's header and primary navigation.

Skip links are especially useful for people who navigate with the aid of assistive technology such as switch control, voice command, or mouth sticks/head wands, where the act of moving through repetitive links can be a laborious task.

Proximity

Large amounts of interactive content—including anchors—placed in close visual proximity to each other should have space inserted to separate them. This spacing is beneficial for people who suffer from fine motor control issues and may accidentally activate the wrong interactive content while navigating.

Spacing may be created using CSS properties such as margin.

Summary

You should now be well-versed in writing accessible HTML for most occasions. In the next article, we'll give you some tests that you can use to check how well you've understood and retained all this information.

2.7. Aggregate Functions #

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.7. Aggregate Functions #

Like most other relational database products, PostgreSQL supports aggregate functions. An aggregate function computes a single result from multiple input rows. For example, there are aggregates to compute the count, sum, avg (average), max (maximum) and min (minimum) over a set of rows.

As an example, we can find the highest low-temperature reading anywhere with:

SELECT max(temp_lo) FROM weather;
 max
-----
  46
(1 row)

If we wanted to know what city (or cities) that reading occurred in, we might try:

SELECT city FROM weather WHERE temp_lo = max(temp_lo);     -- WRONG

but this will not work since the aggregate max cannot be used in the WHERE clause. (This restriction exists because the WHERE clause determines which rows will be included in the aggregate calculation; so obviously it has to be evaluated before aggregate functions are computed.) However, as is often the case the query can be restated to accomplish the desired result, here by using a subquery:

SELECT city FROM weather
    WHERE temp_lo = (SELECT max(temp_lo) FROM weather);
     city
---------------
 San Francisco
(1 row)

This is OK because the subquery is an independent computation that computes its own aggregate separately from what is happening in the outer query.

Aggregates are also very useful in combination with GROUP BY clauses. For example, we can get the number of readings and the maximum low temperature observed in each city with:

SELECT city, count(*), max(temp_lo)
    FROM weather
    GROUP BY city;
     city      | count | max
---------------+-------+-----
 Hayward       |     1 |  37
 San Francisco |     2 |  46
(2 rows)

which gives us one output row per city. Each aggregate result is computed over the table rows matching that city. We can filter these grouped rows using HAVING:

SELECT city, count(*), max(temp_lo)
    FROM weather
    GROUP BY city
    HAVING max(temp_lo) < 40;
  city   | count | max
---------+-------+-----
 Hayward |     1 |  37
(1 row)

which gives us the same results for only the cities that have all temp_lo values below 40. Finally, if we only care about cities whose names begin with “S”, we might do:

SELECT city, count(*), max(temp_lo)
    FROM weather
    WHERE city LIKE 'S%'            -- (1)
    GROUP BY city;
     city      | count | max
---------------+-------+-----
 San Francisco |     2 |  46
(1 row)

(1)

The LIKE operator does pattern matching and is explained in Section 9.7.

It is important to understand the interaction between aggregates and SQL's WHERE and HAVING clauses. The fundamental difference between WHERE and HAVING is this: WHERE selects input rows before groups and aggregates are computed (thus, it controls which rows go into the aggregate computation), whereas HAVING selects group rows after groups and aggregates are computed. Thus, the WHERE clause must not contain aggregate functions; it makes no sense to try to use an aggregate to determine which rows will be inputs to the aggregates. On the other hand, the HAVING clause always contains aggregate functions. (Strictly speaking, you are allowed to write a HAVING clause that doesn't use aggregates, but it's seldom useful. The same condition could be used more efficiently at the WHERE stage.)

In the previous example, we can apply the city name restriction in WHERE, since it needs no aggregate. This is more efficient than adding the restriction to HAVING, because we avoid doing the grouping and aggregate calculations for all rows that fail the WHERE check.

Another way to select the rows that go into an aggregate computation is to use FILTER, which is a per-aggregate option:

SELECT city, count(*) FILTER (WHERE temp_lo < 45), max(temp_lo)
    FROM weather
    GROUP BY city;
     city      | count | max
---------------+-------+-----
 Hayward       |     1 |  37
 San Francisco |     1 |  46
(2 rows)

FILTER is much like WHERE, except that it removes rows only from the input of the particular aggregate function that it is attached to. Here, the count aggregate counts only rows with temp_lo below 45; but the max aggregate is still applied to all rows, so it still finds the reading of 46.

5.7. Modifying Tables #

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.

5.7. Modifying Tables #

When you create a table and you realize that you made a mistake, or the requirements of the application change, you can drop the table and create it again. But this is not a convenient option if the table is already filled with data, or if the table is referenced by other database objects (for instance a foreign key constraint). Therefore PostgreSQL provides a family of commands to make modifications to existing tables. Note that this is conceptually distinct from altering the data contained in the table: here we are interested in altering the definition, or structure, of the table.

You can:

  • Add columns

  • Remove columns

  • Add constraints

  • Remove constraints

  • Change default values

  • Change column data types

  • Rename columns

  • Rename tables

All these actions are performed using the ALTER TABLE command, whose reference page contains details beyond those given here.

5.7.1. Adding a Column #

To add a column, use a command like:

ALTER TABLE products ADD COLUMN description text;

The new column is initially filled with whatever default value is given (null if you don't specify a DEFAULT clause).

Tip

Adding a column with a constant default value does not require each row of the table to be updated when the ALTER TABLE statement is executed. Instead, the default value will be returned the next time the row is accessed, and applied when the table is rewritten, making the ALTER TABLE very fast even on large tables.

If the default value is volatile (e.g., clock_timestamp()) each row will need to be updated with the value calculated at the time ALTER TABLE is executed. To avoid a potentially lengthy update operation, particularly if you intend to fill the column with mostly nondefault values anyway, it may be preferable to add the column with no default, insert the correct values using UPDATE, and then add any desired default as described below.

You can also define constraints on the column at the same time, using the usual syntax:

ALTER TABLE products ADD COLUMN description text CHECK (description <> '');

In fact all the options that can be applied to a column description in CREATE TABLE can be used here. Keep in mind however that the default value must satisfy the given constraints, or the ADD will fail. Alternatively, you can add constraints later (see below) after you've filled in the new column correctly.

5.7.2. Removing a Column #

To remove a column, use a command like:

ALTER TABLE products DROP COLUMN description;

Whatever data was in the column disappears. Table constraints involving the column are dropped, too. However, if the column is referenced by a foreign key constraint of another table, PostgreSQL will not silently drop that constraint. You can authorize dropping everything that depends on the column by adding CASCADE:

ALTER TABLE products DROP COLUMN description CASCADE;

See Section 5.15 for a description of the general mechanism behind this.

5.7.3. Adding a Constraint #

To add a constraint, the table constraint syntax is used. For example:

ALTER TABLE products ADD CHECK (name <> '');
ALTER TABLE products ADD CONSTRAINT some_name UNIQUE (product_no);
ALTER TABLE products ADD FOREIGN KEY (product_group_id) REFERENCES product_groups;

To add a not-null constraint, which is normally not written as a table constraint, this special syntax is available:

ALTER TABLE products ALTER COLUMN product_no SET NOT NULL;

This command silently does nothing if the column already has a not-null constraint.

The constraint will be checked immediately, so the table data must satisfy the constraint before it can be added.

5.7.4. Removing a Constraint #

To remove a constraint you need to know its name. If you gave it a name then that's easy. Otherwise the system assigned a generated name, which you need to find out. The psql command \d tablename can be helpful here; other interfaces might also provide a way to inspect table details. Then the command is:

ALTER TABLE products DROP CONSTRAINT some_name;

As with dropping a column, you need to add CASCADE if you want to drop a constraint that something else depends on. An example is that a foreign key constraint depends on a unique or primary key constraint on the referenced column(s).

Simplified syntax is available to drop a not-null constraint:

ALTER TABLE products ALTER COLUMN product_no DROP NOT NULL;

This mirrors the SET NOT NULL syntax for adding a not-null constraint. This command will silently do nothing if the column does not have a not-null constraint. (Recall that a column can have at most one not-null constraint, so it is never ambiguous which constraint this command acts on.)

5.7.5. Changing a Column's Default Value #

To set a new default for a column, use a command like:

ALTER TABLE products ALTER COLUMN price SET DEFAULT 7.77;

Note that this doesn't affect any existing rows in the table, it just changes the default for future INSERT commands.

To remove any default value, use:

ALTER TABLE products ALTER COLUMN price DROP DEFAULT;

This is effectively the same as setting the default to null. As a consequence, it is not an error to drop a default where one hadn't been defined, because the default is implicitly the null value.

5.7.6. Changing a Column's Data Type #

To convert a column to a different data type, use a command like:

ALTER TABLE products ALTER COLUMN price TYPE numeric(10,2);

This will succeed only if each existing entry in the column can be converted to the new type by an implicit cast. If a more complex conversion is needed, you can add a USING clause that specifies how to compute the new values from the old.

PostgreSQL will attempt to convert the column's default value (if any) to the new type, as well as any constraints that involve the column. But these conversions might fail, or might produce surprising results. It's often best to drop any constraints on the column before altering its type, and then add back suitably modified constraints afterwards.

5.7.7. Renaming a Column #

To rename a column:

ALTER TABLE products RENAME COLUMN product_no TO product_number;

5.7.8. Renaming a Table #

To rename a table:

ALTER TABLE products RENAME TO items;

22.7. Maximum Likelihood 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.7. Maximum Likelihood
Open the notebook in SageMaker Studio Lab

One of the most commonly encountered way of thinking in machine learning is the maximum likelihood point of view. This is the concept that when working with a probabilistic model with unknown parameters, the parameters which make the data have the highest probability are the most likely ones.

22.7.1. The Maximum Likelihood Principle

This has a Bayesian interpretation which can be helpful to think about. Suppose that we have a model with parameters \(\boldsymbol{\theta}\) and a collection of data examples \(X\). For concreteness, we can imagine that \(\boldsymbol{\theta}\) is a single value representing the probability that a coin comes up heads when flipped, and \(X\) is a sequence of independent coin flips. We will look at this example in depth later.

If we want to find the most likely value for the parameters of our model, that means we want to find

(22.7.1)\[\mathop{\mathrm{argmax}} P(\boldsymbol{\theta}\mid X).\]

By Bayes’ rule, this is the same thing as

(22.7.2)\[\mathop{\mathrm{argmax}} \frac{P(X \mid \boldsymbol{\theta})P(\boldsymbol{\theta})}{P(X)}.\]

The expression \(P(X)\), a parameter agnostic probability of generating the data, does not depend on \(\boldsymbol{\theta}\) at all, and so can be dropped without changing the best choice of \(\boldsymbol{\theta}\). Similarly, we may now posit that we have no prior assumption on which set of parameters are better than any others, so we may declare that \(P(\boldsymbol{\theta})\) does not depend on theta either! This, for instance, makes sense in our coin flipping example where the probability it comes up heads could be any value in \([0,1]\) without any prior belief it is fair or not (often referred to as an uninformative prior). Thus we see that our application of Bayes’ rule shows that our best choice of \(\boldsymbol{\theta}\) is the maximum likelihood estimate for \(\boldsymbol{\theta}\):

(22.7.3)\[\hat{\boldsymbol{\theta}} = \mathop{\mathrm{argmax}} _ {\boldsymbol{\theta}} P(X \mid \boldsymbol{\theta}).\]

As a matter of common terminology, the probability of the data given the parameters (\(P(X \mid \boldsymbol{\theta})\)) is referred to as the likelihood.

22.7.1.1. A Concrete Example

Let’s see how this works in a concrete example. Suppose that we have a single parameter \(\theta\) representing the probability that a coin flip is heads. Then the probability of getting a tails is \(1-\theta\), and so if our observed data \(X\) is a sequence with \(n_H\) heads and \(n_T\) tails, we can use the fact that independent probabilities multiply to see that

(22.7.4)\[P(X \mid \theta) = \theta^{n_H}(1-\theta)^{n_T}.\]

If we flip \(13\) coins and get the sequence “HHHTHTTHHHHHT”, which has \(n_H = 9\) and \(n_T = 4\), we see that this is

(22.7.5)\[P(X \mid \theta) = \theta^9(1-\theta)^4.\]

One nice thing about this example will be that we know the answer going in. Indeed, if we said verbally, “I flipped 13 coins, and 9 came up heads, what is our best guess for the probability that the coin comes us heads?,” everyone would correctly guess \(9/13\). What this maximum likelihood method will give us is a way to get that number from first principals in a way that will generalize to vastly more complex situations.

For our example, the plot of \(P(X \mid \theta)\) is as follows:

%matplotlib inline
import torch
from d2l import torch as d2l

theta = torch.arange(0, 1, 0.001)
p = theta**9 * (1 - theta)**4.

d2l.plot(theta, p, 'theta', 'likelihood')
../_images/output_maximum-likelihood_907113_3_0.svg

This has its maximum value somewhere near our expected \(9/13 \approx 0.7\ldots\). To see if it is exactly there, we can turn to calculus. Notice that at the maximum, the gradient of the function is flat. Thus, we could find the maximum likelihood estimate (22.7.1) by finding the values of \(\theta\) where the derivative is zero, and finding the one that gives the highest probability. We compute:

(22.7.6)\[\begin{split}\begin{aligned} 0 & = \frac{d}{d\theta} P(X \mid \theta) \\ & = \frac{d}{d\theta} \theta^9(1-\theta)^4 \\ & = 9\theta^8(1-\theta)^4 - 4\theta^9(1-\theta)^3 \\ & = \theta^8(1-\theta)^3(9-13\theta). \end{aligned}\end{split}\]

This has three solutions: \(0\), \(1\) and \(9/13\). The first two are clearly minima, not maxima as they assign probability \(0\) to our sequence. The final value does not assign zero probability to our sequence, and thus must be the maximum likelihood estimate \(\hat \theta = 9/13\).

22.7.2. Numerical Optimization and the Negative Log-Likelihood

The previous example is nice, but what if we have billions of parameters and data examples?

First, notice that if we make the assumption that all the data examples are independent, we can no longer practically consider the likelihood itself as it is a product of many probabilities. Indeed, each probability is in \([0,1]\), say typically of value about \(1/2\), and the product of \((1/2)^{1000000000}\) is far below machine precision. We cannot work with that directly.

However, recall that the logarithm turns products to sums, in which case

(22.7.7)\[\log((1/2)^{1000000000}) = 1000000000\cdot\log(1/2) \approx -301029995.6\ldots\]

This number fits perfectly within even a single precision \(32\)-bit float. Thus, we should consider the log-likelihood, which is

(22.7.8)\[\log(P(X \mid \boldsymbol{\theta})).\]

Since the function \(x \mapsto \log(x)\) is increasing, maximizing the likelihood is the same thing as maximizing the log-likelihood. Indeed in Section 22.9 we will see this reasoning applied when working with the specific example of the naive Bayes classifier.

We often work with loss functions, where we wish to minimize the loss. We may turn maximum likelihood into the minimization of a loss by taking \(-\log(P(X \mid \boldsymbol{\theta}))\), which is the negative log-likelihood.

To illustrate this, consider the coin flipping problem from before, and pretend that we do not know the closed form solution. We may compute that

(22.7.9)\[-\log(P(X \mid \boldsymbol{\theta})) = -\log(\theta^{n_H}(1-\theta)^{n_T}) = -(n_H\log(\theta) + n_T\log(1-\theta)).\]

This can be written into code, and freely optimized even for billions of coin flips.

# Set up our data
n_H = 8675309
n_T = 256245

# Initialize our paramteres
theta = torch.tensor(0.5, requires_grad=True)

# Perform gradient descent
lr = 1e-9
for iter in range(100):
    loss = -(n_H * torch.log(theta) + n_T * torch.log(1 - theta))
    loss.backward()
    with torch.no_grad():
        theta -= lr * theta.grad
    theta.grad.zero_()

# Check output
theta, n_H / (n_H + n_T)
(tensor(0.9713, requires_grad=True), 0.9713101437890875)

Numerical convenience is not the only reason why people like to use negative log-likelihoods. There are several other reasons why it is preferable.

The second reason we consider the log-likelihood is the simplified application of calculus rules. As discussed above, due to independence assumptions, most probabilities we encounter in machine learning are products of individual probabilities.

(22.7.10)\[P(X\mid\boldsymbol{\theta}) = p(x_1\mid\boldsymbol{\theta})\cdot p(x_2\mid\boldsymbol{\theta})\cdots p(x_n\mid\boldsymbol{\theta}).\]

This means that if we directly apply the product rule to compute a derivative we get

(22.7.11)\[\begin{split}\begin{aligned} \frac{\partial}{\partial \boldsymbol{\theta}} P(X\mid\boldsymbol{\theta}) & = \left(\frac{\partial}{\partial \boldsymbol{\theta}}P(x_1\mid\boldsymbol{\theta})\right)\cdot P(x_2\mid\boldsymbol{\theta})\cdots P(x_n\mid\boldsymbol{\theta}) \\ & \quad + P(x_1\mid\boldsymbol{\theta})\cdot \left(\frac{\partial}{\partial \boldsymbol{\theta}}P(x_2\mid\boldsymbol{\theta})\right)\cdots P(x_n\mid\boldsymbol{\theta}) \\ & \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \vdots \\ & \quad + P(x_1\mid\boldsymbol{\theta})\cdot P(x_2\mid\boldsymbol{\theta}) \cdots \left(\frac{\partial}{\partial \boldsymbol{\theta}}P(x_n\mid\boldsymbol{\theta})\right). \end{aligned}\end{split}\]

This requires \(n(n-1)\) multiplications, along with \((n-1)\) additions, so it is proportional to quadratic time in the inputs! Sufficient cleverness in grouping terms will reduce this to linear time, but it requires some thought. For the negative log-likelihood we have instead

(22.7.12)\[-\log\left(P(X\mid\boldsymbol{\theta})\right) = -\log(P(x_1\mid\boldsymbol{\theta})) - \log(P(x_2\mid\boldsymbol{\theta})) \cdots - \log(P(x_n\mid\boldsymbol{\theta})),\]

which then gives

(22.7.13)\[- \frac{\partial}{\partial \boldsymbol{\theta}} \log\left(P(X\mid\boldsymbol{\theta})\right) = \frac{1}{P(x_1\mid\boldsymbol{\theta})}\left(\frac{\partial}{\partial \boldsymbol{\theta}}P(x_1\mid\boldsymbol{\theta})\right) + \cdots + \frac{1}{P(x_n\mid\boldsymbol{\theta})}\left(\frac{\partial}{\partial \boldsymbol{\theta}}P(x_n\mid\boldsymbol{\theta})\right).\]

This requires only \(n\) divides and \(n-1\) sums, and thus is linear time in the inputs.

The third and final reason to consider the negative log-likelihood is the relationship to information theory, which we will discuss in detail in Section 22.11. This is a rigorous mathematical theory which gives a way to measure the degree of information or randomness in a random variable. The key object of study in that field is the entropy which is

(22.7.14)\[H(p) = -\sum_{i} p_i \log_2(p_i),\]

which measures the randomness of a source. Notice that this is nothing more than the average \(-\log\) probability, and thus if we take our negative log-likelihood and divide by the number of data examples, we get a relative of entropy known as cross-entropy. This theoretical interpretation alone would be sufficiently compelling to motivate reporting the average negative log-likelihood over the dataset as a way of measuring model performance.

22.7.3. Maximum Likelihood for Continuous Variables

Everything that we have done so far assumes we are working with discrete random variables, but what if we want to work with continuous ones?

The short summary is that nothing at all changes, except we replace all the instances of the probability with the probability density. Recalling that we write densities with lower case \(p\), this means that for example we now say

(22.7.15)\[-\log\left(p(X\mid\boldsymbol{\theta})\right) = -\log(p(x_1\mid\boldsymbol{\theta})) - \log(p(x_2\mid\boldsymbol{\theta})) \cdots - \log(p(x_n\mid\boldsymbol{\theta})) = -\sum_i \log(p(x_i \mid \theta)).\]

The question becomes, “Why is this OK?” After all, the reason we introduced densities was because probabilities of getting specific outcomes themselves was zero, and thus is not the probability of generating our data for any set of parameters zero?

Indeed, this is the case, and understanding why we can shift to densities is an exercise in tracing what happens to the epsilons.

Let’s first re-define our goal. Suppose that for continuous random variables we no longer want to compute the probability of getting exactly the right value, but instead matching to within some range \(\epsilon\). For simplicity, we assume our data is repeated observations \(x_1, \ldots, x_N\) of identically distributed random variables \(X_1, \ldots, X_N\). As we have seen previously, this can be written as

(22.7.16)\[\begin{split}\begin{aligned} &P(X_1 \in [x_1, x_1+\epsilon], X_2 \in [x_2, x_2+\epsilon], \ldots, X_N \in [x_N, x_N+\epsilon]\mid\boldsymbol{\theta}) \\ \approx &\epsilon^Np(x_1\mid\boldsymbol{\theta})\cdot p(x_2\mid\boldsymbol{\theta}) \cdots p(x_n\mid\boldsymbol{\theta}). \end{aligned}\end{split}\]

Thus, if we take negative logarithms of this we obtain

(22.7.17)\[\begin{split}\begin{aligned} &-\log(P(X_1 \in [x_1, x_1+\epsilon], X_2 \in [x_2, x_2+\epsilon], \ldots, X_N \in [x_N, x_N+\epsilon]\mid\boldsymbol{\theta})) \\ \approx & -N\log(\epsilon) - \sum_{i} \log(p(x_i\mid\boldsymbol{\theta})). \end{aligned}\end{split}\]

If we examine this expression, the only place that the \(\epsilon\) occurs is in the additive constant \(-N\log(\epsilon)\). This does not depend on the parameters \(\boldsymbol{\theta}\) at all, so the optimal choice of \(\boldsymbol{\theta}\) does not depend on our choice of \(\epsilon\)! If we demand four digits or four-hundred, the best choice of \(\boldsymbol{\theta}\) remains the same, thus we may freely drop the epsilon to see that what we want to optimize is

(22.7.18)\[- \sum_{i} \log(p(x_i\mid\boldsymbol{\theta})).\]

Thus, we see that the maximum likelihood point of view can operate with continuous random variables as easily as with discrete ones by replacing the probabilities with probability densities.

22.7.4. Summary

  • The maximum likelihood principle tells us that the best fit model for a given dataset is the one that generates the data with the highest probability.

  • Often people work with the negative log-likelihood instead for a variety of reasons: numerical stability, conversion of products to sums (and the resulting simplification of gradient computations), and theoretical ties to information theory.

  • While simplest to motivate in the discrete setting, it may be freely generalized to the continuous setting as well by maximizing the probability density assigned to the datapoints.

22.7.5. Exercises

  1. Suppose that you know that a non-negative random variable has density \(\alpha e^{-\alpha x}\) for some value \(\alpha>0\). You obtain a single observation from the random variable which is the number \(3\). What is the maximum likelihood estimate for \(\alpha\)?

  2. Suppose that you have a dataset of samples \(\{x_i\}_{i=1}^N\) drawn from a Gaussian with unknown mean, but variance \(1\). What is the maximum likelihood estimate for the mean?

3.1. Cross-validation: evaluating estimator performance

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.1. Cross-validation: evaluating estimator performance

Learning the parameters of a prediction function and testing it on the same data is a methodological mistake: a model that would just repeat the labels of the samples that it has just seen would have a perfect score but would fail to predict anything useful on yet-unseen data. This situation is called overfitting. To avoid it, it is common practice when performing a (supervised) machine learning experiment to hold out part of the available data as a test set X_test, y_test. Note that the word “experiment” is not intended to denote academic use only, because even in commercial settings machine learning usually starts out experimentally. Here is a flowchart of typical cross validation workflow in model training. The best parameters can be determined by grid search techniques.

Grid Search Workflow

In scikit-learn a random split into training and test sets can be quickly computed with the train_test_split helper function. Let’s load the iris data set to fit a linear support vector machine on it:

>>> import numpy as np
>>> from sklearn.model_selection import train_test_split
>>> from sklearn import datasets
>>> from sklearn import svm

>>> X, y = datasets.load_iris(return_X_y=True)
>>> X.shape, y.shape
((150, 4), (150,))

We can now quickly sample a training set while holding out 40% of the data for testing (evaluating) our classifier:

>>> X_train, X_test, y_train, y_test = train_test_split(
...     X, y, test_size=0.4, random_state=0)

>>> X_train.shape, y_train.shape
((90, 4), (90,))
>>> X_test.shape, y_test.shape
((60, 4), (60,))

>>> clf = svm.SVC(kernel='linear', C=1).fit(X_train, y_train)
>>> clf.score(X_test, y_test)
0.96

When evaluating different settings (“hyperparameters”) for estimators, such as the C setting that must be manually set for an SVM, there is still a risk of overfitting on the test set because the parameters can be tweaked until the estimator performs optimally. This way, knowledge about the test set can “leak” into the model and evaluation metrics no longer report on generalization performance. To solve this problem, yet another part of the dataset can be held out as a so-called “validation set”: training proceeds on the training set, after which evaluation is done on the validation set, and when the experiment seems to be successful, final evaluation can be done on the test set.

However, by partitioning the available data into three sets, we drastically reduce the number of samples which can be used for learning the model, and the results can depend on a particular random choice for the pair of (train, validation) sets.

A solution to this problem is a procedure called cross-validation (CV for short). A test set should still be held out for final evaluation, but the validation set is no longer needed when doing CV. In the basic approach, called k-fold CV, the training set is split into k smaller sets (other approaches are described below, but generally follow the same principles). The following procedure is followed for each of the k “folds”:

  • A model is trained using \(k-1\) of the folds as training data;

  • the resulting model is validated on the remaining part of the data (i.e., it is used as a test set to compute a performance measure such as accuracy).

The performance measure reported by k-fold cross-validation is then the average of the values computed in the loop. This approach can be computationally expensive, but does not waste too much data (as is the case when fixing an arbitrary validation set), which is a major advantage in problems such as inverse inference where the number of samples is very small.

A depiction of a 5 fold cross validation on a training set, while holding out a test set.

3.1.1. Computing cross-validated metrics

The simplest way to use cross-validation is to call the cross_val_score helper function on the estimator and the dataset.

The following example demonstrates how to estimate the accuracy of a linear kernel support vector machine on the iris dataset by splitting the data, fitting a model and computing the score 5 consecutive times (with different splits each time):

>>> from sklearn.model_selection import cross_val_score
>>> clf = svm.SVC(kernel='linear', C=1, random_state=42)
>>> scores = cross_val_score(clf, X, y, cv=5)
>>> scores
array([0.96, 1. , 0.96, 0.96, 1. ])

The mean score and the standard deviation are hence given by:

>>> print("%0.2f accuracy with a standard deviation of %0.2f" % (scores.mean(), scores.std()))
0.98 accuracy with a standard deviation of 0.02

By default, the score computed at each CV iteration is the score method of the estimator. It is possible to change this by using the scoring parameter:

>>> from sklearn import metrics
>>> scores = cross_val_score(
...     clf, X, y, cv=5, scoring='f1_macro')
>>> scores
array([0.96, 1., 0.96, 0.96, 1.])

See The scoring parameter: defining model evaluation rules for details. In the case of the Iris dataset, the samples are balanced across target classes hence the accuracy and the F1-score are almost equal.

When the cv argument is an integer, cross_val_score uses the KFold or StratifiedKFold strategies by default, the latter being used if the estimator derives from ClassifierMixin.

It is also possible to use other cross validation strategies by passing a cross validation iterator instead, for instance:

>>> from sklearn.model_selection import ShuffleSplit
>>> n_samples = X.shape[0]
>>> cv = ShuffleSplit(n_splits=5, test_size=0.3, random_state=0)
>>> cross_val_score(clf, X, y, cv=cv)
array([0.977, 0.977, 1., 0.955, 1.])

Another option is to use an iterable yielding (train, test) splits as arrays of indices, for example:

>>> def custom_cv_2folds(X):
...     n = X.shape[0]
...     i = 1
...     while i <= 2:
...         idx = np.arange(n * (i - 1) / 2, n * i / 2, dtype=int)
...         yield idx, idx
...         i += 1
...
>>> custom_cv = custom_cv_2folds(X)
>>> cross_val_score(clf, X, y, cv=custom_cv)
array([1.        , 0.973])
Data transformation with held-out data

Just as it is important to test a predictor on data held-out from training, preprocessing (such as standardization, feature selection, etc.) and similar data transformations similarly should be learnt from a training set and applied to held-out data for prediction:

>>> from sklearn import preprocessing
>>> X_train, X_test, y_train, y_test = train_test_split(
...     X, y, test_size=0.4, random_state=0)
>>> scaler = preprocessing.StandardScaler().fit(X_train)
>>> X_train_transformed = scaler.transform(X_train)
>>> clf = svm.SVC(C=1).fit(X_train_transformed, y_train)
>>> X_test_transformed = scaler.transform(X_test)
>>> clf.score(X_test_transformed, y_test)
0.9333

A Pipeline makes it easier to compose estimators, providing this behavior under cross-validation:

>>> from sklearn.pipeline import make_pipeline
>>> clf = make_pipeline(preprocessing.StandardScaler(), svm.SVC(C=1))
>>> cross_val_score(clf, X, y, cv=cv)
array([0.977, 0.933, 0.955, 0.933, 0.977])

See Pipelines and composite estimators.

3.1.1.1. The cross_validate function and multiple metric evaluation

The cross_validate function differs from cross_val_score in two ways:

  • It allows specifying multiple metrics for evaluation.

  • It returns a dict containing fit-times, score-times (and optionally training scores, fitted estimators, train-test split indices) in addition to the test score.

For single metric evaluation, where the scoring parameter is a string, callable or None, the keys will be - ['test_score', 'fit_time', 'score_time']

And for multiple metric evaluation, the return value is a dict with the following keys - ['test_<scorer1_name>', 'test_<scorer2_name>', 'test_<scorer...>', 'fit_time', 'score_time']

return_train_score is set to False by default to save computation time. To evaluate the scores on the training set as well you need to set it to True. You may also retain the estimator fitted on each training set by setting return_estimator=True. Similarly, you may set return_indices=True to retain the training and testing indices used to split the dataset into train and test sets for each cv split.

The multiple metrics can be specified either as a list, tuple or set of predefined scorer names:

>>> from sklearn.model_selection import cross_validate
>>> from sklearn.metrics import recall_score
>>> scoring = ['precision_macro', 'recall_macro']
>>> clf = svm.SVC(kernel='linear', C=1, random_state=0)
>>> scores = cross_validate(clf, X, y, scoring=scoring)
>>> sorted(scores.keys())
['fit_time', 'score_time', 'test_precision_macro', 'test_recall_macro']
>>> scores['test_recall_macro']
array([0.96, 1., 0.96, 0.96, 1.])

Or as a dict mapping scorer name to a predefined or custom scoring function:

>>> from sklearn.metrics import make_scorer
>>> scoring = {'prec_macro': 'precision_macro',
...            'rec_macro': make_scorer(recall_score, average='macro')}
>>> scores = cross_validate(clf, X, y, scoring=scoring,
...                         cv=5, return_train_score=True)
>>> sorted(scores.keys())
['fit_time', 'score_time', 'test_prec_macro', 'test_rec_macro',
 'train_prec_macro', 'train_rec_macro']
>>> scores['train_rec_macro']
array([0.97, 0.97, 0.99, 0.98, 0.98])

Here is an example of cross_validate using a single metric:

>>> scores = cross_validate(clf, X, y,
...                         scoring='precision_macro', cv=5,
...                         return_estimator=True)
>>> sorted(scores.keys())
['estimator', 'fit_time', 'score_time', 'test_score']

3.1.1.2. Obtaining predictions by cross-validation

The function cross_val_predict has a similar interface to cross_val_score, but returns, for each element in the input, the prediction that was obtained for that element when it was in the test set. Only cross-validation strategies that assign all elements to a test set exactly once can be used (otherwise, an exception is raised).

Warning

Note on inappropriate usage of cross_val_predict

The result of cross_val_predict may be different from those obtained using cross_val_score as the elements are grouped in different ways. The function cross_val_score takes an average over cross-validation folds, whereas cross_val_predict simply returns the labels (or probabilities) from several distinct models undistinguished. Thus, cross_val_predict is not an appropriate measure of generalization error.

The function cross_val_predict is appropriate for:
  • Visualization of predictions obtained from different models.

  • Model blending: When predictions of one supervised estimator are used to train another estimator in ensemble methods.

The available cross validation iterators are introduced in the following section.

Examples

3.1.2. Cross validation iterators

The following sections list utilities to generate indices that can be used to generate dataset splits according to different cross validation strategies.

3.1.2.1. Cross-validation iterators for i.i.d. data

Assuming that some data is Independent and Identically Distributed (i.i.d.) is making the assumption that all samples stem from the same generative process and that the generative process is assumed to have no memory of past generated samples.

The following cross-validators can be used in such cases.

Note

While i.i.d. data is a common assumption in machine learning theory, it rarely holds in practice. If one knows that the samples have been generated using a time-dependent process, it is safer to use a time-series aware cross-validation scheme. Similarly, if we know that the generative process has a group structure (samples collected from different subjects, experiments, measurement devices), it is safer to use group-wise cross-validation.

3.1.2.1.1. K-fold

KFold divides all the samples in \(k\) groups of samples, called folds (if \(k = n\), this is equivalent to the Leave One Out strategy), of equal sizes (if possible). The prediction function is learned using \(k - 1\) folds, and the fold left out is used for test.

Example of 2-fold cross-validation on a dataset with 4 samples:

>>> import numpy as np
>>> from sklearn.model_selection import KFold

>>> X = ["a", "b", "c", "d"]
>>> kf = KFold(n_splits=2)
>>> for train, test in kf.split(X):
...     print("%s %s" % (train, test))
[2 3] [0 1]
[0 1] [2 3]

Here is a visualization of the cross-validation behavior. Note that KFold is not affected by classes or groups.

../_images/sphx_glr_plot_cv_indices_006.png

Each fold is constituted by two arrays: the first one is related to the training set, and the second one to the test set. Thus, one can create the training/test sets using numpy indexing:

>>> X = np.array([[0., 0.], [1., 1.], [-1., -1.], [2., 2.]])
>>> y = np.array([0, 1, 0, 1])
>>> X_train, X_test, y_train, y_test = X[train], X[test], y[train], y[test]

3.1.2.1.2. Repeated K-Fold

RepeatedKFold repeats KFold \(n\) times, producing different splits in each repetition.

Example of 2-fold K-Fold repeated 2 times:

>>> import numpy as np
>>> from sklearn.model_selection import RepeatedKFold
>>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
>>> random_state = 12883823
>>> rkf = RepeatedKFold(n_splits=2, n_repeats=2, random_state=random_state)
>>> for train, test in rkf.split(X):
...     print("%s %s" % (train, test))
...
[2 3] [0 1]
[0 1] [2 3]
[0 2] [1 3]
[1 3] [0 2]

Similarly, RepeatedStratifiedKFold repeats StratifiedKFold \(n\) times with different randomization in each repetition.

3.1.2.1.3. Leave One Out (LOO)

LeaveOneOut (or LOO) is a simple cross-validation. Each learning set is created by taking all the samples except one, the test set being the sample left out. Thus, for \(n\) samples, we have \(n\) different training sets and \(n\) different test sets. This cross-validation procedure does not waste much data as only one sample is removed from the training set:

>>> from sklearn.model_selection import LeaveOneOut

>>> X = [1, 2, 3, 4]
>>> loo = LeaveOneOut()
>>> for train, test in loo.split(X):
...     print("%s %s" % (train, test))
[1 2 3] [0]
[0 2 3] [1]
[0 1 3] [2]
[0 1 2] [3]

Potential users of LOO for model selection should weigh a few known caveats. When compared with \(k\)-fold cross validation, one builds \(n\) models from \(n\) samples instead of \(k\) models, where \(n > k\). Moreover, each is trained on \(n - 1\) samples rather than \((k-1) n / k\). In both ways, assuming \(k\) is not too large and \(k < n\), LOO is more computationally expensive than \(k\)-fold cross validation.

In terms of accuracy, LOO often results in high variance as an estimator for the test error. Intuitively, since \(n - 1\) of the \(n\) samples are used to build each model, models constructed from folds are virtually identical to each other and to the model built from the entire training set.

However, if the learning curve is steep for the training size in question, then 5 or 10-fold cross validation can overestimate the generalization error.

As a general rule, most authors and empirical evidence suggest that 5 or 10-fold cross validation should be preferred to LOO.

References

3.1.2.1.4. Leave P Out (LPO)

LeavePOut is very similar to LeaveOneOut as it creates all the possible training/test sets by removing \(p\) samples from the complete set. For \(n\) samples, this produces \({n \choose p}\) train-test pairs. Unlike LeaveOneOut and KFold, the test sets will overlap for \(p > 1\).

Example of Leave-2-Out on a dataset with 4 samples:

>>> from sklearn.model_selection import LeavePOut

>>> X = np.ones(4)
>>> lpo = LeavePOut(p=2)
>>> for train, test in lpo.split(X):
...     print("%s %s" % (train, test))
[2 3] [0 1]
[1 3] [0 2]
[1 2] [0 3]
[0 3] [1 2]
[0 2] [1 3]
[0 1] [2 3]

3.1.2.1.5. Random permutations cross-validation a.k.a. Shuffle & Split

The ShuffleSplit iterator will generate a user defined number of independent train / test dataset splits. Samples are first shuffled and then split into a pair of train and test sets.

It is possible to control the randomness for reproducibility of the results by explicitly seeding the random_state pseudo random number generator.

Here is a usage example:

>>> from sklearn.model_selection import ShuffleSplit
>>> X = np.arange(10)
>>> ss = ShuffleSplit(n_splits=5, test_size=0.25, random_state=0)
>>> for train_index, test_index in ss.split(X):
...     print("%s %s" % (train_index, test_index))
[9 1 6 7 3 0 5] [2 8 4]
[2 9 8 0 6 7 4] [3 5 1]
[4 5 1 0 6 9 7] [2 3 8]
[2 7 5 8 0 3 4] [6 1 9]
[4 1 0 6 8 9 3] [5 2 7]

Here is a visualization of the cross-validation behavior. Note that ShuffleSplit is not affected by classes or groups.

../_images/sphx_glr_plot_cv_indices_008.png

ShuffleSplit is thus a good alternative to KFold cross validation that allows a finer control on the number of iterations and the proportion of samples on each side of the train / test split.

3.1.2.2. Cross-validation iterators with stratification based on class labels

Some classification tasks can naturally exhibit rare classes: for instance, there could be orders of magnitude more negative observations than positive observations (e.g. medical screening, fraud detection, etc). As a result, cross-validation splitting can generate train or validation folds without any occurrence of a particular class. This typically leads to undefined classification metrics (e.g. ROC AUC), exceptions raised when attempting to call fit or missing columns in the output of the predict_proba or decision_function methods of multiclass classifiers trained on different folds.

To mitigate such problems, splitters such as StratifiedKFold and StratifiedShuffleSplit implement stratified sampling to ensure that relative class frequencies are approximately preserved in each fold.

Note

Stratified sampling was introduced in scikit-learn to workaround the aforementioned engineering problems rather than solve a statistical one.

Stratification makes cross-validation folds more homogeneous, and as a result hides some of the variability inherent to fitting models with a limited number of observations.

As a result, stratification can artificially shrink the spread of the metric measured across cross-validation iterations: the inter-fold variability does no longer reflect the uncertainty in the performance of classifiers in the presence of rare classes.

3.1.2.2.1. Stratified K-fold

StratifiedKFold is a variation of K-fold which returns stratified folds: each set contains approximately the same percentage of samples of each target class as the complete set.

Here is an example of stratified 3-fold cross-validation on a dataset with 50 samples from two unbalanced classes. We show the number of samples in each class and compare with KFold.

>>> from sklearn.model_selection import StratifiedKFold, KFold
>>> import numpy as np
>>> X, y = np.ones((50, 1)), np.hstack(([0] * 45, [1] * 5))
>>> skf = StratifiedKFold(n_splits=3)
>>> for train, test in skf.split(X, y):
...     print('train -  {}   |   test -  {}'.format(
...         np.bincount(y[train]), np.bincount(y[test])))
train -  [30  3]   |   test -  [15  2]
train -  [30  3]   |   test -  [15  2]
train -  [30  4]   |   test -  [15  1]
>>> kf = KFold(n_splits=3)
>>> for train, test in kf.split(X, y):
...     print('train -  {}   |   test -  {}'.format(
...         np.bincount(y[train]), np.bincount(y[test])))
train -  [28  5]   |   test -  [17]
train -  [28  5]   |   test -  [17]
train -  [34]   |   test -  [11  5]

We can see that StratifiedKFold preserves the class ratios (approximately 1 / 10) in both train and test datasets.

Here is a visualization of the cross-validation behavior.

../_images/sphx_glr_plot_cv_indices_009.png

RepeatedStratifiedKFold can be used to repeat Stratified K-Fold n times with different randomization in each repetition.

3.1.2.2.2. Stratified Shuffle Split

StratifiedShuffleSplit is a variation of ShuffleSplit, which returns stratified splits, i.e. which creates splits by preserving the same percentage for each target class as in the complete set.

Here is a visualization of the cross-validation behavior.

../_images/sphx_glr_plot_cv_indices_012.png

3.1.2.3. Predefined fold-splits / Validation-sets

For some datasets, a pre-defined split of the data into training- and validation fold or into several cross-validation folds already exists. Using PredefinedSplit it is possible to use these folds e.g. when searching for hyperparameters.

For example, when using a validation set, set the test_fold to 0 for all samples that are part of the validation set, and to -1 for all other samples.

3.1.2.4. Cross-validation iterators for grouped data

The i.i.d. assumption is broken if the underlying generative process yields groups of dependent samples.

Such a grouping of data is domain specific. An example would be when there is medical data collected from multiple patients, with multiple samples taken from each patient. And such data is likely to be dependent on the individual group. In our example, the patient id for each sample will be its group identifier.

In this case we would like to know if a model trained on a particular set of groups generalizes well to the unseen groups. To measure this, we need to ensure that all the samples in the validation fold come from groups that are not represented at all in the paired training fold.

The following cross-validation splitters can be used to do that. The grouping identifier for the samples is specified via the groups parameter.

3.1.2.4.1. Group K-fold

GroupKFold is a variation of K-fold which ensures that the same group is not represented in both testing and training sets. For example if the data is obtained from different subjects with several samples per-subject and if the model is flexible enough to learn from highly person specific features it could fail to generalize to new subjects. GroupKFold makes it possible to detect this kind of overfitting situations.

Imagine you have three subjects, each with an associated number from 1 to 3:

>>> from sklearn.model_selection import GroupKFold

>>> X = [0.1, 0.2, 2.2, 2.4, 2.3, 4.55, 5.8, 8.8, 9, 10]
>>> y = ["a", "b", "b", "b", "c", "c", "c", "d", "d", "d"]
>>> groups = [1, 1, 1, 2, 2, 2, 3, 3, 3, 3]

>>> gkf = GroupKFold(n_splits=3)
>>> for train, test in gkf.split(X, y, groups=groups):
...     print("%s %s" % (train, test))
[0 1 2 3 4 5] [6 7 8 9]
[0 1 2 6 7 8 9] [3 4 5]
[3 4 5 6 7 8 9] [0 1 2]

Each subject is in a different testing fold, and the same subject is never in both testing and training. Notice that the folds do not have exactly the same size due to the imbalance in the data. If class proportions must be balanced across folds, StratifiedGroupKFold is a better option.

Here is a visualization of the cross-validation behavior.

../_images/sphx_glr_plot_cv_indices_007.png

Similar to KFold, the test sets from GroupKFold will form a complete partition of all the data.

While GroupKFold attempts to place the same number of samples in each fold when shuffle=False, when shuffle=True it attempts to place an equal number of distinct groups in each fold (but does not account for group sizes).

3.1.2.4.2. StratifiedGroupKFold

StratifiedGroupKFold is a cross-validation scheme that combines both StratifiedKFold and GroupKFold. The idea is to try to preserve the distribution of classes in each split while keeping each group within a single split. That might be useful when you have an unbalanced dataset so that using just GroupKFold might produce skewed splits.

Example:

>>> from sklearn.model_selection import StratifiedGroupKFold
>>> X = list(range(18))
>>> y = [1] * 6 + [0] * 12
>>> groups = [1, 2, 3, 3, 4, 4, 1, 1, 2, 2, 3, 4, 5, 5, 5, 6, 6, 6]
>>> sgkf = StratifiedGroupKFold(n_splits=3)
>>> for train, test in sgkf.split(X, y, groups=groups):
...     print("%s %s" % (train, test))
[ 0  2  3  4  5  6  7 10 11 15 16 17] [ 1  8  9 12 13 14]
[ 0  1  4  5  6  7  8  9 11 12 13 14] [ 2  3 10 15 16 17]
[ 1  2  3  8  9 10 12 13 14 15 16 17] [ 0  4  5  6  7 11]
Implementation notes
  • With the current implementation full shuffle is not possible in most scenarios. When shuffle=True, the following happens:

    1. All groups are shuffled.

    2. Groups are sorted by standard deviation of classes using stable sort.

    3. Sorted groups are iterated over and assigned to folds.

    That means that only groups with the same standard deviation of class distribution will be shuffled, which might be useful when each group has only a single class.

  • The algorithm greedily assigns each group to one of n_splits test sets, choosing the test set that minimises the variance in class distribution across test sets. Group assignment proceeds from groups with highest to lowest variance in class frequency, i.e. large groups peaked on one or few classes are assigned first.

  • This split is suboptimal in a sense that it might produce imbalanced splits even if perfect stratification is possible. If you have relatively close distribution of classes in each group, using GroupKFold is better.

Here is a visualization of cross-validation behavior for uneven groups:

../_images/sphx_glr_plot_cv_indices_005.png

3.1.2.4.3. Leave One Group Out

LeaveOneGroupOut is a cross-validation scheme where each split holds out samples belonging to one specific group. Group information is provided via an array that encodes the group of each sample.

Each training set is thus constituted by all the samples except the ones related to a specific group. This is the same as LeavePGroupsOut with n_groups=1 and the same as GroupKFold with n_splits equal to the number of unique labels passed to the groups parameter.

For example, in the cases of multiple experiments, LeaveOneGroupOut can be used to create a cross-validation based on the different experiments: we create a training set using the samples of all the experiments except one:

>>> from sklearn.model_selection import LeaveOneGroupOut

>>> X = [1, 5, 10, 50, 60, 70, 80]
>>> y = [0, 1, 1, 2, 2, 2, 2]
>>> groups = [1, 1, 2, 2, 3, 3, 3]
>>> logo = LeaveOneGroupOut()
>>> for train, test in logo.split(X, y, groups=groups):
...     print("%s %s" % (train, test))
[2 3 4 5 6] [0 1]
[0 1 4 5 6] [2 3]
[0 1 2 3] [4 5 6]

Another common application is to use time information: for instance the groups could be the year of collection of the samples and thus allow for cross-validation against time-based splits.

3.1.2.4.4. Leave P Groups Out

LeavePGroupsOut is similar to LeaveOneGroupOut, but removes samples related to \(P\) groups for each training/test set. All possible combinations of \(P\) groups are left out, meaning test sets will overlap for \(P>1\).

Example of Leave-2-Group Out:

>>> from sklearn.model_selection import LeavePGroupsOut

>>> X = np.arange(6)
>>> y = [1, 1, 1, 2, 2, 2]
>>> groups = [1, 1, 2, 2, 3, 3]
>>> lpgo = LeavePGroupsOut(n_groups=2)
>>> for train, test in lpgo.split(X, y, groups=groups):
...     print("%s %s" % (train, test))
[4 5] [0 1 2 3]
[2 3] [0 1 4 5]
[0 1] [2 3 4 5]

3.1.2.4.5. Group Shuffle Split

The GroupShuffleSplit iterator behaves as a combination of ShuffleSplit and LeavePGroupsOut, and generates a sequence of randomized partitions in which a subset of groups are held out for each split. Each train/test split is performed independently meaning there is no guaranteed relationship between successive test sets.

Here is a usage example:

>>> from sklearn.model_selection import GroupShuffleSplit

>>> X = [0.1, 0.2, 2.2, 2.4, 2.3, 4.55, 5.8, 0.001]
>>> y = ["a", "b", "b", "b", "c", "c", "c", "a"]
>>> groups = [1, 1, 2, 2, 3, 3, 4, 4]
>>> gss = GroupShuffleSplit(n_splits=4, test_size=0.5, random_state=0)
>>> for train, test in gss.split(X, y, groups=groups):
...     print("%s %s" % (train, test))
...
[0 1 2 3] [4 5 6 7]
[2 3 6 7] [0 1 4 5]
[2 3 4 5] [0 1 6 7]
[4 5 6 7] [0 1 2 3]

Here is a visualization of the cross-validation behavior.

../_images/sphx_glr_plot_cv_indices_011.png

This class is useful when the behavior of LeavePGroupsOut is desired, but the number of groups is large enough that generating all possible partitions with \(P\) groups withheld would be prohibitively expensive. In such a scenario, GroupShuffleSplit provides a random sample (with replacement) of the train / test splits generated by LeavePGroupsOut.

3.1.2.5. Using cross-validation iterators to split train and test

The above group cross-validation functions may also be useful for splitting a dataset into training and testing subsets. Note that the convenience function train_test_split is a wrapper around ShuffleSplit and thus only allows for stratified splitting (using the class labels) and cannot account for groups.

To perform the train and test split, use the indices for the train and test subsets yielded by the generator output by the split() method of the cross-validation splitter. For example:

>>> import numpy as np
>>> from sklearn.model_selection import GroupShuffleSplit

>>> X = np.array([0.1, 0.2, 2.2, 2.4, 2.3, 4.55, 5.8, 0.001])
>>> y = np.array(["a", "b", "b", "b", "c", "c", "c", "a"])
>>> groups = np.array([1, 1, 2, 2, 3, 3, 4, 4])
>>> train_indx, test_indx = next(
...     GroupShuffleSplit(random_state=7).split(X, y, groups)
... )
>>> X_train, X_test, y_train, y_test = \
...     X[train_indx], X[test_indx], y[train_indx], y[test_indx]
>>> X_train.shape, X_test.shape
((6,), (2,))
>>> np.unique(groups[train_indx]), np.unique(groups[test_indx])
(array([1, 2, 4]), array([3]))

3.1.2.6. Cross validation of time series data

Time series data is characterized by the correlation between observations that are near in time (autocorrelation). However, classical cross-validation techniques such as KFold and ShuffleSplit assume the samples are independent and identically distributed, and would result in unreasonable correlation between training and testing instances (yielding poor estimates of generalization error) on time series data. Therefore, it is very important to evaluate our model for time series data on the “future” observations least like those that are used to train the model. To achieve this, one solution is provided by TimeSeriesSplit.

3.1.2.6.1. Time Series Split

TimeSeriesSplit is a variation of k-fold which returns first \(k\) folds as train set and the \((k+1)\) th fold as test set. Note that unlike standard cross-validation methods, successive training sets are supersets of those that come before them. Also, it adds all surplus data to the first training partition, which is always used to train the model.

This class can be used to cross-validate time series data samples that are observed at fixed time intervals. Indeed, the folds must represent the same duration, in order to have comparable metrics across folds.

Example of 3-split time series cross-validation on a dataset with 6 samples:

>>> from sklearn.model_selection import TimeSeriesSplit

>>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4], [1, 2], [3, 4]])
>>> y = np.array([1, 2, 3, 4, 5, 6])
>>> tscv = TimeSeriesSplit(n_splits=3)
>>> print(tscv)
TimeSeriesSplit(gap=0, max_train_size=None, n_splits=3, test_size=None)
>>> for train, test in tscv.split(X):
...     print("%s %s" % (train, test))
[0 1 2] [3]
[0 1 2 3] [4]
[0 1 2 3 4] [5]

Here is a visualization of the cross-validation behavior.

../_images/sphx_glr_plot_cv_indices_013.png

3.1.3. A note on shuffling

If the data ordering is not arbitrary (e.g. samples with the same class label are contiguous), shuffling it first may be essential to get a meaningful cross-validation result. However, the opposite may be true if the samples are not independently and identically distributed. For example, if samples correspond to news articles, and are ordered by their time of publication, then shuffling the data will likely lead to a model that is overfit and an inflated validation score: it will be tested on samples that are artificially similar (close in time) to training samples.

Some cross validation iterators, such as KFold, have an inbuilt option to shuffle the data indices before splitting them. Note that:

  • This consumes less memory than shuffling the data directly.

  • By default no shuffling occurs, including for the (stratified) K fold cross-validation performed by specifying cv=some_integer to cross_val_score, grid search, etc. Keep in mind that train_test_split still returns a random split.

  • The random_state parameter defaults to None, meaning that the shuffling will be different every time KFold(..., shuffle=True) is iterated. However, GridSearchCV will use the same shuffling for each set of parameters validated by a single call to its fit method.

  • To get identical results for each split, set random_state to an integer.

For more details on how to control the randomness of cv splitters and avoid common pitfalls, see Controlling randomness.

3.1.4. Cross validation and model selection

Cross validation iterators can also be used to directly perform model selection using Grid Search for the optimal hyperparameters of the model. This is the topic of the next section: Tuning the hyper-parameters of an estimator.

3.1.5. Permutation test score

permutation_test_score offers another way to evaluate the performance of a predictor. It provides a permutation-based p-value, which represents how likely an observed performance of the estimator would be obtained by chance. The null hypothesis in this test is that the estimator fails to leverage any statistical dependency between the features and the targets to make correct predictions on left-out data. permutation_test_score generates a null distribution by calculating n_permutations different permutations of the data. In each permutation the target values are randomly shuffled, thereby removing any dependency between the features and the targets. The p-value output is the fraction of permutations whose cross-validation score is better or equal than the true score without permuting targets. For reliable results n_permutations should typically be larger than 100 and cv between 3-10 folds.

A low p-value provides evidence that the dataset contains some real dependency between features and targets and that the estimator was able to utilize this dependency to obtain good results. A high p-value, in reverse, could be due to either one of these:

  • a lack of dependency between features and targets (i.e., there is no systematic relationship and any observed patterns are likely due to random chance)

  • or because the estimator was not able to use the dependency in the data (for instance because it underfit).

In the latter case, using a more appropriate estimator that is able to use the structure in the data, would result in a lower p-value.

Cross-validation provides information about how well an estimator generalizes by estimating the range of its expected scores. However, an estimator trained on a high dimensional dataset with no structure may still perform better than expected on cross-validation, just by chance. This can typically happen with small datasets with less than a few hundred samples. permutation_test_score provides information on whether the estimator has found a real dependency between features and targets and can help in evaluating the performance of the estimator.

It is important to note that this test has been shown to produce low p-values even if there is only weak structure in the data because in the corresponding permutated datasets there is absolutely no structure. This test is therefore only able to show whether the model reliably outperforms random guessing.

Finally, permutation_test_score is computed using brute force and internally fits (n_permutations + 1) * n_cv models. It is therefore only tractable with small datasets for which fitting an individual model is very fast. Using the n_jobs parameter parallelizes the computation and thus speeds it up.

Examples

References

11.5. Multi-Head Attention Open the notebook in SageMaker Studio Lab

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

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

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

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

11.5. Multi-Head Attention
Open the notebook in SageMaker Studio Lab

In practice, given the same set of queries, keys, and values we may want our model to combine knowledge from different behaviors of the same attention mechanism, such as capturing dependencies of various ranges (e.g., shorter-range vs. longer-range) within a sequence. Thus, it may be beneficial to allow our attention mechanism to jointly use different representation subspaces of queries, keys, and values.

To this end, instead of performing a single attention pooling, queries, keys, and values can be transformed with \(h\) independently learned linear projections. Then these \(h\) projected queries, keys, and values are fed into attention pooling in parallel. In the end, \(h\) attention-pooling outputs are concatenated and transformed with another learned linear projection to produce the final output. This design is called multi-head attention, where each of the \(h\) attention pooling outputs is a head (Vaswani et al., 2017). Using fully connected layers to perform learnable linear transformations, Fig. 11.5.1 describes multi-head attention.

../_images/multi-head-attention.svg

Fig. 11.5.1 Multi-head attention, where multiple heads are concatenated then linearly transformed.

import math
import torch
from torch import nn
from d2l import torch as d2l

11.5.1. Model

Before providing the implementation of multi-head attention, let’s formalize this model mathematically. Given a query \(\mathbf{q} \in \mathbb{R}^{d_q}\), a key \(\mathbf{k} \in \mathbb{R}^{d_k}\), and a value \(\mathbf{v} \in \mathbb{R}^{d_v}\), each attention head \(\mathbf{h}_i\) (\(i = 1, \ldots, h\)) is computed as

(11.5.1)\[\mathbf{h}_i = f(\mathbf W_i^{(q)}\mathbf q, \mathbf W_i^{(k)}\mathbf k,\mathbf W_i^{(v)}\mathbf v) \in \mathbb R^{p_v},\]

where \(\mathbf W_i^{(q)}\in\mathbb R^{p_q\times d_q}\), \(\mathbf W_i^{(k)}\in\mathbb R^{p_k\times d_k}\), and \(\mathbf W_i^{(v)}\in\mathbb R^{p_v\times d_v}\) are learnable parameters and \(f\) is attention pooling, such as additive attention and scaled dot product attention in Section 11.3. The multi-head attention output is another linear transformation via learnable parameters \(\mathbf W_o\in\mathbb R^{p_o\times h p_v}\) of the concatenation of \(h\) heads:

(11.5.2)\[\begin{split}\mathbf W_o \begin{bmatrix}\mathbf h_1\\\vdots\\\mathbf h_h\end{bmatrix} \in \mathbb{R}^{p_o}.\end{split}\]

Based on this design, each head may attend to different parts of the input. More sophisticated functions than the simple weighted average can be expressed.

11.5.2. Implementation

In our implementation, we choose the scaled dot product attention for each head of the multi-head attention. To avoid significant growth of computational cost and parametrization cost, we set \(p_q = p_k = p_v = p_o / h\). Note that \(h\) heads can be computed in parallel if we set the number of outputs of linear transformations for the query, key, and value to \(p_q h = p_k h = p_v h = p_o\). In the following implementation, \(p_o\) is specified via the argument num_hiddens.

class MultiHeadAttention(d2l.Module):  #@save
    """Multi-head attention."""
    def __init__(self, num_hiddens, num_heads, dropout, bias=False, **kwargs):
        super().__init__()
        self.num_heads = num_heads
        self.attention = d2l.DotProductAttention(dropout)
        self.W_q = nn.LazyLinear(num_hiddens, bias=bias)
        self.W_k = nn.LazyLinear(num_hiddens, bias=bias)
        self.W_v = nn.LazyLinear(num_hiddens, bias=bias)
        self.W_o = nn.LazyLinear(num_hiddens, bias=bias)

    def forward(self, queries, keys, values, valid_lens):
        # Shape of queries, keys, or values:
        # (batch_size, no. of queries or key-value pairs, num_hiddens)
        # Shape of valid_lens: (batch_size,) or (batch_size, no. of queries)
        # After transposing, shape of output queries, keys, or values:
        # (batch_size * num_heads, no. of queries or key-value pairs,
        # num_hiddens / num_heads)
        queries = self.transpose_qkv(self.W_q(queries))
        keys = self.transpose_qkv(self.W_k(keys))
        values = self.transpose_qkv(self.W_v(values))

        if valid_lens is not None:
            # On axis 0, copy the first item (scalar or vector) for num_heads
            # times, then copy the next item, and so on
            valid_lens = torch.repeat_interleave(
                valid_lens, repeats=self.num_heads, dim=0)

        # Shape of output: (batch_size * num_heads, no. of queries,
        # num_hiddens / num_heads)
        output = self.attention(queries, keys, values, valid_lens)
        # Shape of output_concat: (batch_size, no. of queries, num_hiddens)
        output_concat = self.transpose_output(output)
        return self.W_o(output_concat)

To allow for parallel computation of multiple heads, the above MultiHeadAttention class uses two transposition methods as defined below. Specifically, the transpose_output method reverses the operation of the transpose_qkv method.

@d2l.add_to_class(MultiHeadAttention)  #@save
def transpose_qkv(self, X):
    """Transposition for parallel computation of multiple attention heads."""
    # Shape of input X: (batch_size, no. of queries or key-value pairs,
    # num_hiddens). Shape of output X: (batch_size, no. of queries or
    # key-value pairs, num_heads, num_hiddens / num_heads)
    X = X.reshape(X.shape[0], X.shape[1], self.num_heads, -1)
    # Shape of output X: (batch_size, num_heads, no. of queries or key-value
    # pairs, num_hiddens / num_heads)
    X = X.permute(0, 2, 1, 3)
    # Shape of output: (batch_size * num_heads, no. of queries or key-value
    # pairs, num_hiddens / num_heads)
    return X.reshape(-1, X.shape[2], X.shape[3])

@d2l.add_to_class(MultiHeadAttention)  #@save
def transpose_output(self, X):
    """Reverse the operation of transpose_qkv."""
    X = X.reshape(-1, self.num_heads, X.shape[1], X.shape[2])
    X = X.permute(0, 2, 1, 3)
    return X.reshape(X.shape[0], X.shape[1], -1)

Let’s test our implemented MultiHeadAttention class using a toy example where keys and values are the same. As a result, the shape of the multi-head attention output is (batch_size, num_queries, num_hiddens).

num_hiddens, num_heads = 100, 5
attention = MultiHeadAttention(num_hiddens, num_heads, 0.5)
batch_size, num_queries, num_kvpairs = 2, 4, 6
valid_lens = torch.tensor([3, 2])
X = torch.ones((batch_size, num_queries, num_hiddens))
Y = torch.ones((batch_size, num_kvpairs, num_hiddens))
d2l.check_shape(attention(X, Y, Y, valid_lens),
                (batch_size, num_queries, num_hiddens))

11.5.3. Summary

Multi-head attention combines knowledge of the same attention pooling via different representation subspaces of queries, keys, and values. To compute multiple heads of multi-head attention in parallel, proper tensor manipulation is needed.

11.5.4. Exercises

  1. Visualize attention weights of multiple heads in this experiment.

  2. Suppose that we have a trained model based on multi-head attention and we want to prune less important attention heads to increase the prediction speed. How can we design experiments to measure the importance of an attention head?

1.6. Nearest Neighbors

Assigned source reading · The scikit-learn developers

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

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

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

Full license and notices
BSD 3-Clause License

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

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

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

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

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

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

1.6. Nearest Neighbors

sklearn.neighbors provides functionality for unsupervised and supervised neighbors-based learning methods. Unsupervised nearest neighbors is the foundation of many other learning methods, notably manifold learning and spectral clustering. Supervised neighbors-based learning comes in two flavors: classification for data with discrete labels, and regression for data with continuous labels.

The principle behind nearest neighbor methods is to find a predefined number of training samples closest in distance to the new point, and predict the label from these. The number of samples can be a user-defined constant (k-nearest neighbor learning), or vary based on the local density of points (radius-based neighbor learning). The distance can, in general, be any metric measure: standard Euclidean distance is the most common choice. Neighbors-based methods are known as non-generalizing machine learning methods, since they simply “remember” all of its training data (possibly transformed into a fast indexing structure such as a Ball Tree or KD Tree).

Despite its simplicity, nearest neighbors has been successful in a large number of classification and regression problems, including handwritten digits and satellite image scenes. Being a non-parametric method, it is often successful in classification situations where the decision boundary is very irregular.

The classes in sklearn.neighbors can handle either NumPy arrays or scipy.sparse matrices as input. For dense matrices, a large number of possible distance metrics are supported. For sparse matrices, arbitrary Minkowski metrics are supported for searches.

There are many learning routines which rely on nearest neighbors at their core. One example is kernel density estimation, discussed in the density estimation section.

1.6.1. Unsupervised Nearest Neighbors

NearestNeighbors implements unsupervised nearest neighbors learning. It acts as a uniform interface to three different nearest neighbors algorithms: BallTree, KDTree, and a brute-force algorithm based on routines in sklearn.metrics.pairwise. The choice of neighbors search algorithm is controlled through the keyword 'algorithm', which must be one of ['auto', 'ball_tree', 'kd_tree', 'brute']. When the default value 'auto' is passed, the algorithm attempts to determine the best approach from the training data. For a discussion of the strengths and weaknesses of each option, see Nearest Neighbor Algorithms.

Warning

Regarding the Nearest Neighbors algorithms, if two neighbors \(k+1\) and \(k\) have identical distances but different labels, the result will depend on the ordering of the training data.

1.6.1.1. Finding the Nearest Neighbors

For the simple task of finding the nearest neighbors between two sets of data, the unsupervised algorithms within sklearn.neighbors can be used:

>>> from sklearn.neighbors import NearestNeighbors
>>> import numpy as np
>>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
>>> nbrs = NearestNeighbors(n_neighbors=2, algorithm='ball_tree').fit(X)
>>> distances, indices = nbrs.kneighbors(X)
>>> indices
array([[0, 1],
       [1, 0],
       [2, 1],
       [3, 4],
       [4, 3],
       [5, 4]]...)
>>> distances
array([[0.        , 1.        ],
       [0.        , 1.        ],
       [0.        , 1.41421356],
       [0.        , 1.        ],
       [0.        , 1.        ],
       [0.        , 1.41421356]])

Because the query set matches the training set, the nearest neighbor of each point is the point itself, at a distance of zero.

It is also possible to efficiently produce a sparse graph showing the connections between neighboring points:

>>> nbrs.kneighbors_graph(X).toarray()
array([[1., 1., 0., 0., 0., 0.],
       [1., 1., 0., 0., 0., 0.],
       [0., 1., 1., 0., 0., 0.],
       [0., 0., 0., 1., 1., 0.],
       [0., 0., 0., 1., 1., 0.],
       [0., 0., 0., 0., 1., 1.]])

The dataset is structured such that points nearby in index order are nearby in parameter space, leading to an approximately block-diagonal matrix of K-nearest neighbors. Such a sparse graph is useful in a variety of circumstances which make use of spatial relationships between points for unsupervised learning: in particular, see Isomap, LocallyLinearEmbedding, and SpectralClustering.

1.6.1.2. KDTree and BallTree Classes

Alternatively, one can use the KDTree or BallTree classes directly to find nearest neighbors. This is the functionality wrapped by the NearestNeighbors class used above. The Ball Tree and KD Tree have the same interface; we’ll show an example of using the KD Tree here:

>>> from sklearn.neighbors import KDTree
>>> import numpy as np
>>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
>>> kdt = KDTree(X, leaf_size=30, metric='euclidean')
>>> kdt.query(X, k=2, return_distance=False)
array([[0, 1],
       [1, 0],
       [2, 1],
       [3, 4],
       [4, 3],
       [5, 4]]...)

Refer to the KDTree and BallTree class documentation for more information on the options available for nearest neighbors searches, including specification of query strategies, distance metrics, etc. For a list of valid metrics use KDTree.valid_metrics and BallTree.valid_metrics:

>>> from sklearn.neighbors import KDTree, BallTree
>>> KDTree.valid_metrics
['euclidean', 'l2', 'minkowski', 'p', 'manhattan', 'cityblock', 'l1', 'chebyshev', 'infinity']
>>> BallTree.valid_metrics
['euclidean', 'l2', 'minkowski', 'p', 'manhattan', 'cityblock', 'l1', 'chebyshev', 'infinity', 'seuclidean', 'mahalanobis', 'hamming', 'canberra', 'braycurtis', 'jaccard', 'dice', 'rogerstanimoto', 'russellrao', 'sokalmichener', 'sokalsneath', 'haversine', 'pyfunc']

1.6.2. Nearest Neighbors Classification

Neighbors-based classification is a type of instance-based learning or non-generalizing learning: it does not attempt to construct a general internal model, but simply stores instances of the training data. Classification is computed from a simple majority vote of the nearest neighbors of each point: a query point is assigned the data class which has the most representatives within the nearest neighbors of the point.

scikit-learn implements two different nearest neighbors classifiers: KNeighborsClassifier implements learning based on the \(k\) nearest neighbors of each query point, where \(k\) is an integer value specified by the user. RadiusNeighborsClassifier implements learning based on the number of neighbors within a fixed radius \(r\) of each training point, where \(r\) is a floating-point value specified by the user.

The \(k\)-neighbors classification in KNeighborsClassifier is the most commonly used technique. The optimal choice of the value \(k\) is highly data-dependent: in general a larger \(k\) suppresses the effects of noise, but makes the classification boundaries less distinct.

In cases where the data is not uniformly sampled, radius-based neighbors classification in RadiusNeighborsClassifier can be a better choice. The user specifies a fixed radius \(r\), such that points in sparser neighborhoods use fewer nearest neighbors for the classification. For high-dimensional parameter spaces, this method becomes less effective due to the so-called “curse of dimensionality”.

The basic nearest neighbors classification uses uniform weights: that is, the value assigned to a query point is computed from a simple majority vote of the nearest neighbors. Under some circumstances, it is better to weight the neighbors such that nearer neighbors contribute more to the fit. This can be accomplished through the weights keyword. The default value, weights = 'uniform', assigns uniform weights to each neighbor. weights = 'distance' assigns weights proportional to the inverse of the distance from the query point. Alternatively, a user-defined function of the distance can be supplied to compute the weights.

classification_1

Examples

1.6.3. Nearest Neighbors Regression

Neighbors-based regression can be used in cases where the data labels are continuous rather than discrete variables. The label assigned to a query point is computed based on the mean of the labels of its nearest neighbors.

scikit-learn implements two different neighbors regressors: KNeighborsRegressor implements learning based on the \(k\) nearest neighbors of each query point, where \(k\) is an integer value specified by the user. RadiusNeighborsRegressor implements learning based on the neighbors within a fixed radius \(r\) of the query point, where \(r\) is a floating-point value specified by the user.

The basic nearest neighbors regression uses uniform weights: that is, each point in the local neighborhood contributes uniformly to the classification of a query point. Under some circumstances, it can be advantageous to weight points such that nearby points contribute more to the regression than faraway points. This can be accomplished through the weights keyword. The default value, weights = 'uniform', assigns equal weights to all points. weights = 'distance' assigns weights proportional to the inverse of the distance from the query point. Alternatively, a user-defined function of the distance can be supplied, which will be used to compute the weights.

../_images/sphx_glr_plot_regression_001.png

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

../_images/sphx_glr_plot_multioutput_face_completion_001.png

Examples

1.6.4. Nearest Neighbor Algorithms

1.6.4.1. Brute Force

Fast computation of nearest neighbors is an active area of research in machine learning. The most naive neighbor search implementation involves the brute-force computation of distances between all pairs of points in the dataset: for \(N\) samples in \(D\) dimensions, this approach scales as \(O[D N^2]\). Efficient brute-force neighbors searches can be very competitive for small data samples. However, as the number of samples \(N\) grows, the brute-force approach quickly becomes infeasible. In the classes within sklearn.neighbors, brute-force neighbors searches are specified using the keyword algorithm = 'brute', and are computed using the routines available in sklearn.metrics.pairwise.

1.6.4.2. K-D Tree

To address the computational inefficiencies of the brute-force approach, a variety of tree-based data structures have been invented. In general, these structures attempt to reduce the required number of distance calculations by efficiently encoding aggregate distance information for the sample. The basic idea is that if point \(A\) is very distant from point \(B\), and point \(B\) is very close to point \(C\), then we know that points \(A\) and \(C\) are very distant, without having to explicitly calculate their distance. In this way, the computational cost of a nearest neighbors search can be reduced to \(O[D N \log(N)]\) or better. This is a significant improvement over brute-force for large \(N\).

An early approach to taking advantage of this aggregate information was the KD tree data structure (short for K-dimensional tree), which generalizes two-dimensional Quad-trees and 3-dimensional Oct-trees to an arbitrary number of dimensions. The KD tree is a binary tree structure which recursively partitions the parameter space along the data axes, dividing it into nested orthotropic regions into which data points are filed. The construction of a KD tree is very fast: because partitioning is performed only along the data axes, no \(D\)-dimensional distances need to be computed. Once constructed, the nearest neighbor of a query point can be determined with only \(O[\log(N)]\) distance computations. Though the KD tree approach is very fast for low-dimensional (\(D < 20\)) neighbors searches, it becomes inefficient as \(D\) grows very large: this is one manifestation of the so-called “curse of dimensionality”. In scikit-learn, KD tree neighbors searches are specified using the keyword algorithm = 'kd_tree', and are computed using the class KDTree.

References

1.6.4.3. Ball Tree

To address the inefficiencies of KD Trees in higher dimensions, the ball tree data structure was developed. Where KD trees partition data along Cartesian axes, ball trees partition data in a series of nesting hyper-spheres. This makes tree construction more costly than that of the KD tree, but results in a data structure which can be very efficient on highly structured data, even in very high dimensions.

A ball tree recursively divides the data into nodes defined by a centroid \(C\) and radius \(r\), such that each point in the node lies within the hyper-sphere defined by \(r\) and \(C\). The number of candidate points for a neighbor search is reduced through use of the triangle inequality:

\[|x+y| \leq |x| + |y|\]

With this setup, a single distance calculation between a test point and the centroid is sufficient to determine a lower and upper bound on the distance to all points within the node. Because of the spherical geometry of the ball tree nodes, it can out-perform a KD-tree in high dimensions, though the actual performance is highly dependent on the structure of the training data. In scikit-learn, ball-tree-based neighbors searches are specified using the keyword algorithm = 'ball_tree', and are computed using the class BallTree. Alternatively, the user can work with the BallTree class directly.

References
Choice of Nearest Neighbors Algorithm

The optimal algorithm for a given dataset is a complicated choice, and depends on a number of factors:

  • number of samples \(N\) (i.e. n_samples) and dimensionality \(D\) (i.e. n_features).

    • Brute force query time grows as \(O[D N]\)

    • Ball tree query time grows as approximately \(O[D \log(N)]\)

    • KD tree query time changes with \(D\) in a way that is difficult to precisely characterise. For small \(D\) (less than 20 or so) the cost is approximately \(O[D\log(N)]\), and the KD tree query can be very efficient. For larger \(D\), the cost increases to nearly \(O[DN]\), and the overhead due to the tree structure can lead to queries which are slower than brute force.

    For small data sets (\(N\) less than 30 or so), \(\log(N)\) is comparable to \(N\), and brute force algorithms can be more efficient than a tree-based approach. Both KDTree and BallTree address this through providing a leaf size parameter: this controls the number of samples at which a query switches to brute-force. This allows both algorithms to approach the efficiency of a brute-force computation for small \(N\).

  • data structure: intrinsic dimensionality of the data and/or sparsity of the data. Intrinsic dimensionality refers to the dimension \(d \le D\) of a manifold on which the data lies, which can be linearly or non-linearly embedded in the parameter space. Sparsity refers to the degree to which the data fills the parameter space (this is to be distinguished from the concept as used in “sparse” matrices. The data matrix may have no zero entries, but the structure can still be “sparse” in this sense).

    • Brute force query time is unchanged by data structure.

    • Ball tree and KD tree query times can be greatly influenced by data structure. In general, sparser data with a smaller intrinsic dimensionality leads to faster query times. Because the KD tree internal representation is aligned with the parameter axes, it will not generally show as much improvement as ball tree for arbitrarily structured data.

    Datasets used in machine learning tend to be very structured, and are very well-suited for tree-based queries.

  • number of neighbors \(k\) requested for a query point.

    • Brute force query time is largely unaffected by the value of \(k\)

    • Ball tree and KD tree query time will become slower as \(k\) increases. This is due to two effects: first, a larger \(k\) leads to the necessity to search a larger portion of the parameter space. Second, using \(k > 1\) requires internal queueing of results as the tree is traversed.

    As \(k\) becomes large compared to \(N\), the ability to prune branches in a tree-based query is reduced. In this situation, Brute force queries can be more efficient.

  • number of query points. Both the ball tree and the KD Tree require a construction phase. The cost of this construction becomes negligible when amortized over many queries. If only a small number of queries will be performed, however, the construction can make up a significant fraction of the total cost. If very few query points will be required, brute force is better than a tree-based method.

Currently, algorithm = 'auto' selects 'brute' if any of the following conditions are verified:

  • input data is sparse

  • metric = 'precomputed'

  • \(D > 15\)

  • \(k >= N/2\)

  • effective_metric_ isn’t in the VALID_METRICS list for either 'kd_tree' or 'ball_tree'

Otherwise, it selects the first out of 'kd_tree' and 'ball_tree' that has effective_metric_ in its VALID_METRICS list. This heuristic is based on the following assumptions:

  • the number of query points is at least the same order as the number of training points

  • leaf_size is close to its default value of 30

  • when \(D > 15\), the intrinsic dimensionality of the data is generally too high for tree-based methods

Effect of leaf_size

As noted above, for small sample sizes a brute force search can be more efficient than a tree-based query. This fact is accounted for in the ball tree and KD tree by internally switching to brute force searches within leaf nodes. The level of this switch can be specified with the parameter leaf_size. This parameter choice has many effects:

construction time

A larger leaf_size leads to a faster tree construction time, because fewer nodes need to be created

query time

Both a large or small leaf_size can lead to suboptimal query cost. For leaf_size approaching 1, the overhead involved in traversing nodes can significantly slow query times. For leaf_size approaching the size of the training set, queries become essentially brute force. A good compromise between these is leaf_size = 30, the default value of the parameter.

memory

As leaf_size increases, the memory required to store a tree structure decreases. This is especially important in the case of ball tree, which stores a \(D\)-dimensional centroid for each node. The required storage space for BallTree is approximately 1 / leaf_size times the size of the training set.

leaf_size is not referenced for brute force queries.

Valid Metrics for Nearest Neighbor Algorithms

For a list of available metrics, see the documentation of the DistanceMetric class and the metrics listed in sklearn.metrics.pairwise.PAIRWISE_DISTANCE_FUNCTIONS. Note that the “cosine” metric uses cosine_distances.

A list of valid metrics for any of the above algorithms can be obtained by using their valid_metric attribute. For example, valid metrics for KDTree can be generated by:

>>> from sklearn.neighbors import KDTree
>>> print(sorted(KDTree.valid_metrics))
['chebyshev', 'cityblock', 'euclidean', 'infinity', 'l1', 'l2', 'manhattan', 'minkowski', 'p']

1.6.5. Nearest Centroid Classifier

The NearestCentroid classifier is a simple algorithm that represents each class by the centroid of its members. In effect, this makes it similar to the label updating phase of the KMeans algorithm. It also has no parameters to choose, making it a good baseline classifier. It does, however, suffer on non-convex classes, as well as when classes have drastically different variances, as equal variance in all dimensions is assumed. See Linear Discriminant Analysis (LinearDiscriminantAnalysis) and Quadratic Discriminant Analysis (QuadraticDiscriminantAnalysis) for more complex methods that do not make this assumption. Usage of the default NearestCentroid is simple:

>>> from sklearn.neighbors import NearestCentroid
>>> import numpy as np
>>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
>>> y = np.array([1, 1, 1, 2, 2, 2])
>>> clf = NearestCentroid()
>>> clf.fit(X, y)
NearestCentroid()
>>> print(clf.predict([[-0.8, -1]]))
[1]

1.6.5.1. Nearest Shrunken Centroid

The NearestCentroid classifier has a shrink_threshold parameter, which implements the nearest shrunken centroid classifier. In effect, the value of each feature for each centroid is divided by the within-class variance of that feature. The feature values are then reduced by shrink_threshold. Most notably, if a particular feature value crosses zero, it is set to zero. In effect, this removes the feature from affecting the classification. This is useful, for example, for removing noisy features.

In the example below, using a small shrink threshold increases the accuracy of the model from 0.81 to 0.82.

nearest_centroid_1 nearest_centroid_2

Examples

1.6.6. Nearest Neighbors Transformer

Many scikit-learn estimators rely on nearest neighbors: Several classifiers and regressors such as KNeighborsClassifier and KNeighborsRegressor, but also some clustering methods such as DBSCAN and SpectralClustering, and some manifold embeddings such as TSNE and Isomap.

All these estimators can compute internally the nearest neighbors, but most of them also accept precomputed nearest neighbors sparse graph, as given by kneighbors_graph and radius_neighbors_graph. With mode mode='connectivity', these functions return a binary adjacency sparse graph as required, for instance, in SpectralClustering. Whereas with mode='distance', they return a distance sparse graph as required, for instance, in DBSCAN. To include these functions in a scikit-learn pipeline, one can also use the corresponding classes KNeighborsTransformer and RadiusNeighborsTransformer. The benefits of this sparse graph API are multiple.

First, the precomputed graph can be reused multiple times, for instance while varying a parameter of the estimator. This can be done manually by the user, or using the caching properties of the scikit-learn pipeline:

>>> import tempfile
>>> from sklearn.manifold import Isomap
>>> from sklearn.neighbors import KNeighborsTransformer
>>> from sklearn.pipeline import make_pipeline
>>> from sklearn.datasets import make_regression
>>> cache_path = tempfile.gettempdir()  # we use a temporary folder here
>>> X, _ = make_regression(n_samples=50, n_features=25, random_state=0)
>>> estimator = make_pipeline(
...     KNeighborsTransformer(mode='distance'),
...     Isomap(n_components=3, metric='precomputed'),
...     memory=cache_path)
>>> X_embedded = estimator.fit_transform(X)
>>> X_embedded.shape
(50, 3)

Second, precomputing the graph can give finer control on the nearest neighbors estimation, for instance enabling multiprocessing though the parameter n_jobs, which might not be available in all estimators.

Finally, the precomputation can be performed by custom estimators to use different implementations, such as approximate nearest neighbors methods, or implementation with special data types. The precomputed neighbors sparse graph needs to be formatted as in radius_neighbors_graph output:

  • a CSR matrix (although COO, CSC or LIL will be accepted).

  • only explicitly store nearest neighborhoods of each sample with respect to the training data. This should include those at 0 distance from a query point, including the matrix diagonal when computing the nearest neighborhoods between the training data and itself.

  • each row’s data should store the distance in increasing order (optional. Unsorted data will be stable-sorted, adding a computational overhead).

  • all values in data should be non-negative.

  • there should be no duplicate indices in any row (see scipy/scipy#5807).

  • if the algorithm being passed the precomputed matrix uses k nearest neighbors (as opposed to radius neighborhood), at least k neighbors must be stored in each row (or k+1, as explained in the following note).

Note

When a specific number of neighbors is queried (using KNeighborsTransformer), the definition of n_neighbors is ambiguous since it can either include each training point as its own neighbor, or exclude them. Neither choice is perfect, since including them leads to a different number of non-self neighbors during training and testing, while excluding them leads to a difference between fit(X).transform(X) and fit_transform(X), which is against scikit-learn API. In KNeighborsTransformer we use the definition which includes each training point as its own neighbor in the count of n_neighbors. However, for compatibility reasons with other estimators which use the other definition, one extra neighbor will be computed when mode == 'distance'. To maximise compatibility with all estimators, a safe choice is to always include one extra neighbor in a custom nearest neighbors estimator, since unnecessary neighbors will be filtered by following estimators.

Examples

1.6.7. Neighborhood Components Analysis

Neighborhood Components Analysis (NCA, NeighborhoodComponentsAnalysis) is a distance metric learning algorithm which aims to improve the accuracy of nearest neighbors classification compared to the standard Euclidean distance. The algorithm directly maximizes a stochastic variant of the leave-one-out k-nearest neighbors (KNN) score on the training set. It can also learn a low-dimensional linear projection of data that can be used for data visualization and fast classification.

nca_illustration_1 nca_illustration_2

In the above illustrating figure, we consider some points from a randomly generated dataset. We focus on the stochastic KNN classification of point no. 3. The thickness of a link between sample 3 and another point is proportional to their distance, and can be seen as the relative weight (or probability) that a stochastic nearest neighbor prediction rule would assign to this point. In the original space, sample 3 has many stochastic neighbors from various classes, so the right class is not very likely. However, in the projected space learned by NCA, the only stochastic neighbors with non-negligible weight are from the same class as sample 3, guaranteeing that the latter will be well classified. See the mathematical formulation for more details.

1.6.7.1. Classification

Combined with a nearest neighbors classifier (KNeighborsClassifier), NCA is attractive for classification because it can naturally handle multi-class problems without any increase in the model size, and does not introduce additional parameters that require fine-tuning by the user.

NCA classification has been shown to work well in practice for data sets of varying size and difficulty. In contrast to related methods such as Linear Discriminant Analysis, NCA does not make any assumptions about the class distributions. The nearest neighbor classification can naturally produce highly irregular decision boundaries.

To use this model for classification, one needs to combine a NeighborhoodComponentsAnalysis instance that learns the optimal transformation with a KNeighborsClassifier instance that performs the classification in the projected space. Here is an example using the two classes:

>>> from sklearn.neighbors import (NeighborhoodComponentsAnalysis,
... KNeighborsClassifier)
>>> from sklearn.datasets import load_iris
>>> from sklearn.model_selection import train_test_split
>>> from sklearn.pipeline import Pipeline
>>> X, y = load_iris(return_X_y=True)
>>> X_train, X_test, y_train, y_test = train_test_split(X, y,
... stratify=y, test_size=0.7, random_state=42)
>>> nca = NeighborhoodComponentsAnalysis(random_state=42)
>>> knn = KNeighborsClassifier(n_neighbors=3)
>>> nca_pipe = Pipeline([('nca', nca), ('knn', knn)])
>>> nca_pipe.fit(X_train, y_train)
Pipeline(...)
>>> print(nca_pipe.score(X_test, y_test))
0.96190476...

nca_classification_1 nca_classification_2

The plot shows decision boundaries for Nearest Neighbor Classification and Neighborhood Components Analysis classification on the iris dataset, when training and scoring on only two features, for visualisation purposes.

1.6.7.2. Dimensionality reduction

NCA can be used to perform supervised dimensionality reduction. The input data are projected onto a linear subspace consisting of the directions which minimize the NCA objective. The desired dimensionality can be set using the parameter n_components. For instance, the following figure shows a comparison of dimensionality reduction with Principal Component Analysis (PCA), Linear Discriminant Analysis (LinearDiscriminantAnalysis) and Neighborhood Component Analysis (NeighborhoodComponentsAnalysis) on the Digits dataset, a dataset with size \(n_{samples} = 1797\) and \(n_{features} = 64\). The data set is split into a training and a test set of equal size, then standardized. For evaluation the 3-nearest neighbor classification accuracy is computed on the 2-dimensional projected points found by each method. Each data sample belongs to one of 10 classes.

nca_dim_reduction_1 nca_dim_reduction_2 nca_dim_reduction_3

Examples

1.6.7.3. Mathematical formulation

The goal of NCA is to learn an optimal linear transformation matrix of size (n_components, n_features), which maximises the sum over all samples \(i\) of the probability \(p_i\) that \(i\) is correctly classified, i.e.:

\[\underset{L}{\arg\max} \sum\limits_{i=0}^{N - 1} p_{i}\]

with \(N\) = n_samples and \(p_i\) the probability of sample \(i\) being correctly classified according to a stochastic nearest neighbors rule in the learned embedded space:

\[p_{i}=\sum\limits_{j \in C_i}{p_{i j}}\]

where \(C_i\) is the set of points in the same class as sample \(i\), and \(p_{i j}\) is the softmax over Euclidean distances in the embedded space:

\[p_{i j} = \frac{\exp(-||L x_i - L x_j||^2)}{\sum\limits_{k \ne i} {\exp{-(||L x_i - L x_k||^2)}}} , \quad p_{i i} = 0\]
Mahalanobis distance

NCA can be seen as learning a (squared) Mahalanobis distance metric:

\[|| L(x_i - x_j)||^2 = (x_i - x_j)^TM(x_i - x_j),\]

where \(M = L^T L\) is a symmetric positive semi-definite matrix of size (n_features, n_features).

1.6.7.4. Implementation

This implementation follows what is explained in the original paper [1]. For the optimisation method, it currently uses scipy’s L-BFGS-B with a full gradient computation at each iteration, to avoid to tune the learning rate and provide stable learning.

See the examples below and the docstring of NeighborhoodComponentsAnalysis.fit for further information.

1.6.7.5. Complexity

1.6.7.5.1. Training

NCA stores a matrix of pairwise distances, taking n_samples ** 2 memory. Time complexity depends on the number of iterations done by the optimisation algorithm. However, one can set the maximum number of iterations with the argument max_iter. For each iteration, time complexity is O(n_components x n_samples x min(n_samples, n_features)).

1.6.7.5.2. Transform

Here the transform operation returns \(LX^T\), therefore its time complexity equals n_components * n_features * n_samples_test. There is no added space complexity in the operation.

References

LLM10:2025 Unbounded Consumption

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.

LLM10:2025 Unbounded Consumption

Unbounded Consumption refers to the process where a Large Language Model (LLM) generates outputs based on input queries or prompts. Inference is a critical function of LLMs, involving the application of learned patterns and knowledge to produce relevant responses or predictions.

Attacks designed to disrupt service, deplete the target’s financial resources, or even steal intellectual property by cloning a model’s behavior all depend on a common class of security vulnerability in order to succeed. Unbounded Consumption occurs when a Large Language Model (LLM) application allows users to conduct excessive and uncontrolled inferences, leading to risks such as denial of service (DoS), economic losses, model theft, and service degradation. The high computational demands of LLMs, especially in cloud environments, make them vulnerable to resource exploitation and unauthorized usage.

Common Examples of Vulnerability

1. Variable-Length Input Flood

Attackers can overload the LLM with numerous inputs of varying lengths, exploiting processing inefficiencies. This can deplete resources and potentially render the system unresponsive, significantly impacting service availability.

2. Denial of Wallet (DoW)

By initiating a high volume of operations, attackers exploit the cost-per-use model of cloud-based AI services, leading to unsustainable financial burdens on the provider and risking financial ruin.

3. Continuous Input Overflow

Continuously sending inputs that exceed the LLM’s context window can lead to excessive computational resource use, resulting in service degradation and operational disruptions.

4. Resource-Intensive Queries

Submitting unusually demanding queries involving complex sequences or intricate language patterns can drain system resources, leading to prolonged processing times and potential system failures.

5. Model Extraction via API

Attackers may query the model API using carefully crafted inputs and prompt injection techniques to collect sufficient outputs to replicate a partial model or create a shadow model. This not only poses risks of intellectual property theft but also undermines the integrity of the original model.

6. Functional Model Replication

Using the target model to generate synthetic training data can allow attackers to fine-tune another foundational model, creating a functional equivalent. This circumvents traditional query-based extraction methods, posing significant risks to proprietary models and technologies.

7. Side-Channel Attacks

Malicious attackers may exploit input filtering techniques of the LLM to execute side-channel attacks, harvesting model weights and architectural information. This could compromise the model’s security and lead to further exploitation.

Prevention and Mitigation Strategies

1. Input Validation

Implement strict input validation to ensure that inputs do not exceed reasonable size limits.

2. Limit Exposure of Logits and Logprobs

Restrict or obfuscate the exposure of logit_bias and logprobs in API responses. Provide only the necessary information without revealing detailed probabilities.

3. Rate Limiting

Apply rate limiting and user quotas to restrict the number of requests a single source entity can make in a given time period.

4. Resource Allocation Management

Monitor and manage resource allocation dynamically to prevent any single user or request from consuming excessive resources.

5. Timeouts and Throttling

Set timeouts and throttle processing for resource-intensive operations to prevent prolonged resource consumption.

6.Sandbox Techniques

Restrict the LLM’s access to network resources, internal services, and APIs.

  • This is particularly significant for all common scenarios as it encompasses insider risks and threats. Furthermore, it governs the extent of access the LLM application has to data and resources, thereby serving as a crucial control mechanism to mitigate or prevent side-channel attacks.

7. Comprehensive Logging, Monitoring and Anomaly Detection

Continuously monitor resource usage and implement logging to detect and respond to unusual patterns of resource consumption.

8. Watermarking

Implement watermarking frameworks to embed and detect unauthorized use of LLM outputs.

9. Graceful Degradation

Design the system to degrade gracefully under heavy load, maintaining partial functionality rather than complete failure.

10. Limit Queued Actions and Scale Robustly

Implement restrictions on the number of queued actions and total actions, while incorporating dynamic scaling and load balancing to handle varying demands and ensure consistent system performance.

11. Adversarial Robustness Training

Train models to detect and mitigate adversarial queries and extraction attempts.

12. Glitch Token Filtering

Build lists of known glitch tokens and scan output before adding it to the model’s context window.

13. Access Controls

Implement strong access controls, including role-based access control (RBAC) and the principle of least privilege, to limit unauthorized access to LLM model repositories and training environments.

14. Centralized ML Model Inventory

Use a centralized ML model inventory or registry for models used in production, ensuring proper governance and access control.

15. Automated MLOps Deployment

Implement automated MLOps deployment with governance, tracking, and approval workflows to tighten access and deployment controls within the infrastructure.

Example Attack Scenarios

Scenario #1: Uncontrolled Input Size

An attacker submits an unusually large input to an LLM application that processes text data, resulting in excessive memory usage and CPU load, potentially crashing the system or significantly slowing down the service.

Scenario #2: Repeated Requests

An attacker transmits a high volume of requests to the LLM API, causing excessive consumption of computational resources and making the service unavailable to legitimate users.

Scenario #3: Resource-Intensive Queries

An attacker crafts specific inputs designed to trigger the LLM’s most computationally expensive processes, leading to prolonged CPU usage and potential system failure.

Scenario #4: Denial of Wallet (DoW)

An attacker generates excessive operations to exploit the pay-per-use model of cloud-based AI services, causing unsustainable costs for the service provider.

Scenario #5: Functional Model Replication

An attacker uses the LLM’s API to generate synthetic training data and fine-tunes another model, creating a functional equivalent and bypassing traditional model extraction limitations.

Scenario #6: Bypassing System Input Filtering

A malicious attacker bypasses input filtering techniques and preambles of the LLM to perform a side-channel attack and retrieve model information to a remote controlled resource under their control.

Reference Links

  1. Proof Pudding (CVE-2019-20634) AVID (moohax & monoxgas)
  2. arXiv:2403.06634 Stealing Part of a Production Language Model arXiv
  3. Runaway LLaMA | How Meta’s LLaMA NLP model leaked: Deep Learning Blog
  4. I Know What You See:: Arxiv White Paper
  5. A Comprehensive Defense Framework Against Model Extraction Attacks: IEEE
  6. Alpaca: A Strong, Replicable Instruction-Following Model: Stanford Center on Research for Foundation Models (CRFM)
  7. How Watermarking Can Help Mitigate The Potential Risks Of LLMs?: KD Nuggets
  8. Securing AI Model Weights Preventing Theft and Misuse of Frontier Models
  9. Sponge Examples: Energy-Latency Attacks on Neural Networks: Arxiv White Paper arXiv
  10. Sourcegraph Security Incident on API Limits Manipulation and DoS Attack Sourcegraph

Related Frameworks and Taxonomies

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

    Django Tutorial Part 11: Deploying Django to production

    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.

    Django Tutorial Part 11: Deploying Django to production

    You've already created and tested example website using Django, so now, it's time to install it on a web server so it can be accessed by anyone over the public internet. This page describes how to host a Django project and what you need to prepare your site for a production deployment.

    Prerequisites: Complete all previous tutorial topics, including Django Tutorial Part 10: Testing a Django web application.
    Objective: To learn where and how you can deploy a Django app to production.

    Overview

    Once your site is finished (or finished "enough" to start public testing) you're going to need to host it somewhere more public and accessible than your personal development computer.

    Up to now you've been working in a development environment, using the Django development web server to share your site to the local browser/network, and running your website with (insecure) development settings that expose debug and other private information. Before you can host a website externally you're first going to have to:

    • Make a few changes to your project settings.
    • Choose an environment for hosting the Django app.
    • Choose an environment for hosting any static files.
    • Set up a production-level infrastructure for serving your website.

    This tutorial provides some guidance on your options for choosing a hosting site, a brief overview of what you need to do in order to get your Django app ready for production, and a working example of how to install the LocalLibrary website onto the Railway cloud hosting service.

    What is a production environment?

    The production environment is the environment provided by the server computer where you will run your website for external consumption. The environment includes:

    • Computer hardware on which the website runs.
    • Operating system (e.g., Linux, Windows).
    • Programming language runtime and framework libraries on top of which your website is written.
    • Web server used to serve pages and other content (e.g., Nginx, Apache).
    • Application server that passes "dynamic" requests between your Django website and the web server.
    • Databases on which your website is dependent.

    Note: Depending on how your production environment is configured you might also have a reverse proxy, load balancer, and so on.

    The server computer could be located on your premises and connected to the internet by a fast link, but it is far more common to use a computer that is hosted "in the cloud". What this actually means is that your code is run on some remote computer (or possibly a "virtual" computer) in your hosting company's data center(s). The remote server will usually offer some guaranteed level of computing resources (CPU, RAM, storage memory, etc.) and internet connectivity for a certain price.

    This sort of remotely accessible computing/networking hardware is referred to as Infrastructure as a Service (IaaS). Many IaaS vendors provide options to preinstall a particular operating system, onto which you must install the other components of your production environment. Other vendors allow you to select more fully-featured environments, perhaps including a complete Django and web-server setup.

    Note: Pre-built environments can make setting up your website very easy because they reduce the configuration, but the available options may limit you to an unfamiliar server (or other components) and may be based on an older version of the OS. Often it is better to install components yourself, so that you get the ones that you want, and when you need to upgrade parts of the system, you have some idea of where to start!

    Other hosting providers support Django as part of a Platform as a Service (PaaS) offering. In this sort of hosting you don't need to worry about most of your production environment (web server, application server, load balancers) as the host platform takes care of those for you — along with most of what you need to do in order to scale your application. That makes deployment quite easy, because you just need to concentrate on your web application and not all the other server infrastructure.

    Some developers will choose the increased flexibility provided by IaaS over PaaS, while others will appreciate the reduced maintenance overhead and easier scaling of PaaS. When you're getting started, setting up your website on a PaaS system is much easier, and so that is what we'll do in this tutorial.

    Note: If you choose a Python/Django-friendly hosting provider they should provide instructions on how to set up a Django website using different configurations of web server, application server, reverse proxy, and so on. (this won't be relevant if you choose a PaaS). For example, there are many step-by-step guides for various configurations in the DigitalOcean Django community docs.

    Choosing a hosting provider

    There are many hosting providers that are known to either actively support or work well with Django, including: Heroku, DigitalOcean, Railway, Python Anywhere, Amazon Web Services, Azure, Google Cloud, Hetzner, and Vultr Cloud Compute — to name just a few. These vendors provide different types of environments (IaaS, PaaS), and different levels of computing and network resources at different prices.

    Some of the things to consider when choosing a host:

    • How busy your site is likely to be and the cost of data and computing resources required to meet that demand.
    • Level of support for scaling horizontally (adding more machines) and vertically (upgrading to more powerful machines) and the costs of doing so.
    • Where the supplier has data centers, and hence where access is likely to be fastest.
    • The host's historical uptime and downtime performance.
    • Tools provided for managing the site — are they easy to use and are they secure (e.g., SFTP vs. FTP).
    • Inbuilt frameworks for monitoring your server.
    • Known limitations. Some hosts will deliberately block certain services (e.g., email). Others offer only a certain number of hours of "live time" in some price tiers, or only offer a small amount of storage.
    • Additional benefits. Some providers will offer free domain names and support for TLS certificates that you would otherwise have to pay for.
    • Whether the "free" tier you're relying on expires over time, and whether the cost of migrating to a more expensive tier means you would have been better off using some other service in the first place!

    The good news when you're starting out is that there are quite a few sites that provide "free" computing environments that are intended for evaluation and testing. These are usually fairly resource constrained/limited environments, and you do need to be aware that they may expire after some introductory period or have other constraints. They are however great for testing low traffic sites in a hosted environment, and can provide an easy migration to paying for more resources when your site gets busier. Popular choices in this category include Vultr Cloud Compute, Python Anywhere, Amazon Web Services, Microsoft Azure, and so on.

    Most providers also offer a "basic" tier that is intended for small production sites, and which provide more useful levels of computing power and fewer limitations. Railway, Heroku, and DigitalOcean are examples of popular hosting providers that have a relatively inexpensive basic computing tier (in the $5 to $10 USD per month range).

    Note: Remember that price is not the only selection criterion. If your website is successful, it may turn out that scalability is the most important consideration.

    Getting your website ready to publish

    The Django skeleton website created using the django-admin and manage.py tools are configured to make development easier. Many of the Django project settings (specified in settings.py) should be different for production, either for security or performance reasons.

    Note: It is common to have a separate settings.py file for production, and/or to conditionally import sensitive settings from a separate file or an environment variable. This file should then be protected, even if the rest of the source code is available on a public repository.

    The critical settings that you must check are:

    • DEBUG. This should be set as False in production (DEBUG = False). This stops the sensitive/confidential debug trace and variable information from being displayed.
    • SECRET_KEY. This is a large random value used for CSRF protection, etc. It is important that the key used in production is not in source control or accessible outside the production server.

    The Django documents suggest that secret information might best be loaded from an environment variable or read from a server-only file. Let's change the LocalLibrary application so that we read our SECRET_KEY and DEBUG variables from environment variables if they are defined, falling back to values defined in an .env file in the root, and lastly to using the default values in the configuration file. This is very flexible as it allows any configuration supported by the hosting server.

    For reading environment values from a file we'll use python-dotenv. This is a library for reading key-value pairs out of a file and using them as environment variables, but only if the corresponding environment variable is not defined.

    Install the library into your virtual environment as shown (and also update your requirements.txt file):

    bash
    pip3 install python-dotenv
    

    Then open /locallibrary/settings.py and insert the following code after BASE_DIR is defined, but before the security warning: # SECURITY WARNING: keep the secret key used in production secret!

    python
    # Support env variables from .env file if defined
    import os
    from dotenv import load_dotenv
    
    env_path = os.path.join(BASE_DIR, ".env")
    if os.path.exists(env_path):
        load_dotenv(env_path)
    

    This loads the .env file from the root of the web application. Variables defined as KEY=VALUE in the file are imported when the key is used in os.environ.get('<KEY>'', '<DEFAULT VALUE>'), if defined.

    Note: Any values that you add to .env are likely to be secrets! You must not save them to GitHub, and you should add .env to your .gitignore file so that it is not added by accident.

    Next disable the original SECRET_KEY configuration and add the new lines as shown below. During development no environment variable will be specified for the key, so the default value will be used (it shouldn't matter what key you use here, or if the key "leaks", because you won't use it in production).

    python
    # SECURITY WARNING: keep the secret key used in production secret!
    # SECRET_KEY = 'django-insecure-&psk#na5l=p3q8_a+-$4w1f^lt3lx1c@d*p4x$ymm_rn7pwb87'
    import os
    SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'django-insecure-&psk#na5l=p3q8_a+-$4w1f^lt3lx1c@d*p4x$ymm_rn7pwb87')
    

    Then comment out the existing DEBUG setting and add the new line shown below.

    python
    # SECURITY WARNING: don't run with debug turned on in production!
    # DEBUG = True
    DEBUG = os.environ.get('DJANGO_DEBUG', '') != 'False'
    

    The value of the DEBUG will be True by default, but will only be False if the value of the DJANGO_DEBUG environment variable is set to False or DJANGO_DEBUG=False is set in the .env file. Please note that environment variables are strings and not Python types. We therefore need to compare strings. The only way to set the DEBUG variable to False is to actually set it to the string False.

    You can set the environment variable to "False" on Linux by issuing the following command:

    bash
    export DJANGO_DEBUG=False
    

    A full checklist of settings you might want to change is provided in Deployment checklist (Django docs). You can also list a number of these using the terminal command below:

    bash
    python3 manage.py check --deploy
    

    Gunicorn

    Gunicorn is a pure-Python HTTP server that is commonly used for serving Django WSGI applications.

    While we don't need Gunicorn to serve our LocalLibrary application during development, we'll install it locally so that it becomes part of our requirements when the application is deployed.

    First make sure that you're in the Python virtual environment that was created when you set up the development environment (use the workon [name-of-virtual-environment] command). Then install Gunicorn locally on the command line using pip:

    bash
    pip3 install gunicorn
    

    Database configuration

    SQLite, the default Django database that you've been using for development, is a reasonable choice for small to medium websites. Unfortunately it cannot be used on some popular hosting services, such as Heroku, because they don't provide persistent data storage in the application environment (a requirement of SQLite). While that might not affect us for the example deployment(s), we'll show you another approach that will work on Railway, Heroku, and some other services.

    The approach is to use a database that runs in its own process somewhere on the Internet, and is accessed by the Django library application using an address passed as an environment variable. In this case we'll use a Postgres database that is also hosted on Railway, but you could use any database hosting service you like.

    The database connection information will be supplied to Django using an environment variable named DATABASE_URL. Rather than hard-coding this information into Django, we'll use the dj-database-url package to parse the DATABASE_URL environment variable and automatically convert it to Django's desired configuration format. In addition to installing the dj-database-url package we'll also need to install psycopg2, as Django needs this to interact with Postgres databases.

    dj-database-url

    dj-database-url is used to extract the Django database configuration from an environment variable.

    Install it locally so that it becomes part of our requirements to set up on the deployment server:

    bash
    pip3 install dj-database-url
    

    settings.py

    Open /locallibrary/settings.py and copy the following configuration into the bottom of the file:

    python
    # Update database configuration from $DATABASE_URL environment variable (if defined)
    import dj_database_url
    
    if 'DATABASE_URL' in os.environ:
        DATABASES['default'] = dj_database_url.config(
            conn_max_age=500,
            conn_health_checks=True,
        )
    

    Django will now use the database configuration in DATABASE_URL if the environment variable is set; otherwise it uses the default SQLite database. The value conn_max_age=500 makes the connection persistent, which is far more efficient than recreating the connection on every request cycle (this is optional and can be removed if needed).

    psycopg2

    Django needs psycopg2 to work with Postgres databases. Install it locally so that it becomes part of our requirements for Railway to set up on the remote server:

    bash
    pip3 install psycopg2-binary
    

    Note that Django will use the SQLite database during development by default, unless DATABASE_URL is set. You can switch to Postgres completely and use the same hosted database for development and production by setting the same environment variable in your development environment (Railway makes it easy to use the same environment for production and development). Alternatively you can also install and use a self-hosted Postgres database on your local computer.

    Serving static files in production

    During development we use Django and the Django development web server to serve both our dynamic HTML and our static files (CSS, JavaScript, etc.). This is inefficient for static files, because the requests have to pass through Django even though Django doesn't do anything with them. While this doesn't matter during development, it would have a significant performance impact if we were to use the same approach in production.

    In the production environment we typically separate the static files from the Django web application, making it easier to serve them directly from the web server or from a content delivery network (CDN).

    The important setting variables are:

    • STATIC_URL: This is the base URL location from which static files will be served, for example on a CDN.
    • STATIC_ROOT: This is the absolute path to a directory where Django's collectstatic tool will gather any static files referenced in our templates. Once collected, these can then be uploaded as a group to wherever the files are to be hosted.
    • STATICFILES_DIRS: This lists additional directories that Django's collectstatic tool should search for static files.

    Django templates refer to static file locations relative to a static tag (you can see this in the base template defined in Django Tutorial Part 5: Creating our home page), which in turn maps to the STATIC_URL setting. Static files can therefore be uploaded to any host and you can update your application to find them using this setting.

    The collectstatic tool is used to collect static files into the folder defined by the STATIC_ROOT project setting. It is called with the following command:

    bash
    python3 manage.py collectstatic
    

    For this tutorial, collectstatic can be run before the application is uploaded, copying all the static files in the application to the location specified in STATIC_ROOT. Whitenoise then finds the files from the location defined by STATIC_ROOT (by default) and serves them at the base URL defined by STATIC_URL.

    settings.py

    Open /locallibrary/settings.py and copy the following configuration into the bottom of the file. The BASE_DIR should already have been defined in your file (the STATIC_URL may already have been defined within the file when it was created. While it will cause no harm, you might as well delete the duplicate previous reference).

    python
    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/5.0/howto/static-files/
    
    # The absolute path to the directory where collectstatic will collect static files for deployment.
    STATIC_ROOT = BASE_DIR / 'staticfiles'
    
    # The URL to use when referring to static files (where they will be served from)
    STATIC_URL = '/static/'
    

    We'll actually do the file serving using a library called WhiteNoise, which we install and configure in the next section.

    Whitenoise

    There are many ways to serve static files in production (we saw the relevant Django settings in the previous sections). The WhiteNoise project provides one of the easiest methods for serving static assets directly from Gunicorn in production.

    Check out WhiteNoise documentation for an explanation of how it works and why the implementation is a relatively efficient method for serving these files.

    The steps to set up WhiteNoise to use with the project are given here (and reproduced below):

    Install whitenoise

    Install whitenoise locally using the following command:

    bash
    pip3 install whitenoise
    

    settings.py

    To install WhiteNoise into your Django application, open /locallibrary/settings.py, find the MIDDLEWARE setting and add the WhiteNoiseMiddleware near the top of the list, just below the SecurityMiddleware:

    python
    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'whitenoise.middleware.WhiteNoiseMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]
    

    Optionally, you can reduce the size of the static files when they are served (this is more efficient). Just add the following to the bottom of /locallibrary/settings.py:

    python
    # Static file serving.
    # https://whitenoise.readthedocs.io/en/stable/django.html#add-compression-and-caching-support
    STORAGES = {
        # ...
        "staticfiles": {
            "BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage",
        },
    }
    

    You don't need to do anything else to configure WhiteNoise because it uses your project settings for STATIC_ROOT and STATIC_URL by default.

    Requirements

    The Python requirements of your web application should be stored in a file requirements.txt in the root of your repository. Many hosting services will automatically install dependencies in this file (in others you have to do this yourself). You can create this file using pip on the command line (run the following in the repo root):

    bash
    pip3 freeze > requirements.txt
    

    After installing all the different dependencies above, your requirements.txt file should have at least these items listed (though the version numbers may be different). Please delete any other dependencies not listed below, unless you've explicitly added them for this application.

    Django==5.0.2
    dj-database-url==2.1.0
    gunicorn==21.2.0
    psycopg2-binary==2.9.9
    wheel==0.38.1
    whitenoise==6.6.0
    python-dotenv==1.0.1
    

    Update your application repository in GitHub

    Many hosting services allow you to import and/or synchronize projects from a local repository or from cloud-based source version control platforms. This can make deployment and iterative development much easier.

    You should already be using GitHub to store the local library source code (this was set up in Source code management with Git and GitHub as part of setting up your development environment.

    This is a good point to make a backup of your "vanilla" project — while some of the changes we're going to be making in the following sections might be useful for deployment on any hosting service (or for development) others might not. Assuming you have already backed up all the changes made so far to the main branch on GitHub you can create a new branch to back up your changes as shown:

    bash
    # Fetch the latest main branch
    git checkout main
    git pull origin main
    
    # Create branch vanilla_deployment from the current branch (main)
    git checkout -b vanilla_deployment
    
    # Push the new branch to GitHub
    git push origin vanilla_deployment
    
    # Switch back to main
    git checkout main
    
    # Make any further changes in a new branch
    git checkout -b my_changes_for_deployment # Create a new branch
    

    Example: Hosting on PythonAnywhere

    This section provides a practical demonstration of how to host LocalLibrary on PythonAnywhere.

    Why PythonAnywhere?

    We are choosing to use PythonAnywhere for several reasons:

    • PythonAnywhere has a free beginner plan that is really free, albeit with some limitations. The fact that it is affordable for all developers is really important to MDN!

      Note: This tutorial has been hosted on Heroku, Railway, and now PythonAnywhere, migrating when the previously free plans were discontinued. We've chosen PythonAnywhere because we think this plan is likely to remain free. We've kept the Railway example too, which is not free, for comparison, and because it allows us to more easily demonstrate features such as integration with a Postgres databases running on a different service.

    • PythonAnywhere takes care of the infrastructure so you don't have to. Not having to worry about servers, load balancers, reverse proxies, and so on, makes it much easier to get started.

    • The skills and concepts you will learn when using PythonAnywhere are transferrable.

    • The service and plan limitations do not particularly impact us using PythonAnywhere for the tutorial. For example:

      • The beginner plan allows one web app at <your-username>.pythonanywhere.com, restricted outbound Internet access from your apps, low CPU/bandwidth, no IPython/Jupyter notebook support, no free Postgres database. But there is enough space for our basic site to run!
      • Custom domains are not supported (at time of writing).
      • The environment shuts down when not in use, so may be slow to restart. You can run it forever, but you will need to visit the site every three months and renew the web application.
      • There is free support for a separate MySQL database, but not Postgres. In this demonstration we'll just use the default Django SQLite database.

    PythonAnywhere is appropriate for hosting this demonstration, and can be scaled to larger projects if needed. You should take the time to determine if it is suitable for your own website.

    How does PythonAnywhere work?

    PythonAnywhere provides an entirely web-based interface for uploading, editing, and otherwise working with your application.

    Through the interface you can launch a bash console to a Ubuntu Linux environment in which you can create your application. In this demonstration we'll use the console to clone our local library GitHub repository, and create a Python environment in which we can run the web application.

    The free plan doesn't provide separate Postgres support. While we could use some other hosting service for our database, we'll just use the default SQLite database created by Django in the hosted Ubuntu environment (there is more than enough space for demonstrating the library functionality).

    Once the application is running, it can be configured for production by setting environment variables through the bash console.

    That's all the overview you need to get started.

    Get a PythonAnywhere account

    To start using PythonAnywhere you will first need to create an account:

    • Go to PythonAnywhere Plans and pricing page, and select the Create a Beginner account button.
    • Create an account with your username, email, and password, acknowledge the terms and conditions, and then select Register.
    • You'll then be logged in and redirected to the PythonAnywhere dashboard: https://www.pythonanywhere.com/user/<your_user_name>/.

    Install library from GitHub

    Next we're going open a Bash prompt, set up a virtual environment, and fetch the local library source code from GitHub. We'll also configure the default database and collect static files so that they can be served by PythonAnywhere.

    1. First open the Console management screen by selecting Consoles in the top application bar.

    2. Then select the Bash link to create and launch a new console:

      Image of PythonAnywhere Console management screen

      Note that any console that you create is saved for your later re-use, along with all its history. The green arrow above shows that this account has a console we could have opened instead.

    3. In the console, enter the following command to create a Python 3.10 virtual environment named "env_local_library" for installing the local library dependencies.

      bash
      mkvirtualenv --python=python3.10 env_local_library
      

      This is exactly the same process as covered in Setting up a Django development environment. We could have named the environment anything, and we can deactivate it and reactivate it using the commands below:

      bash
      deactivate
      workon env_local_library
      
    4. Next get the library sources from GitHub. PythonAnywhere expects you to install applications in a folder named after your site URL.

      Note: Because we're using the free account you can only name your account <your_pythonanywhere_username>.pythonanywhere.com (for example, if your username is "Odtsetseg" you will have to put the local library source into a folder named odtsetseg.pythonanywhere.com).

      Enter the following command to clone your library sources into an appropriately named folder (you will need to replace the username values with your own name):

      bash
      git clone https://github.com/<github_username>/django-locallibrary-tutorial.git <your_pythonanywhere_username>.pythonanywhere.com
      
      # Navigate into the new folder
      cd <your_pythonanywhere_username>.pythonanywhere.com
      
    5. Install the library dependencies using the requirements.txt file:

      bash
      pip3 install -r requirements.txt
      
    6. Create and configure an SQLite database on the hosting computer (just as we did during development).

      bash
      python manage.py migrate
      

      Note: For the Railway example we will Configure a Postgres database, and connect to it by setting the DATABASE_URL environment variable. It is important that migrate is called after configuring what database to use database.

    7. Collect all the static files into a location where they can be served in production:

      bash
      python manage.py collectstatic --no-input
      
    8. Create a superuser for accessing the site (as covered in the Django admin site section):

      bash
      python manage.py createsuperuser
      

      Note the details, as you'll need them to test your site.

    Set up the web app

    After getting the local library sources and installing the dependencies in a virtual environment, we need to tell PythonAnywhere how to find them and use them as a web app.

    1. Navigate to the Web section of the site and select the Add a new web app link:

      PythonAnywhere "Web" section showing button for adding a new app

      The Create new web app wizard will then open to guide you through configuring the main properties of the web app.

    2. Select Next to skip through the web app domain name configuration. The free account will create the domain based on your user name: <user_name>.pythonanywhere.com.

      PythonAnywhere prompt for setting the domain name of new web app

    3. In the Select a Python Web framework screen select Manual configuration.

      PythonAnywhere prompt for selecting web framework used for the application

      Manual configuration allows us complete control over how the environment is configured. This doesn't matter so much now, but it would if we were hosting multiple sites, potentially with different versions of Python and/or Django.

    4. In the Select a Python version screen select 3.10

      PythonAnywhere prompt for selecting Python version for Web application

      More generally you should select the latest version of Python allowed by the version of Django that you are using.

    5. In the Manual configuration screen select Next (the screen just explains some of the options for configuration)

      PythonAnywhere prompt explaining next configuration options

      The web app is created, and displayed in the Web section as shown. The screen has a Reload button that you can use to reload the web application after you make any further changes. As noted on the screen, you'll need to click the Run until 3 months from today button to keep the site alive for another three months (and ongoing).

      PythonAnywhere Configured Web app

    6. Scroll down to the "Code" section of the Web tab and select the link to the WSGI configuration file. This will have a name with the form /var/www/<user_name>_pythonanywhere_com_wsgi.py.

      PythonAnywhere WSGI file in Web tab, code section

      Replace the content in the file with the following text (first updating "hamishwillee" with your own username), and then select the Save button.

      python
      import os
      import sys
      
      path = '/home/hamishwillee/hamishwillee.pythonanywhere.com'
      if path not in sys.path:
          sys.path.append(path)
      
      os.environ['DJANGO_SETTINGS_MODULE'] = 'locallibrary.settings'
      
      from django.core.wsgi import get_wsgi_application
      application = get_wsgi_application()
      

      Note that the role of the WSGI file is to help the Gunicorn server find the local library application. PythonAnywhere expects this file to be in this location, which is why the WSGI file already in the project cannot be used.

    7. Scroll down to the "Virtualenv" section of the Web tab. Select the link Enter the path to a virtual env, if desired and enter the path of the virtual environment created in the previous section. If you named it "env_local_library" as suggested, the path will be: /home/<user_name>/.virtualenvs/env_local_library

      PythonAnywhere Virtual env section of Web tab

    8. Scroll down to the "Static files" section of the Web tab.

      PythonAnywhere Static files section of Web tab

      Select the Enter URL link and enter \static_files\. This is the STATIC_URL in the application settings, and reflects the location where files were copied when we ran collectstatic in the previous section.

    9. Near the top of the Web tab select the Reload button to restart the site. Then select the site URL link to launch the live site:

    PythonAnywhere Web screen with the link to launch the site highlighted

    Set ALLOWED_HOSTS and CSRF_TRUSTED_ORIGINS

    When the site is opened, at this point you'll see an error debug screen as shown below. This is a Django security error that is raised because our source code is not running on an "allowed host".

    A detailed error page with a full traceback of an invalid HTTP_HOST header

    Note: This kind of debug information is very useful when you're getting set up, but is a security risk in a deployed site. In the next section we'll show you how to disable this level of logging on the live site using environment variables.

    Open /locallibrary/settings.py in your GitHub project and change the ALLOWED_HOSTS setting to include your PythonAnywhere site URL:

    python
    ## For example, for a site URL at 'hamishwillee.pythonanywhere.com'
    ## (replace the string below with your own site URL):
    ALLOWED_HOSTS = ['hamishwillee.pythonanywhere.com', '127.0.0.1']
    
    # During development, you can instead set just the base URL
    # (you might decide to change the site a few times).
    # ALLOWED_HOSTS = ['.pythonanywhere.com','127.0.0.1']
    

    Since the applications uses CSRF protection, you will also need to set the CSRF_TRUSTED_ORIGINS key. Open /locallibrary/settings.py and add a line like the one below:

    python
    ## For example, for a site URL is at 'web-production-3640.up.railway.app'
    ## (replace the string below with your own site URL):
    CSRF_TRUSTED_ORIGINS = ['https://hamishwillee.pythonanywhere.com']
    
    # During development/for this tutorial you can instead set just the base URL
    # CSRF_TRUSTED_ORIGINS = ['https://*.pythonanywhere.com']
    

    Save these settings and commit them to your GitHub repo.

    You will then need to update the version of your project on PythonAnywhere. Assuming you're using your Bash prompt in the folder <user_name>.pythonanywhere.com, and you have pushed the changes to the main branch, then you could import them in the Bash prompt using the command:

    bash
    git pull origin main
    

    Use the Restart button on the Web tab to restart the application. If you refresh your hosted site, it should now open and display the home page of the site.

    You should be able to log in with the superuser account you created above, and create authors, genres, books, and so on, just as you did on your local computer.

    Using environment variables on PythonAnywhere

    In the section on Getting your website ready to publish we modified the application so that it can be configured using environment variables or variables in a .env file in production.

    Specifically we set up the library so that you can set:

    • DJANGO_DEBUG=False to reduce the debug tracing shown to the user when there is an error.
    • DJANGO_SECRET_KEY to some secret value in production.
    • DATABASE_URL if your application uses a hosted database (we do not in this example).

    The way that environment variables are set depends on the hosting service. For PythonAnywhere you need to read them from an environment file. We're already set up for that, so all we need to do is create the file.

    The steps are:

    1. Open a PythonAnywhere Bash prompt.

    2. Navigate to your application directory (replacing <user-name> with your own account):

      bash
      cd ~/<user-name>.pythonanywhere.com
      
    3. Set the environment variables by writing them as key-value pairs to the .env file. For example, to set DJANGO_DEBUG to False in the Bash console, enter the following command:

      bash
      echo "DJANGO_DEBUG=False" >> .env
      
    4. Restart the application.

    You can test that the operation worked by attempting to open a record that does not exist (for example, create a genre, then increment the number in the URL bar to open a record that has not yet been created). If the environment variable has been loaded you'll get a "Not found" message rather than a detailed debug trace.

    Example: Hosting on Railway

    This section provides a practical demonstration of how to install LocalLibrary on Railway.

    Why Railway?

    Warning: Railway no longer has a completely free starter tier. We've kept these instructions because Railway has some great features, and will be a better option for some users.

    Railway is an attractive hosting option for several reasons:

    • Railway takes care of most of the infrastructure so you don't have to. Not having to worry about servers, load balancers, reverse proxies, and so on, makes it much easier to get started.
    • Railway has a focus on developer experience for development and deployment, which leads to a faster and softer learning curve than many other alternatives.
    • The skills and concepts you will learn when using Railway are transferrable. While Railway has some excellent new features, other popular hosting services use many of the same ideas and approaches.
    • Railway documentation is clear and complete.
    • The service appears to be very reliable, and if you end up loving it, the pricing is predictable, and scaling your app is very easy.

    You should take the time to determine if Railway is suitable for your own website.

    How does Railway work?

    Web applications are each run in their own isolated and independent virtualized container. In order to execute your application, Railway needs to be able to set up the appropriate environment and dependencies, and also understand how it is launched. For Django apps we provide this information in a number of text files:

    • runtime.txt: states the programming language and version to use.
    • requirements.txt: lists the Python dependencies needed for your site, including Django.
    • Procfile: A list of processes to be executed to start the web application. For Django this will usually be the Gunicorn web application server (with a .wsgi script).
    • wsgi.py: WSGI configuration to call our Django application in the Railway environment.

    Once the application is running it can configure itself using information provided in environment variables. For example, an application that uses a database can get the address using the variable DATABASE_URL. The database service itself may be hosted by Railway or some other provider.

    Developers interact with Railway through the Railway site, and using a special Command Line Interface (CLI) tool. The CLI allows you to associate a local GitHub repository with a railway project, upload the repository from the local branch to the live site, inspect the logs of the running process, set and get configuration variables and much more. One of the most useful features is that you can use the CLI to run your local project with the same environment variables as the live project.

    In order to get our application to work on Railway, we'll need to put our Django web application into a git repository, add the files above, integrate with a database add-on, and make changes to properly handle static files. Once we've done all that, we can set up a Railway account, get the Railway client, and install our website.

    That's all the overview you need in order to get started.

    Update the app for Railway

    This section explains the changes you'll need to make to our LocalLibrary application to get it to work on Railway. We really only have to create a Procfile and runtime.txt file, because almost everything else is already present.

    Note that these changes will not prevent you using the local testing and workflows we've already learned.

    Procfile

    A Procfile is the web application "entry point". It lists the commands that will be executed by Railway to start your site.

    Create the file Procfile (with no file extension) in the root of your GitHub repo and copy/paste in the following text:

    web: python manage.py migrate && python manage.py collectstatic --no-input && gunicorn locallibrary.wsgi
    

    The web: prefix tells Railway that this is a web process and can be sent HTTP traffic. We then call the command Django migration command python manage.py migrate to set up the database tables. Next, we call the Django command python manage.py collectstatic to collect static files into the folder defined by the STATIC_ROOT project setting (see the section serving static files in production below). Finally, we start the gunicorn process, a popular web application server, passing it configuration information in the module locallibrary.wsgi (created with our application skeleton: /locallibrary/wsgi.py).

    You will note that we already set up the project to include gunicorn and support serving static files!

    You can also use the Procfile to start worker processes or to run other non-interactive tasks before the release is deployed.

    Runtime

    The runtime.txt file, if defined, tells Railway which version of Python to use. Create the file in the root of the repo and add the following text:

    python-3.10.2
    

    Note: Hosting providers do not necessarily support every Python runtime minor version. They will generally use the closest supported version to the value that you specify.

    Re-test and save changes to GitHub

    Before you proceed, first test the site again locally and make sure it wasn't broken by any of the changes above. Run the development web server as usual and then check the site still works as you expect on your browser.

    bash
    python3 manage.py runserver
    

    Next, let's push the changes to GitHub. In the terminal (after having navigated to our local repository), enter the following commands:

    bash
    git checkout -b railway_changes
    git add -A
    git commit -m "Added files and changes required for deployment"
    git push origin railway_changes
    

    Then create and merge the PR on GitHub.

    We should now be ready to start deploying LocalLibrary on Railway.

    Get a Railway account

    To start using Railway you will first need to create an account:

    • Go to railway.com and click the Login link in the top toolbar.
    • Select GitHub in the popup to log in using your GitHub credentials
    • You may then need to go to your email and verify your account.
    • You'll then be logged in to the Railway.com dashboard: https://railway.com/dashboard.

    Deploy on Railway from GitHub

    Next we'll set up Railway to deploy our library from GitHub. First choose the Dashboard option from the site top menu, then select the New Project button:

    Railway website dashboard with new project button

    Railway will display a list of options for the new project, including the option to deploy a project from a template that is first created in your GitHub account, and a number of databases. Select Deploy from GitHub repo.

    Railway website screen - deploy

    All projects in the GitHub repos you shared with Railway during setup are displayed. Select your GitHub repository for the local library: <user-name>/django-locallibrary-tutorial.

    Railway website screen showing a dialog to choose an existing GitHub repository or choose a new one

    Confirm your deployment by selecting Deploy Now.

    Confirmation screen - select deploy

    Railway will then load and deploy your project, displaying progress on the deployments tab. When deployment successfully completes, you'll see a screen like the one below.

    Railway website screen - deployment

    You can click the site URL (highlighted above) to open the site in a browser (it still won't work, because the setup is not complete).

    Set ALLOWED_HOSTS and CSRF_TRUSTED_ORIGINS

    When the site is opened, at this point you'll see an error debug screen as shown below. This is a Django security error that is raised because our source code is not running on an "allowed host".

    A detailed error page with a full traceback of an invalid HTTP_HOST header

    Note: This kind of debug information is very useful when you're getting set up, but is a security risk in a deployed site. We'll show you how to disable it once the site is up and running.

    Open /locallibrary/settings.py in your GitHub project and change the ALLOWED_HOSTS setting to include your Railway site URL:

    python
    ## For example, for a site URL at 'web-production-3640.up.railway.app'
    ## (replace the string below with your own site URL):
    ALLOWED_HOSTS = ['web-production-3640.up.railway.app', '127.0.0.1']
    
    # During development, you can instead set just the base URL
    # (you might decide to change the site a few times).
    # ALLOWED_HOSTS = ['.railway.com','127.0.0.1']
    

    Since the applications uses CSRF protection, you will also need to set the CSRF_TRUSTED_ORIGINS key. Open /locallibrary/settings.py and add a line like the one below:

    python
    ## For example, for a site URL is at 'web-production-3640.up.railway.app'
    ## (replace the string below with your own site URL):
    CSRF_TRUSTED_ORIGINS = ['https://web-production-3640.up.railway.app']
    
    # During development/for this tutorial you can instead set just the base URL
    # CSRF_TRUSTED_ORIGINS = ['https://*.railway.app']
    

    Then save your settings and commit them to your GitHub repo (Railway will automatically update and redeploy your application).

    Provision and connect a Postgres SQL database

    Next we need to create a Postgres database and connect it to the Django application that we just deployed. (If you open the site now you'll get a new error because the database cannot be accessed). We will create the database as part of the application project, although you can create the database in its own separate project.

    On Railway, choose the Dashboard option from the site top menu and then select your application project. At this stage it just contains a single service for your application (this can be selected to set variables and other details of the service). The Settings button can be selected to change project-wide settings. Select the New button, which is used to add services to the project.

    Railway project with new service button highlighted

    Select Database when prompted about the type of service to add:

    Railway project - select database as new service

    Then select Add PostgreSQL to start adding the database

    Railway project - select Postgres as new service

    Railway will then provision a service containing an empty database in the same project. On completion you will now see both the application and database services in the project view.

    Railway project with application and Postgres database service

    Select the web service and then the Variables tab. Select New Variable and then in the Variable name box, select Add reference. Scroll down and select DATABASE_URL (this is the name of the variable that we set up the locallibrary to read as an environment variable).

    Railway website screen selecting a DATABASE_URL

    Then select Add to add the variable reference and finally Deploy (this will appear in a popup). Note that you could also have opened the Postgres database, then its variable tab, and copied the variable across.

    If you open the project now it should display just as it did locally. Note however that there is no way to populate the library with data yet, because we have not yet created a superuser account. We'll do that using the CLI tool on our local computer.

    Install the client

    Download and install the Railway client for your local operating system by following the instructions here.

    After the client is installed you will be able to run commands. Some of the more important operations include deploying the current directory of your computer to an associated Railway project (without having to upload to GitHub), and running your Django project locally using the same settings as you have on the production server. We show these in the next sections.

    You can get a list of all the possible commands by entering the following in a terminal.

    bash
    railway help
    

    Note: In the following section we use railway login and railway link to link the current project to a directory. If you are logged out by the system, you will need to call both commands again to re-link the project.

    Configure a superuser

    In order to create a superuser, we need to call the Django createsuperuser command against the production database (this is the same operation as we ran locally in Django Tutorial Part 4: Django admin site > Creating a superuser). Railway doesn't provide direct terminal access to the server, and we can't add this command to the Procfile because it is interactive.

    What we can do is call this command locally on our Django project when it is connected to the production database. The Railway client makes this easy by providing a mechanism to run commands locally using the same environment variables as the production server, including the database connection string.

    First open a terminal or command prompt in a git clone of your locallibrary project. Then log into your browser account using the login or login --browserless command (follow any resulting prompts and instructions from the client or website to complete the login):

    bash
    railway login
    

    Once logged in, link your current locallibrary directory to the associated Railway project using the following command. Note that you will need to select/enter a particular project when prompted:

    bash
    railway link
    

    Now that the local directory and project are linked you can run the local Django project with settings from the production environment. First ensure that your normal Django development environment is ready. Then call the following command, entering name, email, and password as required:

    bash
    railway run python manage.py createsuperuser
    

    You should now be able to open your website admin area (https://[your-url].railway.app/admin/) and populate the database, just as shown in Django Tutorial Part 4: Django admin site.

    Setting configuration variables

    The final step is to make the site secure. Specifically, we need to disable debug logging and set a secret CSRF key. The work to read the needed values from environment variables was done in getting your website ready to publish (see DJANGO_DEBUG and DJANGO_SECRET_KEY).

    Open the information screen for the project and select the Variables tab. This should already have the DATABASE_URL as shown below.

    Railway - add a new variable screen

    There are many ways to generate a cryptographically secret key. A simple way is to run the following Python command on your development computer:

    bash
    python -c "import secrets; print(secrets.token_urlsafe())"
    

    Select the New Variable button and enter the key DJANGO_SECRET_KEY with your secret value (then select Add). Then enter the key DJANGO_DEBUG with the value False. The final set of variables should look like this:

    Railway screen showing all the project variables

    Debugging

    The Railway client provides the logs command to show the tail of logs (a more full log is available on the site for each project):

    bash
    railway logs
    

    If you need more information than this can provide you will need to start looking into Django Logging.

    Summary

    That's the end of this tutorial on setting up Django apps in production, and also the series of tutorials on working with Django. We hope you've found them useful. You can check out a fully worked-through version of the source code on GitHub here.

    The next step is to read our last few articles, and then complete the assessment task.

    See also