Algorithm Search⌘K

Definitionintro

Shannon diversity index

Also called Shannon-Wiener index.

The entropy of the relative species abundances in a community, which grows with both the number of species and their evenness.

The Shannon diversity index of a community is the Shannon entropy of its relative species abundances, H=−∑ipiln⁡piH = -\sum_i p_i \ln p_i. It is 0 when one species makes up the whole community. It grows when species are added, and it grows when the abundances become more even. For SS species it is at most ln⁡S\ln S, the value of a perfectly even community. Ecologists usually compute it with the natural logarithm, so its unit is the nat. The number eHe^H is easier to read: it is the number of equally common species that would give the same entropy, the effective number of species. The index is also called the Shannon-Wiener or the Shannon-Weaver index, but Wiener did not define it.

Definition

Let a community have SS species with relative abundances p1,…,pS≥0p_1, \ldots, p_S \ge 0 and ∑i=1Spi=1\sum_{i=1}^{S} p_i = 1. The Shannon diversity index is

H=−∑i=1Spiln⁡pi,0ln⁡0=0.H = -\sum_{i=1}^{S} p_i \ln p_i, \qquad 0 \ln 0 = 0.

The effective number of species is D1=eHD_1 = e^H, and Pielou's evenness is J=H/ln⁡SJ = H / \ln S for S≥2S \ge 2.

In a sample of nn individuals with nin_i of species ii, the plug-in estimate is

H^=−∑i:ni>0ninln⁡nin=ln⁡n−1n∑i:ni>0niln⁡ni.\hat H = -\sum_{i : n_i > 0} \frac{n_i}{n} \ln \frac{n_i}{n} = \ln n - \frac{1}{n} \sum_{i : n_i > 0} n_i \ln n_i.

It has negative bias: unseen species add nothing, and even for the species that are seen, E[H^]<H\mathbb{E}[\hat H] < H. The Miller-Madow correction adds (Sobs−1)/(2n)(S_{obs} - 1) / (2 n), with SobsS_{obs} the number of observed species. This is the first term of the bias for a fixed number of species and large nn (an asymptotic result, not an exact correction).

Properties that follow from the definition (theorems):

  • 0≤H≤ln⁡S0 \le H \le \ln S. H=0H = 0 if and only if one pi=1p_i = 1, and H=ln⁡SH = \ln S if and only if all pi=1/Sp_i = 1/S.
  • H=ln⁡S−DKL(p ∥ u)H = \ln S - D_{KL}(p \,\|\, u), where uu is the uniform distribution on the SS species and DKLD_{KL} is the Kullback-Leibler divergence. So ln⁡S−H\ln S - H measures how far the community is from even.
  • Grouping: if the species are split into groups with total abundances wgw_g, then HH is the entropy of (wg)(w_g) plus ∑gwgHg\sum_g w_g H_g, where HgH_g is the entropy of the abundances within group gg.
  • A change of the base of the logarithm multiplies HH by a constant: HH in bits is H/ln⁡2H / \ln 2.

Examples and non-examples

  • The abundances (5,3,2)(5, 3, 2) give p=(0.5,0.3,0.2)p = (0.5, 0.3, 0.2) and H=1.029653H = 1.029653 nats, or 1.4854751.485475 bits. Then eH=2.800094e^H = 2.800094, so the community is as diverse as 2.82.8 equally common species, and J=1.029653/ln⁡3=0.937231J = 1.029653 / \ln 3 = 0.937231. As a sample of n=10n = 10, the Miller-Madow form is 1.029653+2/20=1.1296531.029653 + 2/20 = 1.129653.
  • The counts (10,6,4)(10, 6, 4) have the same proportions, so they give the same H=1.029653H = 1.029653. The index depends only on the proportions. The Miller-Madow form is 1.029653+2/40=1.0796531.029653 + 2/40 = 1.079653, closer to the plug-in value because the sample is larger.
  • Four species with 25 individuals each give H=ln⁡4=1.386294H = \ln 4 = 1.386294, eH=4e^H = 4 and J=1J = 1.
  • The counts (97,1,1,1)(97, 1, 1, 1) have four species, but one species makes up 97 percent. They give H=0.167701H = 0.167701, eH=1.182582e^H = 1.182582 and J=0.120970J = 0.120970.
  • Non-example: a raw count. −∑niln⁡ni-\sum n_i \ln n_i with counts in place of proportions is not the index. It depends on the sample size and can be negative.
  • Non-example: comparing samples of unequal size. The plug-in H^\hat H of a sample of 50 individuals and that of a sample of 5000 are not comparable, because the bias depends on nn. Use rarefaction to a common size, or a bias-corrected estimate.
  • Non-example: a difference of entropies as a difference of diversity. HH is not linear in the number of species: going from 1 to 2 equally common species adds 0.6930.693, and going from 100 to 101 adds 0.0100.010. Compare eHe^H instead.

