Shannon entropyEasynumpyinformation-theoryentropystatistics
Shannon entropy
Background
Shannon entropy measures the average uncertainty (in bits) of a discrete distribution. A fair coin has 1 bit of entropy; a certain outcome has 0. Entropy is the foundation of information theory and shows up everywhere in ML — it is the impurity criterion for decision-tree splits and the basis of cross-entropy loss.
Problem statement
Implement shannon_entropy(p) for a discrete probability distribution:
Skip zero-probability terms (treat ). The result is in bits.
Input
p—np.ndarray(K,), a probability distribution (non-negative, sums to 1).
Output
A float: the entropy in bits.
Examples
Example 1
Input: p = [0.5, 0.5]
Output: 1.0
Explanation: a fair binary choice needs exactly one bit: .
Constraints
- Use so the answer is in bits.
- Ignore entries where (their contribution is 0, and is undefined).
- Entropy is maximized () by the uniform distribution and minimized (0) by a point mass.
Notes
- Switching to natural log gives entropy in nats; the only difference is the log base.
- Entropy is the expected "surprise" ; rare events carry more bits of information.
Python
Loading...
This problem ships 5 hidden tests. They run in your browser via Pyodide — no backend, no submission queue. Press ▶ Run tests to execute.
- •Fair coin has 1 bit
- •Certain outcome has 0 entropy
- •Uniform over K has log2(K) bits
- •Zero-probability terms are skipped (no NaN)
- •Uniform maximizes entropy over the same support size