03 Bayesian Classifiers

90-Minute Main Lesson: Probability → Loss → Decision

  • Objectives: Compute a posterior from prior and likelihood; decide with a loss matrix; distinguish MLE from MAP; assess probability ranking and calibration.

  • learning path:

    • prerequisite and Bayes update 20 min → decision loss 20 min → estimation and the naive assumption 20 min → Fuyao Glass main case 20 min → checks and synthesis 10 min.

    • GMM/EM is an extension.

  • Answer first: Given \(P(D)=0.1\), \(P(+|D)=0.8\), and \(P(+|\neg D)=0.2\), compute \(P(+)\).

  • Feedback: \(P(+)=0.8\times0.1+0.2\times0.9=0.26\), so \(P(D|+)\approx0.308\), not 0.8.

Welcome to Chapter 3: Bayesian Classifiers

Bayesian Classifier Workflow A three-stage diagram showing the process of a Bayesian classifier: Data Input (X), Probabilistic Model (P(Y|X)), and Decision Output (Y), connected by Learn and Predict steps. Bayesian Classifier Workflow 1. Data Input X 2. Probabilistic Model P(Y|X) 3. Decision Output Y Learn Predict

The Core Question: How to Make Optimal Classifications Under Uncertainty?

Imagine you are a credit manager at a bank, facing a critical decision every day:

Should this loan application be approved?

This links two distinct tasks: classify the applicant’s default state, then choose a lending action using the loss matrix.

  • Input Data (X): Applicant’s features, such as annual income, credit score, debt level, etc.
  • True State (\(Y\)): No Default or Default.
  • Model Output: the posterior \(P(Y=\text{Default}\mid X)\) (or a predicted label \(\hat Y\)).
  • Business Action (\(a\)): Approve or Reject; the posterior and loss matrix jointly determine the action.

Case Study: Credit Approval Decisions

Let’s look at some simplified applicant data.

Applicant ID Annual Income ($10k) Credit Score History of Default Our Decision
001 15 720 No ?
002 6 580 Yes ?
003 9 650 No ?

Objective: Estimate \(P(Y\mid X)\) from applicant features, then select the action \(a^*(X)\) with minimum conditional risk. A class label is not a lending action.

Why Choose the Bayesian Approach?

Bayesian classifiers provide a powerful decision-making framework based on probability theory.

Four Advantages of Bayesian Methods A mind map with a central node for 'Bayesian Methods' branching out to four advantages: Handling Uncertainty, Incorporating Prior Knowledge, Strong Interpretability, and Model Elegance. Four Advantages of Bayesian Methods Bayesian Methods Handles unknowns Probability outputs Uses prior knowledge Evidence + expertise Highly Interpretable Transparent decisions Model Elegance Coherent math foundation

Our Learning Roadmap for This Chapter

We will build a complete Bayesian decision-making system step by step.

Bayesian Classifier Learning Roadmap A horizontal roadmap with six steps, showing the learning process from probability basics to practical applications. 1. ProbabilityThe foundation 2. Bayes RuleThe update rule 3. EstimationFit parameters 4. GMMsMixture models 5. Naive BayesThe classifier 6. Real-WorldIssuesTune & validate

Part 1: Foundations of Probability

The Language of Uncertainty

Core Concept 1: Prior Probability

The Prior Probability \(P(y=c)\) is our inherent belief or the historical frequency of a class c occurring, before observing any new data.

In the credit approval example, the prior probability refers to:

Without looking at any specific information about an applicant, what is the probability that a customer will default, based on the bank’s historical data?

It is the baseline or starting point for our decision.

Prior Probability: A Concrete Example

Suppose the bank has processed 10,000 loan applications in the past, of which 500 ultimately defaulted.

Prior Probability: Loan Default Example A donut chart and formulas showing the prior probabilities of loan default (5%) and non-default (95%) based on a total of 10,000 applications. Prior Probability: Loan Default Example Applications 10,000 P(No default) = 95% P(Default) = 5% Base rate

Core Concept 2: Probability Density Function (PDF)

For continuous variables (like income, age), we use a Probability Density Function (p(x)) to describe their distribution.

  • The PDF itself is not a probability; p(x) can be greater than 1.
  • The probability that a variable falls into an interval [a, b] is the integral of the PDF over that interval: \(P(a \le x \le b) = \int_a^b p(x) dx\).
  • The total area under the curve is 1.

PDF (Continuous) vs. PMF (Discrete)

An important distinction:

Comparison of PDF (Probability Density Function) and PMF (Probability Mass Function) A side-by-side comparison. The left panel shows a continuous PDF curve where probability is the area under the curve for an interval. The right panel shows a discrete PMF where probability is the height of the bar at each point. PDF (Probability Density) Continuous variable(e.g., height) Interval probability = area a b PMF (Probability Mass) Discrete variable(e.g., die roll) k Point probability = stem height

Visualization: The Normal (Gaussian) Distribution

The Normal distribution is the most common PDF in finance and business, defined by its mean μ (center) and variance σ² (spread).

Probability Density Function (PDF) of Normal Distributions A chart comparing two Normal distributions on a dark background: N(μ=0, σ²=1) in red and N(μ=2, σ²=0.36) in blue. The blue curve is taller and narrower, indicating a smaller variance. Normal Distribution PDF 0.0 0.2 0.4 0.6 -2 0 2 4 x (Value) p(x) (Probability Density) N(μ=0, σ²=1) N(μ=2, σ²=0.36)

Core Concept 3: Class-Conditional Probability