The pseudocode below computes the plug-in estimate and the derived quantities from a list of counts.

  1. SHANNON(counts)
  2. 1n ← the sum of the counts; S ← the number of counts > 0
  3. 2H ← 0
  4. 3for each count c > 0: p ← c / n; H ← H - p ln p
  5. 4return (H, e^H, H / ln S if S ≥ 2, H + (S - 1) / (2 n))
  • Shannon entropy is the same quantity for any discrete distribution, with the base 2 logarithm in coding.
  • The Simpson diversity index uses ∑pi2\sum p_i^2 in place of ∑piln⁡pi\sum p_i \ln p_i. It gives more weight to common species. Hill's diversity numbers Dq=(∑piq)1/(1−q)D_q = (\sum p_i^q)^{1/(1 - q)} join both: D0=SD_0 = S, D1=eHD_1 = e^H (the limit as q→1q \to 1) and D2=1/∑pi2D_2 = 1 / \sum p_i^2.
  • Perplexity in language modeling is the same exponential of an entropy, the effective number of choices.
  • Gini impurity in decision trees is the Gini-Simpson index 1−∑pi21 - \sum p_i^2, the order 2 counterpart of HH.
  • Rarefaction and the Chao1 estimator address the same sampling problem for the number of species, the diversity of order 0.

Code

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

shannon_diversity_index.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/shannon-diversity-index/. The authors are listed in prov/4HC8AE.jsonl.
"""The Shannon diversity index of a list of species counts.

Input: counts n_i >= 0 with a positive sum. Output: the plug-in index H in
nats, the effective number exp(H), Pielou's evenness H / ln S (None when
fewer than two species are present) and the Miller-Madow form
H + (S - 1) / (2 n). Cost: Theta(k) time for k counts and O(1) extra space.
"""

from __future__ import annotations

import math
from dataclasses import dataclass
from typing import Optional, Sequence


@dataclass(frozen=True)
class Shannon:
    h: float
    effective_number: float
    evenness: Optional[float]
    miller_madow: float


def shannon(counts: Sequence[float]) -> Shannon:
    """Compute the Shannon index and its derived values from the counts."""
    if any(c < 0 for c in counts):
        raise ValueError("counts must be >= 0")
    n = sum(counts)  # @line L1
    if n <= 0:
        raise ValueError("counts must have a positive sum")
    s = sum(1 for c in counts if c > 0)
    h = 0.0  # @line L2
    for c in counts:
        if c > 0:
            p = c / n
            h -= p * math.log(p)  # @line L3
    evenness = h / math.log(s) if s >= 2 else None
    return Shannon(h, math.exp(h), evenness, h + (s - 1) / (2 * n))  # @line L4
test_shannon_diversity_index.py 69 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/shannon-diversity-index/. The authors are listed in prov/4HC8AE.jsonl.
"""Tests of the Shannon index against the page values, the closed form
ln n - (1/n) sum n_i ln n_i, the bounds 0 <= H <= ln S and the grouping rule."""

import math
import random

import pytest

from shannon_diversity_index import shannon

TOL = 1e-6


def oracle(counts):
    n = sum(counts)
    return math.log(n) - sum(c * math.log(c) for c in counts if c > 0) / n


def test_page_values():
    r = shannon([5, 3, 2])
    assert abs(r.h - 1.029653) < TOL
    assert abs(r.h / math.log(2) - 1.485475) < TOL
    assert abs(r.effective_number - 2.800094) < TOL
    assert abs(r.evenness - 0.937231) < TOL
    assert abs(r.miller_madow - 1.129653) < TOL
    assert abs(shannon([10, 6, 4]).miller_madow - 1.079653) < TOL
    assert abs(shannon([25] * 4).effective_number - 4) < 1e-12
    r = shannon([97, 1, 1, 1])
    assert abs(r.h - 0.167701) < TOL and abs(r.evenness - 0.120970) < TOL


def test_edge_cases():
    r = shannon([7])
    assert r.h == 0 and r.effective_number == 1 and r.evenness is None
    assert shannon([0, 4, 0]).h == 0
    with pytest.raises(ValueError):
        shannon([0, 0])
    with pytest.raises(ValueError):
        shannon([3, -1])


def test_random_against_oracle_and_bounds():
    rng = random.Random(31)
    for _ in range(500):
        counts = [rng.randint(0, 20) for _ in range(rng.randint(1, 12))]
        if sum(counts) == 0:
            counts[0] = 1
        s = sum(1 for c in counts if c > 0)
        h = shannon(counts).h
        assert abs(h - oracle(counts)) < 1e-9
        assert -1e-12 <= h <= math.log(s) + 1e-12
        # H = ln S - KL(p || uniform on the S present species).
        n = sum(counts)
        kl = sum(c / n * math.log((c / n) * s) for c in counts if c > 0)
        assert abs(h - (math.log(s) - kl)) < 1e-9


def test_grouping_rule():
    rng = random.Random(32)
    for _ in range(200):
        a = [rng.randint(1, 9) for _ in range(rng.randint(1, 5))]
        b = [rng.randint(1, 9) for _ in range(rng.randint(1, 5))]
        n = sum(a) + sum(b)
        wa, wb = sum(a) / n, sum(b) / n
        left = shannon(a + b).h
        right = shannon([sum(a), sum(b)]).h + wa * shannon(a).h + wb * shannon(b).h
        assert abs(left - right) < 1e-9

References

  1. Claude E. Shannon, A mathematical theory of communication, Bell System Technical Journal 27(3), 1948, pages 379 to 423 (the entropy H = -K sum p_i log p_i and its properties)
  2. M. O. Hill, Diversity and evenness, a unifying notation and its consequences, Ecology 54(2), 1973, pages 427 to 432 (the diversity numbers of order a, with exp(H) as the number of order 1)
  3. Lou Jost, Entropy and diversity, Oikos 113(2), 2006, pages 363 to 375 (entropies and indices against the effective number of species)
  4. Anne E. Magurran, Measuring Biological Diversity, Blackwell, 2004, the chapter on diversity indices (the Shannon index, its evenness measure and its sampling properties)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/4HC8AE/text.yaml