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, . 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 species it is at most , the value of a perfectly even community. Ecologists usually compute it with the natural logarithm, so its unit is the nat. The number 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 species with relative abundances and . The Shannon diversity index is
The effective number of species is , and Pielou's evenness is for .
In a sample of individuals with of species , the plug-in estimate is
It has negative bias: unseen species add nothing, and even for the species that are seen, . The Miller-Madow correction adds , with the number of observed species. This is the first term of the bias for a fixed number of species and large (an asymptotic result, not an exact correction).
Properties that follow from the definition (theorems):
- . if and only if one , and if and only if all .
- , where is the uniform distribution on the species and is the Kullback-Leibler divergence. So measures how far the community is from even.
- Grouping: if the species are split into groups with total abundances , then is the entropy of plus , where is the entropy of the abundances within group .
- A change of the base of the logarithm multiplies by a constant: in bits is .
Examples and non-examples
- The abundances give and nats, or bits. Then , so the community is as diverse as equally common species, and . As a sample of , the Miller-Madow form is .
- The counts have the same proportions, so they give the same . The index depends only on the proportions. The Miller-Madow form is , closer to the plug-in value because the sample is larger.
- Four species with 25 individuals each give , and .
- The counts have four species, but one species makes up 97 percent. They give , and .
- Non-example: a raw count. 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 of a sample of 50 individuals and that of a sample of 5000 are not comparable, because the bias depends on . Use rarefaction to a common size, or a bias-corrected estimate.
- Non-example: a difference of entropies as a difference of diversity. is not linear in the number of species: going from 1 to 2 equally common species adds , and going from 100 to 101 adds . Compare instead.
The pseudocode below computes the plug-in estimate and the derived quantities from a list of counts.
SHANNON(counts)- 1
n ← the sum of the counts; S ← the number of counts > 0 - 2
H ← 0 - 3
for each count c > 0: p ← c / n; H ← H - p ln p - 4
return (H, e^H, H / ln S if S ≥ 2, H + (S - 1) / (2 n))
Related definitions
- Shannon entropy is the same quantity for any discrete distribution, with the base 2 logarithm in coding.
- The Simpson diversity index uses in place of . It gives more weight to common species. Hill's diversity numbers join both: , (the limit as ) and .
- 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 , the order 2 counterpart of .
- 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.
# 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
- 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)
- 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)
- Lou Jost, Entropy and diversity, Oikos 113(2), 2006, pages 363 to 375 (entropies and indices against the effective number of species)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 4HC8AE Edit this page History Report an error Markdown