The Class-Conditional Probability \(p(x | y=c)\) answers: “If we already know a sample belongs to class c, what is the probability density of observing data x?”

In our credit approval example:

  • p(income | y = Default): Given a customer is a defaulter, what does their income distribution look like?
  • p(income | y = No Default): Given a customer is a good client, what does their income distribution look like?

This is the bridge connecting our observation (data x) and the unknown state (class y). We call this the Likelihood.

Visualizing Income Distributions for Different Customer Classes

Suppose historical data shows that non-defaulting customers (blue) generally have higher incomes than defaulting customers (red).

Income Distributions of Different Customer Groups Two overlapping probability density curves. The red curve (defaulters) peaks at a lower income, while the blue curve (non-defaulters) peaks at a higher income. A vertical line shows the likelihoods for a new applicant with an income of $120k. 50k 100k 150k 200k 250k Annual Income ($) Density Applicant income: $120k p(x|default) ≈ 0.18 p(x|no default) ≈ 0.08 Schematic density heights—not posterior probabilities or empirical estimates Income Distributions of Different Customer Groups

Core Concept 4: Posterior Probability

The Posterior Probability \(P(y=c | x)\) is the core of Bayesian decision-making. It is our updated belief that a sample belongs to class c after we have observed the data x.

It answers our most pressing question:

“Given that this applicant’s income is $120k, what is the probability that they are a default risk?”

This is the direct basis for our decision!

  • The likelihood curves and displayed values are schematic: they teach the “prior × likelihood → posterior” calculation and are not estimates from a documented loan sample.

  • An empirical use must separately specify the sample, units, and density-estimation method.

Bayes’ Theorem: The Magic Formula from Prior to Posterior

Bayes’ Theorem is the mathematical cornerstone that connects these four core concepts.

\[ \large{P(y=c \mid \mathbf{x}) = \frac{p(\mathbf{x} \mid y=c) P(y=c)}{p(\mathbf{x})}} \]

This formula tells us how to update our beliefs using data.

An Intuitive Reading of Bayes’ Theorem

\[ \large{\underbrace{P(y=c \mid \mathbf{x})}_{\text{Posterior}} = \frac{\overbrace{p(\mathbf{x} \mid y=c)}^{\text{Likelihood}} \times \overbrace{P(y=c)}^{\text{Prior}}}{\underbrace{p(\mathbf{x})}_{\text{Evidence}}}} \]

  • Posterior: Our updated belief after seeing the evidence.
  • Likelihood: The probability of seeing this evidence, given the class.
  • Prior: Our initial belief.
  • Evidence: The overall probability of seeing this evidence, used for normalization.

Visualizing the Components of Bayes’ Theorem

Visual Breakdown of Bayes' Theorem A diagram showing the four parts of Bayes' Theorem: Posterior P(y|x) equals Likelihood p(x|y) times Prior P(y), all divided by Evidence p(x). P(y|x) Posterior The Final Answer = × p(x|y) Likelihood P(y) Prior p(x) Evidence Normalization Data Evidence Initial Belief

Calculating the ‘Evidence’ p(x): The Law of Total Probability

The denominator p(x) is the total probability of observing the data x, regardless of its class. We calculate it using the Law of Total Probability.

Law of Total Probability A diagram showing the entire sample space partitioned into two categories, C1 (No Default) and C2 (Default). An event 'x' overlaps with both. The total probability of x, p(x), is the sum of its intersections with each category. Law of Total Probability C₁: No Default (Prior: P(C₁)) C₂: Default (Prior: P(C₂)) Event x p(x|C₁)P(C₁) p(x|C₂)P(C₂) p(x) = p(x|C₁)P(C₁) + p(x|C₂)P(C₂)

Part 2: Bayesian Decision Theory

From Probabilities to Profits: The Art of Optimal Decision

With Posterior Probabilities, How Do We Decide?

We can now calculate P(y=Default | x) and P(y=No Default | x).

A seemingly simple and intuitive rule is: Choose the class with the highest posterior probability.

\[ \large{f(\mathbf{x}) = \underset{c}{\arg\max} \ P(y=c \mid \mathbf{x})} \]

This is known as the Maximum a Posteriori (MAP) decision rule.

The Hidden Assumption of the MAP Rule

The MAP rule implies a very strong assumption: the cost of all types of errors is the same.

In the real world, this assumption is often false.

The Costs of Misclassification Are Different: Introducing the Loss Function

In credit approval, there are two types of errors:

  1. Type I Error (False Negative): Misclassifying a defaulting customer as ‘No Default’ (approving a bad loan).
    • Consequence: The bank loses the principal, a huge cost.
  2. Type II Error (False Positive): Misclassifying a non-defaulting customer as ‘Default’ (rejecting a good customer).
    • Consequence: The bank loses potential interest income, a smaller cost.

Quantifying Costs: The Loss Matrix L(a, y)

We use a Loss Matrix L(a, y) to quantify the cost of taking action \(a\) when the applicant’s true state is \(y\).

Loss Matrix for Credit Approval A 2x2 table showing the costs of correctly or incorrectly classifying defaulting/non-defaulting customers. If Our Decision is... If Reality is... Decision: Approve Decision: Reject Nodefault Default Loss: -$20k (Gain Interest) Loss: $1k (Opportunity Cost) Loss: $500k (Loss of Principal) Loss: $0 (Loss Avoided)

Expected Loss: Measuring the Average Cost of a Decision

