#424Shannon entropyEasyProbabilityStatistics
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...
▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.
- •Reference: fair coin is one bit
- •Example: uniform over four is two bits
- •Sample: skewed binary distribution