Neural Mastery
← Practice
Bayes' Rule Categorical Posteriormedium

Bayes' Rule Categorical Posterior

medium Math for ML 10-15 min

NumPy allowed · plain Python earns 10 bonus points

Linear algebra step 1/4

A vector transforms

Matrix multiplication is the first computation behind every model.
Open lesson →
01vector
02matrix
03transform
04result
[2, −1] × [[1, 2], [−.5, 1]] = [0, −2]

Computed matrix × vector transformation

Compute the exact posterior distribution over discrete hypotheses using Bayes' rule.

Related Skills

Task

Implement bayes_posterior(priors, likelihoods): given prior probabilities P(H_k) and likelihoods of evidence P(E | H_k), compute unnormalized products u_k = priors[k] * likelihoods[k]. Normalize by sum(u) so that posteriors sum to 1. Return list of posterior probabilities rounded to 4 decimals.

Function Signature

bayes_posterior(priors: list[float], likelihoods: list[float]) -> list[float]

Examples

Example 1: Uniform Prior Two Hypotheses
Input: priors = [0.5, 0.5] likelihoods = [0.8, 0.2]
Output: [0.8, 0.2]
Explanation: Symmetric prior Bayesian update.
Example 2: Biased Medical Test
Input: priors = [0.01, 0.99] likelihoods = [0.95, 0.05]
Output: [0.161, 0.839]
Explanation: Classic base rate fallacy test update.

Constraints

  • priors and likelihoods have length K >= 2.
  • Sum of priors is ~1.0.
Python3Saved ✓
def bayes_posterior(priors: list[float], likelihoods: list[float]) -> list[float]:
"""Compute posterior probabilities P(H_k | E) = P(E | H_k) * P(H_k) / sum_j P(E | H_j) * P(H_j).
Return list of posterior probabilities rounded to 4 decimals."""
# Your implementation here
pass

Case 1: Uniform Prior Two Hypotheses
Input: priors = [0.5, 0.5] likelihoods = [0.8, 0.2]
Expected: [0.8, 0.2]
Case 2: Biased Medical Test
Input: priors = [0.01, 0.99] likelihoods = [0.95, 0.05]
Expected: [0.161, 0.839]