For a given observation \(x\), the Expected Loss or Conditional Risk \(R(a|x)\) is the posterior-weighted loss of taking action \(a\) over all possible true states \(y\).

\[ \large{R(a \mid \mathbf{x}) = \sum_y L(a, y) P(Y=y \mid \mathbf{x})} \]

This formula calculates: “If I take action \(a\), what average loss will I incur?”

Calculating Expected Loss: A Step-by-Step Example

Suppose for a certain applicant x, we have calculated the posterior probabilities:

  • P(y=No Default | x) = 0.8
  • P(y=Default | x) = 0.2

And recall our loss matrix (simplified to numbers):

  • L(Approve, No Default) = -20 (gain 20k)
  • L(Approve, Default) = 500 (lose 500k)
  • L(Reject, No Default) = 1 (opportunity cost 1k)
  • L(Reject, Default) = 0

Calculating R(Approve | x)

If we choose to ‘Approve’ this loan:

R(Approve | x) = L(Approve, No Default) * P(No Default|x) + L(Approve, Default) * P(Default|x)

\[ \large{R(\text{Approve} \mid \mathbf{x}) = (-20) \times 0.8 + (500) \times 0.2 = -16 + 100 = 84} \]

The expected loss for choosing ‘Approve’ is $84k.

Calculating R(Reject | x)

If we choose to ‘Reject’ this loan:

R(Reject | x) = L(Reject, No Default) * P(No Default|x) + L(Reject, Default) * P(Default|x)

\[ \large{R(\text{Reject} \mid \mathbf{x}) = (1) \times 0.8 + (0) \times 0.2 = 0.8} \]

The expected loss for choosing ‘Reject’ is $0.8k.

The Bayes Decision Rule: Minimize Expected Loss

The optimal action \(a^*(x)\) minimizes the conditional risk \(R(a|x)\) for each applicant.

\[ \large{a^*(\mathbf{x}) = \underset{a}{\arg\min} \ R(a \mid \mathbf{x})} \]

In our example: R(Approve|x) = 84 vs. R(Reject|x) = 0.8. Since 0.8 < 84, the optimal decision is to ‘Reject’.

Even though the applicant has an 80% chance of being a good customer! The 20% risk of default, combined with the high cost, makes rejection the more rational choice.

A Special Case: The 0-1 Loss Function

If the cost of all misclassifications is equal (e.g., 1) and the cost of correct classification is 0, this is the 0-1 loss function.

\[ \large{L(i, j) = \begin{cases} 0, & \text{if } i = j \\ 1, & \text{if } i \neq j \end{cases}} \]

Decision Rule Under 0-1 Loss

Under 0-1 loss, the expected loss R(i|x) simplifies to:

\[ \large{R(i \mid \mathbf{x}) = \sum_{j=1}^{C} L(i, j) P(y=j \mid \mathbf{x}) = \sum_{j \neq i} P(y=j \mid \mathbf{x})} \]

\[ \large{= 1 - P(y=i \mid \mathbf{x})} \]

Minimizing R(i|x) is equivalent to minimizing 1 - P(y=i|x), which means maximizing the posterior probability P(y=i|x).

Therefore, the MAP decision rule is a special case of minimizing expected loss under a 0-1 loss function.

Visualizing the Decision Boundary

The decision rule divides feature space into optimal-action regions. Under 0-1 loss, actions correspond one-to-one with class labels; only in that special case may the regions be called class regions directly.

For the MAP rule, the decision boundary is where the posterior probabilities are equal, e.g., P(y=1|x) = P(y=2|x).

Decision Boundary Illustration Two overlapping normal distribution curves, representing the class-conditional probabilities for two classes. Their intersection point determines the decision boundary. x p(x | y=1)P(y=1) p(x | y=2)P(y=2) Decision Boundary Decide: Class 1 Decide: Class 2

Part 3: Parameter Estimation

Learning from Data: The Estimation Challenge

The Real-World Challenge: We Don’t Know the True Probability Distributions

So far, we have assumed that P(y=c) and p(x|y=c) are known.

In reality, we don’t know them. All we have is a set of historical data (the training set).

Core Task: How can we estimate the parameters of these probability distributions from the data?

The Parameter Estimation Approach

  1. Choose a Model: We first assume the data follows a specific form of probability distribution, such as a Gaussian distribution \(\mathcal{N}(\mu, \sigma^2)\).
  2. Estimate Parameters: Our task then becomes estimating the model’s unknown parameters, \(\theta = (\mu, \sigma^2)\), from the data.
Parameter Estimation Flow A three-stage flowchart: 1. Training Data is input into 2. A Parameter Estimator, which outputs 3. A Probability Model with estimated parameters. Parameter Estimation Flow 1. Training data 2. Estimate θ θ̂ = ? 3. Probability model p(x | θ̂)

Method 1: Maximum Likelihood Estimation (MLE)

The core idea of Maximum Likelihood Estimation (MLE) is:

Choose the set of parameters \(θ\) that maximizes the joint probability of observing the data we have, \(X = {x_1, ..., x_N}\).

In other words, which set of parameters provides the “best explanation” for the data we see?

The Likelihood Function L(θ|X)

We define the likelihood function L(θ|X), which represents the probability of observing data X given parameters θ.

Assuming the samples are independent and identically distributed (i.i.d.), the joint probability is the product of individual sample probabilities:

\[ \large{L(\theta \mid X) = p(X \mid \theta) = \prod_{n=1}^{N} p(x_n \mid \theta)} \]

Our goal is to find the θ* that maximizes L(θ|X).

\[ \large{\theta^*_{MLE} = \underset{\theta}{\arg\max} \ L(\theta \mid X)} \]

MLE Trick: Use the Log-Likelihood Function

Products are difficult to differentiate. We typically maximize the log-likelihood function LL(θ|X) instead.

Since the logarithm is a monotonically increasing function, maximizing L is the same as maximizing log(L).

\[ \large{LL(\theta \mid X) = \log p(X \mid \theta) = \sum_{n=1}^{N} \log p(x_n \mid \theta)} \]

This turns the product into a sum, greatly simplifying the calculation.

MLE Example: Estimating the Mean of a Normal Distribution

Suppose our data \(x_1, ..., x_N\) comes from a Normal distribution with a known variance \(σ²\) but an unknown mean \(μ\).

The log-likelihood function is:

\[ \large{LL(\mu) = \sum_{n=1}^{N} \log \left( \frac{1}{\sqrt{2\pi\sigma^2}} e^{-\frac{(x_n - \mu)^2}{2\sigma^2}} \right)} \]

By taking the derivative with respect to \(μ\), setting it to 0, and solving, we find:

\[ \large{\hat{\mu}_{MLE} = \frac{1}{N} \sum_{n=1}^{N} x_n} \]

Result: the sample mean is the MLE of the population mean.

The Limitation of MLE: Overfitting

MLE completely “trusts” the data. If the dataset is small or biased, the MLE result can be poor.

Classic example: Tossing a coin.

  • You flip a coin 3 times and get Heads, Heads, Heads.
  • MLE will estimate the probability of Heads as \(p(H) = 3/3 = 1\).
  • This implies you will never predict Tails. This is obviously unreasonable.

We need a way to incorporate our prior knowledge about the world (e.g., that coins are usually fair).

Method 2: Maximum a Posteriori (MAP) Estimation

MAP (Maximum a Posteriori) estimation builds on MLE by introducing a prior distribution p(θ) over the parameters θ themselves.

It no longer maximizes the likelihood p(X|θ), but rather the posterior probability of the parameters p(θ|X).

\[ \large{p(\theta \mid X) \propto p(X \mid \theta) p(\theta)} \]

The goal of MAP is:

\[ \large{\theta^*_{MAP} = \underset{\theta}{\arg\max} \ [p(X \mid \theta) p(\theta)]} \]

The Log-Form of MAP

Again, using logarithms simplifies the calculation:

\[ \large{\theta^*_{MAP} = \underset{\theta}{\arg\max} \ [\log p(X \mid \theta) + \log p(\theta)]} \]

\[ \large{= \underset{\theta}{\arg\max} \left[ \sum_{n=1}^{N} \log p(x_n \mid \theta) + \log p(\theta) \right]} \]

MAP: A Balance Between Data Evidence and Prior Belief

\[ \large{\underbrace{\log p(\theta\mid X)}_{\text{Log Posterior}} = \underbrace{\sum_n \log p(x_n\mid\theta)}_{\text{Log Likelihood}} + \underbrace{\log p(\theta)}_{\text{Log Prior}} + \text{constant}} \]

MAP Estimation as a Balance A balance scale metaphor. On the left pan is 'Data Likelihood', and on the right pan is 'Prior Belief'. The pivot point represents the final MAP Estimate, balancing the two. MAP Estimate Data Likelihood log p(X|θ) Prior Belief log p(θ)

MAP Interpretation Check

The final MAP estimate balances data evidence and prior belief. As sample size grows, the likelihood term usually gains influence; the prior is separately stated information, not an extra observation.

Part 4: Handling Complex Distributions

When Reality is Messy: Mixture Models

The Limitation of a Single Model

So far, we have assumed that data from a single class can be described by one simple distribution (like a single Gaussian). But what if the data distribution is more complex?

Unimodal vs. Multimodal Data Distribution The left panel shows a simple, single-peaked distribution that is well-fit by a single Gaussian curve. The right panel shows a complex, double-peaked distribution where a single Gaussian fit is poor. Simple Distribution Single Gaussian fits well Complex (Multimodal) Distribution Single Gaussian is a poor fit

Main lesson: GMM/EM is Extension; continue from MLE/MAP directly to Naive Bayes.

A Solution for Complexity: Gaussian Mixture Models (GMM)

Optional topic: Core proceeds from MLE/MAP directly to the high-dimensional Naive Bayes challenge. Return to GMM/EM only after the principal practice and summary.

What if our data distribution is a mix of several “clusters”?

For example, customer spending habits might be divided into ‘high-spending’, ‘medium-spending’, and ‘low-spending’ groups, with each group being approximately normally distributed.

The Gaussian Mixture Model (GMM) is designed precisely for this situation.

GMM Definition: A Weighted Sum of Multiple Gaussians

A GMM models a complex probability distribution as a weighted sum of K Gaussian components.

\[ \large{p(\mathbf{x}) = \sum_{k=1}^{K} \pi_k \mathcal{N}(\mathbf{x} \mid \mu_k, \Sigma_k)} \]

Where:

  • \(K\): The number of mixture components (a hyperparameter).
  • \(π_k\): The mixing coefficient (weight) of the \(k\)-th component, with \(\sum_{k=1}^{K} \pi_k = 1\).
  • \(μ_k, Σ_k\): The mean and covariance matrix of the \(k\)-th Gaussian component.

The GMM Challenge: A Latent Variable Problem

Estimating the parameters of a GMM (\(π_k, μ_k, Σ_k\)) is much more complex than for a single Gaussian.

This is because we don’t know which Gaussian component each data point \(x_n\) actually belongs to. This “membership” information is a latent variable.

This is a “chicken-and-egg” problem:

  • If we knew which cluster each point belonged to, we could easily estimate each cluster’s parameters.
  • If we knew each cluster’s parameters, we could calculate the probability of each point belonging to each cluster.

The Solution: The Expectation-Maximization (EM) Algorithm

The Expectation-Maximization (EM) algorithm is an iterative algorithm designed specifically to solve parameter estimation problems with latent variables.

It elegantly solves the “chicken-and-egg” dilemma by alternating between two steps until convergence.

The EM Algorithm: E-Step (Expectation)

E-Step (Expectation)

Based on the current model parameters, compute the posterior probability (also called the “responsibility” \(r_{nk}\)) that each data point \(x_n\) was generated by each Gaussian component \(k\).

\[ \large{r_{nk} = P(z_n=k \mid x_n; \theta_{old})} \]

In simple terms, we make a “soft assignment” for each data point, guessing how likely it is to have come from each cluster.

The EM Algorithm: M-Step (Maximization)

M-Step (Maximization)

Based on the “responsibilities” \(r_{nk}\) calculated in the E-step, update the model parameters \(π_k, μ_k, Σ_k\) to maximize the expected log-likelihood.

This is equivalent to performing a weighted MLE estimation for each cluster, where the weights are the responsibilities \(r_{nk}\).

For example, the new mean is a weighted average of all data points:

\[ \large{\mu_k^{new} = \frac{\sum_{n=1}^N r_{nk} x_n}{\sum_{n=1}^N r_{nk}}} \]

The EM Algorithm Flow

Expectation-Maximization (EM) Algorithm Flow A flowchart of the EM algorithm. It starts with parameter initialization, then enters a loop of two steps: the E-step (calculating responsibilities) and the M-step (updating parameters). The loop continues until the parameters converge. Expectation-Maximization (EM) Algorithm Flow 1. Initialize parameters (θ₀) E-Step (Expectation) Compute responsibilities E[z | x, θ] M-Step (Maximization) Update parameters Maximize expectation Repeat until convergence

After the optional topic: after GMM/EM, continue to the final summary without replaying completed Core material.

Part 5: The Naive Bayes Classifier

Putting it all Together for a Practical Solution

The Challenge: The Curse of Dimensionality

  • When our data x has many features, directly estimating the d-dimensional joint probability distribution p(x|y=c) is extremely difficult and requires vast amounts of data.

  • This is known as the “curse of dimensionality”.

Curse of Dimensionality Three panels show how a fixed number of data points becomes increasingly sparse as the dimensionality of the space increases from 1D (a line) to 2D (a square) to 3D (a cube). Curse of Dimensionality 1-Dimension 10 points coverthe line well 2-Dimensions 100 points (10²)Space becomes sparse 3-Dimensions 1000 points (10³)Extremely sparse

The ‘Naive’ Assumption: Conditional Independence of Features

The Naïve Bayes classifier makes a very bold (but often effective) simplifying assumption:

Given the class y, all features \(x_i\) are mutually independent.

This means: once we know a customer is in the ‘Default’ class, their ‘income’ level and their ‘age’ are considered independent pieces of information.

The Power of the Independence Assumption

This “naive” assumption makes calculating the joint probability incredibly simple:

The originally complex joint probability:

\[ \large{p(\mathbf{x}|y=c) = p(x_1, x_2, \ldots, x_d | y=c)} \]

Under the independence assumption, it decomposes into the product of the individual class-conditional probabilities for each feature:

\[ \large{p(\mathbf{x}|y=c) = \prod_{i=1}^{d} p(x_i | y=c)} \]

Now we only need to estimate a one-dimensional \(p(x_i|y=c)\) for each feature separately, which is much easier than estimating a high-dimensional joint distribution!

The Graphical Model of Naive Bayes

This assumption can be represented by a simple graphical model.

Graphical Model Comparison: Naive Bayes vs. General Bayesian Network The left panel shows the Naive Bayes model, where the class node Y is the parent of all feature nodes X, indicating features are conditionally independent. The right panel shows a general network where dependencies can exist between feature nodes. Naive Bayes Features independent given Y Y X₁ X₂ X₃ Xₙ General Bayesian Network Feature dependencies allowed Y X₁ X₂ X₃ Xₙ

Another Practical Problem: The Zero-Probability Issue

Consider a text classification task (e.g., spam detection), where the features are discrete words.

We use MLE to estimate the class-conditional probability p(word="offer" | class="spam") by calculating the frequency of “offer” in spam emails from the training set.

Problem: What if the word “stock” never appeared in any spam emails in our training data? Then:

\[ \large{p(\text{word}="\text{stock}" \mid y=\text{spam}) = 0} \]

The Catastrophic Consequence of Zero Probability

If p("stock" | spam) = 0, then for any new email containing the word “stock”, the posterior probability of it being spam will be zero!

\[ \large{P(\text{spam} \mid \text{email}) \propto \ldots \times \overbrace{p(\text{"stock"} \mid \text{spam})}^{=0} \times \ldots = 0} \]

A single word unseen in the training set completely rules out a class. This makes the model fragile and unreasonable. It has “seen” too little and is too certain.

The Solution: Laplace Smoothing

Laplace Smoothing, also known as Additive Smoothing, is a simple and effective method for handling the zero-probability problem.

The core idea is: When calculating probabilities, artificially add a small constant λ (usually 1) to the count of every possible event.

This is like giving every possible outcome a “head start,” ensuring that even if an event was never seen in the sample, its estimated probability will not be zero.

The Formula for Laplace Smoothing

For a discrete feature, the unsmoothed MLE estimate is:

\[ \large{P(x_i = v \mid y=c) = \frac{N_{cv}}{N_c}} \]

  • \(N_{cv}\): Number of samples in class c where feature has value v
  • \(N_c\): Total number of samples in class c

With Laplace smoothing (λ > 0):

\[ \large{P_{\lambda}(x_i = v \mid y=c) = \frac{N_{cv} + \lambda}{N_c + \lambda S_i}} \]

  • \(S_i\): Total number of possible values for feature \(i\) (e.g., vocabulary size)
  • \(λ\): The smoothing parameter (when \(λ=1\), it’s called “add-one smoothing”)

The Effect of Smoothing: An Example

Assume a feature has two values {Yes, No}, and we have 10 samples in class c.

  • Observations: 10 ‘Yes’, 0 ‘No’.
  • \(S_i = 2\) (two possible values)

MLE Estimate:

  • P('Yes'|c) = 10/10 = 1
  • P('No'|c) = 0/10 = 0 (Dangerous!)

Laplace Smoothing (λ=1):

  • P('Yes'|c) = (10+1)/(10+1*2) = 11/12 ≈ 0.917
  • P('No'|c) = (0+1)/(10+1*2) = 1/12 ≈ 0.083 (Problem solved!)

Objective Retrieval Before the Main Case

Retrieve the opening objectives: compute a posterior from prior and likelihood, decide with a loss matrix, distinguish MLE from MAP, and assess Naive Bayes assumptions and probability quality.

  • Retrieval prompt: Given \(P(D)=0.1\), \(P(+|D)=0.8\), and \(P(+|\neg D)=0.2\), first calculate \(P(+)\).
  • Answer: \(P(+)=0.8\times0.1+0.2\times0.9=0.26\), so \(P(D|+)=0.08/0.26\approx0.308\), not 0.8.

Formative Check 1: Probability or Decision?

A customer’s default posterior is 0.30. Approve-and-default costs 10; reject-and-no-default costs 1. Approve or reject?

Answer

Approval risk is \(0.30\times10=3\); rejection risk is \(0.70\times1=0.7\), so reject. Maximum posterior and minimum expected loss need not choose the same action.

Main Case: Fuyao Glass Gaussian Naive Bayes

  • Data used in this example:
    • Source: data/stock/stock_price_pre_adjusted.h5, key=data, Fuyao Glass 600660.XSHG.

    • Features: 2018–2024 close and volume; use day-\(t\) return, absolute return, and volume growth.

    • Target and split: next-day decline under a chronological 80/20 split.

  • Nearby method source: scikit-learn GaussianNB documentation; the example reports both threshold decisions and probability-ranking evidence.
Code
from pathlib import Path  # Locate the downloaded data file

import pandas as pd  # Read local quotes into a table
from sklearn.naive_bayes import GaussianNB  # Use Gaussian Naive Bayes to estimate class conditional density
from sklearn.metrics import balanced_accuracy_score, roc_auc_score  # Evaluate classification and probability ranking together
# Public download: https://assets.qiufei.site/data/stock/stock_price_pre_adjusted.h5
# After downloading, change the next line to the file's actual location on your device.
# Course-relative option: Path("data/stock/stock_price_pre_adjusted.h5")
# Windows: Path(r"C:\qiufei\data\stock\stock_price_pre_adjusted.h5")
# macOS: Path("/Users/your_name/data/stock/stock_price_pre_adjusted.h5")
# Linux: Path("/home/your_name/data/stock/stock_price_pre_adjusted.h5")
price_path = Path("/home/ubuntu/r2_data_mount/data/stock/stock_price_pre_adjusted.h5")
price_rows = pd.read_hdf(price_path, key='data', where=['order_book_id=="600660.XSHG"', 'date>=Timestamp("2018-01-01")', 'date<=Timestamp("2024-12-31")'], columns=['close', 'volume'])  # Only Load Target Companies, Periods, and Fields
bayes_frame = price_rows.reset_index().sort_values('date')  # Sort by predicted available time
bayes_frame['return_t'] = bayes_frame['close'].pct_change()  # Construct daily return features
bayes_frame['abs_return_t'] = bayes_frame['return_t'].abs()  # Proxy a fluctuation shock of the day with an absolute return
bayes_frame['volume_growth_t'] = bayes_frame['volume'].pct_change()  # Construct Volume Growth Characteristics
bayes_frame['future_return_t1'] = bayes_frame['return_t'].shift(-1)  # Retain continuous future returns before label construction, Avoid coding unknown end-of-day silences as zero
bayes_frame['target_date_t1'] = bayes_frame['date'].shift(-1)  # Preserve the label-realization date for boundary purging
bayes_frame = bayes_frame.replace([float('inf'), float('-inf')], pd.NA).dropna()  # Delete all unobservable or non-finite records before binary-label construction
Code
bayes_frame['down_t1'] = (bayes_frame['future_return_t1'] < 0).astype(int)  # Create binary labels only for observed future returns
assert bayes_frame['future_return_t1'].notna().all() and bayes_frame['date'].max() < price_rows.reset_index()['date'].max()  # Verify that each feature date corresponds to a later real label realization date
split_row = int(len(bayes_frame) * 0.8)  # Pre-fixed time-split position
test_start_date = bayes_frame.iloc[split_row]['date']
train_rows = bayes_frame[(bayes_frame['date'] < test_start_date) & (bayes_frame['target_date_t1'] < test_start_date)]  # Purge training labels realized in test
test_rows = bayes_frame[bayes_frame['date'] >= test_start_date]
assert train_rows['target_date_t1'].max() < test_rows['date'].min()  # Verify the label-realization boundary
feature_names = ['return_t', 'abs_return_t', 'volume_growth_t']  # Define the semantic field actually used by the model
bayes_model = GaussianNB().fit(train_rows[feature_names], train_rows['down_t1'])  # Estimate prior and class condition distributions during the training period
down_probability = bayes_model.predict_proba(test_rows[feature_names])[:, 1]  # Output fall posterior probabilities for test periods
pd.Series({'balanced_accuracy': balanced_accuracy_score(test_rows['down_t1'], down_probability >= 0.5), 'roc_auc': roc_auc_score(test_rows['down_t1'], down_probability), 'test_rows': len(test_rows)})  # Report Outside Sample Metrics and Sample Size
balanced_accuracy      0.486806
roc_auc                0.448681
test_rows            340.000000
dtype: float64

Formative Check 2: The Naive Assumption

return_t and abs_return_t are related. Can Naive Bayes still run, and is its output a causal effect?

Answer

It runs, but violated conditional independence can degrade calibration; inspect calibration and compare a baseline. The posterior is observational prediction, not an intervention effect.

Step-by-Step Exercise: A Loss-Sensitive Threshold

  • Task: If missing a decline costs four times a false alarm, derive the probability threshold and report a new confusion matrix.
  • Complete solution:
    • Predicting decline has risk \((1-p)\times1\); predicting no decline has risk \(p\times4\).

    • Choose decline when \((1-p)<4p\), or \(p>0.2\).

    • Replace down_probability >= 0.5 by >= 0.2 and explain higher recall versus lower precision.

Code
from sklearn.metrics import confusion_matrix, precision_score, recall_score  # Calculate Reconcilable Classification Results under Cost Threshold
threshold_rows = []  # Collect Complete Comparison of Two Thresholds
for probability_threshold in [0.5, 0.2]:  # Compare Default Threshold to Four-to-One Cost Threshold
    threshold_prediction = down_probability >= probability_threshold  # Convert Same Test Probability to Category Decision Making
    threshold_matrix = confusion_matrix(test_rows['down_t1'], threshold_prediction)  # Fixed Label Order Gets TN, FP, FN, TP
    threshold_rows.append({'threshold': probability_threshold, 'precision': precision_score(test_rows['down_t1'], threshold_prediction), 'recall': recall_score(test_rows['down_t1'], threshold_prediction), 'tn': threshold_matrix[0, 0], 'fp': threshold_matrix[0, 1], 'fn': threshold_matrix[1, 0], 'tp': threshold_matrix[1, 1]})  # Save Metrics and Four Frame Counts
pd.DataFrame(threshold_rows)  # Demonstrate recall with reduced thresholds — Accuracy trade-offs
Table 1
threshold precision recall tn fp fn tp
0 0.5 0.463087 0.86250 20 160 22 138
1 0.2 0.471810 0.99375 2 178 1 159

Apply It to a New Case

Switch to Hengrui Pharmaceuticals 600276.XSHG, hold out 2023–2024, compare GaussianNB with a class-prior-only baseline, and create a five-bin calibration table.

Complete-answer reminder

  • show the time split, fields and units, compare with a baseline, report AUC, balanced accuracy and calibration, and explain that association is not causation.

  • Do not claim a meaningful advantage without evidence from repeated time splits.

Complete Solution for the New Case: Hengrui Data Analysis

Table 2
Code
from pathlib import Path  # Locate the downloaded data file

import pandas as pd  # Read and Organize Local Real A-Shares Quotes
from sklearn.naive_bayes import GaussianNB  # Estimating Gaussian Naive Bayes probabilities
from sklearn.metrics import balanced_accuracy_score, roc_auc_score  # Evaluate classification and probability ranking
# Public download: https://assets.qiufei.site/data/stock/stock_price_pre_adjusted.h5
# After downloading, change the next line to the file's actual location on your device.
# Course-relative option: Path("data/stock/stock_price_pre_adjusted.h5")
# Windows: Path(r"C:\qiufei\data\stock\stock_price_pre_adjusted.h5")
# macOS: Path("/Users/your_name/data/stock/stock_price_pre_adjusted.h5")
# Linux: Path("/home/your_name/data/stock/stock_price_pre_adjusted.h5")
transfer_path = Path("/home/ubuntu/r2_data_mount/data/stock/stock_price_pre_adjusted.h5")
transfer_rows = pd.read_hdf(transfer_path, key='data', where=['order_book_id=="600276.XSHG"', 'date>=Timestamp("2018-01-01")', 'date<=Timestamp("2024-12-31")'], columns=['close', 'volume'])  # Select Hengrui Medicine, Period and Field
transfer_frame = transfer_rows.reset_index().sort_values('date')  # Sort by trading days in order of forecast occurrence
transfer_frame['return_t'] = transfer_frame['close'].pct_change()  # Compute one-day returns
transfer_frame['return_5d_t'] = transfer_frame['close'].pct_change(5)  # Compute five-day returns
transfer_frame['volatility_5d_t'] = transfer_frame['return_t'].rolling(5).std()  # Compute rolling five-day volatility
transfer_frame['volume_growth_t'] = transfer_frame['volume'].pct_change()  # Construct Volume Growth
transfer_frame['future_return_t1'] = transfer_frame['return_t'].shift(-1)  # Retain continuous future returns before label construction
transfer_frame['target_date_t1'] = transfer_frame['date'].shift(-1)  # Preserve the label-realization date
transfer_frame = transfer_frame.replace([float('inf'), float('-inf')], pd.NA).dropna()  # Remove rows with unknown future outcomes or non-finite fields
transfer_frame['down_t1'] = (transfer_frame['future_return_t1'] < 0).astype(int)  # Create a binary label only for observed future returns
transfer_train = transfer_frame[(transfer_frame['date'] <= '2022-12-31') & (transfer_frame['target_date_t1'] < '2023-01-01')]  # Purge training labels realized in test
transfer_test = transfer_frame[transfer_frame['date'] >= '2023-01-01']
assert transfer_train['target_date_t1'].max() < transfer_test['date'].min()  # Verify the label-realization boundary

Complete Solution for the New Case: Baseline Metrics

Code
transfer_features = ['return_t', 'return_5d_t', 'volatility_5d_t', 'volume_growth_t']  # Fixed Four T-Points as Available Feature
transfer_bayes = GaussianNB().fit(transfer_train[transfer_features], transfer_train['down_t1'])  # Fitting the model only during the training period
transfer_probability = transfer_bayes.predict_proba(transfer_test[transfer_features])[:, 1]  # Generate Drop Probability for fixed Test Period
prior_probability = pd.Series(transfer_train['down_t1'].mean(), index=transfer_test.index)  # Constructing a Benchmark with Only a Training Period Category Prior
transfer_metrics = pd.DataFrame({'model': ['GaussianNB', 'class-prior baseline'], 'roc_auc': [roc_auc_score(transfer_test['down_t1'], transfer_probability), roc_auc_score(transfer_test['down_t1'], prior_probability)], 'balanced_accuracy': [balanced_accuracy_score(transfer_test['down_t1'], transfer_probability >= 0.5), balanced_accuracy_score(transfer_test['down_t1'], prior_probability >= 0.5)]})  # Summarize same test period metrics
calibration_frame = pd.DataFrame({'observed': transfer_test['down_t1'].to_numpy(), 'probability': transfer_probability})  # Aligning Probability and Real Results
calibration_frame['probability_bin'] = pd.cut(calibration_frame['probability'], bins=[0, .2, .4, .6, .8, 1], include_lowest=True)  # Divide by pre-declared boundaries into five groups
calibration_table = calibration_frame.groupby('probability_bin', observed=False).agg(n=('observed', 'size'), mean_probability=('probability', 'mean'), observed_rate=('observed', 'mean')).reset_index()  # Calculate mean predicted probability and observed frequency for Each Group
display(transfer_metrics)  # Output key indicators for model and a priori benchmarks
Table 3
model roc_auc balanced_accuracy
0 GaussianNB 0.522642 0.52633
1 class-prior baseline 0.500000 0.50000

Executed test results are GaussianNB AUC 0.522642 and balanced accuracy 0.526330; the prior baseline gives 0.500000 for both.

Complete Solution for the New Case: Five-Bin Calibration

Code
calibration_table  # Output a complete five sets of calibration tables
Table 4
probability_bin n mean_probability observed_rate
0 (-0.001, 0.2] 0 NaN NaN
1 (0.2, 0.4] 20 0.333113 0.650000
2 (0.4, 0.6] 431 0.487905 0.522042
3 (0.6, 0.8] 23 0.657749 0.521739
4 (0.8, 1.0] 9 0.951448 0.444444
  • The five bins contain 0, 20, 431, 23, and 9 observations; the 0.4–0.6 bin has mean prediction 0.487905 versus observed decline rate 0.522042.

  • The last feature date is 2024-12-30, and unknown future labels are removed before integer conversion.

  • Empty and small tail bins support neither stable calibration nor causal claims.

Formative Check 3: MLE versus MAP

With little data and a concentrated prior, which estimate is more strongly shrunk? What happens as sample size grows?

Answer

MAP includes the prior and is more strongly shrunk in small samples. Under regular conditions, likelihood dominates with more data and MLE/MAP usually converge.

Sources and Further Reading

  • Berger, Statistical Decision Theory and Bayesian Analysis.
  • Murphy, Probabilistic Machine Learning: An Introduction, classification chapters.
  • McCallum & Nigam (1998), naive Bayes event models.
  • Data: local pre-adjusted A-share data, with fields and filters stated above.

Chapter Summary: The Core Ideas of Bayesian Classifiers

Optional topic: after Core, optionally enter GMM/EM, then continue to the final summary without replaying zero probability, smoothing, or the main case.

Summary of Core Ideas in Bayesian Classifiers A summary of five key concepts: Decision Framework, Optimal Decision, Model Learning, Practicality, and Robustness, each with an icon and a brief description. P(y|x) Decision Combine prior,likelihood, andevidence. Loss Rule Choose actionsby minimumexpected loss. MLE / MAP Fit parameterswith MLEor MAP. Naive Bayes Factor byconditionalindependence. Smoothing Avoid zeroprobabilitiesin sparse data.

Preview of Next Lecture

Today, we explored a classic Generative Model—the Bayesian classifier.

We learned how to model the class-conditional density p(x|y) and the prior P(y).

Next, we will study another major class of models: Discriminative Models, such as Logistic Regression. These models bypass modeling p(x|y) and model the posterior probability P(y|x) directly.

Thank You!

Q & A