Module contents
Lesson 11 of 24Core 90 min

Generative classifiers: Naive Bayes and discriminant analysis

Changes perspective from modeling P(y | x) to modeling P(x | y) and P(y), then applying Bayes. Develops Gaussian, multinomial and Bernoulli Naive Bayes with Laplace smoothing and log-space implementation, and linear and quadratic discriminant analysis. Compares generative and discriminative models using Ng and Jordan’s result and explains why Naive Bayes can classify well despite poorly calibrated probabilities.

After this lesson you can

  • Derive Naive Bayes and the maximum-likelihood estimators for its Gaussian, multinomial and Bernoulli variants.
  • Apply Laplace smoothing and justify it as Bayesian estimation with a Dirichlet prior.
  • Prove that LDA with shared covariance produces linear boundaries and relate it to logistic regression.
  • Compare generative and discriminative models in sample efficiency and asymptotic error (Ng and Jordan, 2002).
  • Implement a numerically stable Naive Bayes text classifier using log-sum-exp.

Before you start

Motivation: classification by counting

In the late 1990s, spam became the first major text-classification problem at scale. The filters that worked were not the most sophisticated: they counted words. Sahami, Dumais, Heckerman and Horvitz presented a Bayesian spam filter in 1998, and in 2002 Paul Graham’s essay “A Plan for Spam” popularized the idea among programmers. The method behind both is what you will build in this lesson: Naive Bayes.

Its appeal is threefold. It trains in one pass: estimating the model means counting how often each word appears in each class, costing O(nuˊmero de tokens)\bigO(\text{número de tokens}) and allowing updates message by message. It works with little data and in high dimensions: with a vocabulary of tens of thousands of words and a few hundred examples, unregularized logistic regression overfits, while Naive Bayes does not. And it is transparent: the decision is a sum of word contributions you can read one by one.

Behind it is a change of perspective from logistic regression. Logistic regression models what you need for a decision directly, P(Y∣x)\Pr(Y \given \vb{x}). Naive Bayes and discriminant analysis do something else: they model how each class generates data, p(x∣y)p(\vb{x} \given y), and each class’s frequency, P(Y=y)\Pr(Y = y), then obtain the posterior using Bayes’ theorem. That choice has measurable consequences: the generative model learns sooner but settles at worse error if its assumptions are false. The result of Ng and Jordan (2002) at the end quantifies this, and you will reproduce it yourself.

Generative versus discriminative

With KK classes and priors πk=P(Y=k)\pi_k = \Pr(Y = k), conditional probability and Bayes’ theorem give

P(Y=k∣x)=πk p(x∣k)∑j=1Kπj p(x∣j),y^(x)=arg max⁡k[log⁡πk+log⁡p(x∣k)].\Pr(Y = k \given \vb{x}) = \frac{\pi_k\, p(\vb{x} \given k)}{\sum_{j=1}^K \pi_j\, p(\vb{x} \given j)}, \qquad \hat y(\vb{x}) = \argmax_k \big[\log \pi_k + \log p(\vb{x} \given k)\big].

The rule on the right is the Bayes rule for 0–1 loss when πk\pi_k and p(x∣k)p(\vb{x} \given k) are the true values: the posterior mode, the functional elicited by that loss (as seen in what each loss estimates). The denominator does not depend on kk, so decisions need only compare numerators; probabilities require normalization.

The two pairs in this lesson are Naive Bayes and logistic regression (with discrete inputs), and linear discriminant analysis and logistic regression (with Gaussian inputs): in both the posterior has exactly the logistic form σ(w⊤x+b)\sigmoid(\vb{w}\T\vb{x} + b), but the generative model obtains w\vb{w} from means, variances or frequencies, while logistic regression optimizes it.

Modeling p(x∣y)p(\vb{x} \given y) is more work than modeling the boundary, but in return gives things a discriminative model does not have:

  • Sampling. With p(x∣y)p(\vb{x} \given y) you can generate synthetic examples from each class. With P(Y∣x)\Pr(Y \given \vb{x}) you cannot.
  • Missing data. If xjx_j is missing at prediction time, the generative model can marginalize: p(xobs∣y)=∫p(x∣y) ⁣dxjp(\vb{x}_{\text{obs}} \given y) = \int p(\vb{x} \given y)\dd x_j. Logistic regression needs the dd values and forces you to impute. You will measure this in the lab.
  • Detecting unusual examples. p(x)=∑kπkp(x∣k)p(\vb{x}) = \sum_k \pi_k p(\vb{x} \given k) says whether an example resembles anything seen; a posterior of 0.990.99 cannot distinguish “clearly class 1” from “nothing like the training data.”
  • Unlabeled data and prior shifts. The same model without labels is a Gaussian mixture fitted with EM; and if class frequencies change in production, just change πk\pi_k without retraining.

The cost is twofold. Statistical: if p(x∣y)p(\vb{x} \given y) is misspecified, the generative model converges to the best rule within its model, which may be far from the best possible rule; the discriminative model bets only on the shape of the boundary. And modeling: a density in Rd\R^d with large dd is much harder to estimate than a boundary. With dd binary variables, each class’s joint distribution has 2d−12^d - 1 free parameters: with d=30d = 30 there are more than 10910^9. An assumption is needed to make it manageable, and there are two broad families. One assumes independence: the most extreme is Naive Bayes, generalized by Bayesian networks with a graph describing variable dependencies. The other assumes nothing and factors exactly via the chain rule, p(x∣y)=∏jp(xj∣x1:j−1,y)p(\vb{x} \given y) = \prod_j p(x_j \given x_{1:j-1}, y), modeling each factor with a neural network: this is the autoregressive factorization of deep generative models, which model p(x)p(\vb{x}) in millions of dimensions.

Naive Bayes

The conditional independence assumption

With binary features, the number of parameters per class goes from 2d−12^d - 1 to dd: exponential to linear. The assumption is almost always false (in an email, “click” and “here” do not appear independently even knowing it is spam), yet the classifier works. Understanding why occupies the section after implementation. First, which univariate model to put in each pjp_j.

Three models for each feature

  • Gaussian, for continuous features: pj(xj∣k)=N(xj;μkj,σkj2)p_j(x_j \given k) = \Normal(x_j; \mu_{kj}, \sigma^2_{kj}). This is Gaussian discriminant analysis with diagonal covariance matrices, one per class.
  • Bernoulli, for binary features (in text, whether word jj appears): pj(xj∣k)=θkjxj(1−θkj)1−xjp_j(x_j \given k) = \theta_{kj}^{x_j}(1 - \theta_{kj})^{1 - x_j}. Each document is described by the VV words in the vocabulary, including absent ones.
  • Multinomial, for counts (in text, how often each word appears): a document of L=∑jxjL = \sum_j x_j tokens is a sequence of LL independent draws from a categorical distribution with parameters θk=(θk1,…,θkV)\vb{\theta}_k = (\theta_{k1}, \dots, \theta_{kV}), with ∑jθkj=1\sum_j \theta_{kj} = 1:
p(x∣k)=L!∏jxj!∏j=1Vθkjxj.p(\vb{x} \given k) = \frac{L!}{\prod_j x_j!} \prod_{j=1}^V \theta_{kj}^{x_j}.

The multinomial coefficient does not depend on class and disappears on comparison. This model is not literally a product of univariate densities (document counts are linked by ∑jxj=L\sum_j x_j = L), but has the same structure: each token is independent of the others given the class. McCallum and Nigam (1998) compared the two text event models on five corpora and found Bernoulli works well with small vocabularies, but multinomial is usually better with large vocabularies, with a mean 27% error reduction relative to Bernoulli.

Let nkn_k be the number of examples in class kk, Nkj=∑i:yi=kxijN_{kj} = \sum_{i : y_i = k} x_{ij} the number of times word jj appears in documents of class kk, Nk=∑jNkjN_k = \sum_j N_{kj} the total tokens in the class, and DkjD_{kj} the number of documents in class kk containing word jj.

Proof

By independence of examples and the Naive Bayes factorization, joint log-likelihood is

ℓ=∑knklog⁡πk+∑k∑j∑i:yi=klog⁡pj(xij∣k),\ell = \sum_{k} n_k \log \pi_k + \sum_{k}\sum_{j} \sum_{i : y_i = k} \log p_j(x_{ij} \given k),

a sum of terms that share no parameters: priors appear only in the first and each pair (k,j)(k, j) only in its own. Maximizing ℓ\ell means maximizing each term separately. The first, under constraint ∑kπk=1\sum_k \pi_k = 1, is that of a categorical distribution, whose maximum is π^k=nk/n\hat\pi_k = n_k/n (the same calculation as the multinomial case below). Each Gaussian term is the log-likelihood of nkn_k observations from a univariate normal, maximized by sample mean and variance with divisor nkn_k. Each Bernoulli term is Dkjlog⁡θ+(nk−Dkj)log⁡(1−θ)D_{kj}\log\theta + (n_k - D_{kj})\log(1 - \theta), whose derivative vanishes at θ=Dkj/nk\theta = D_{kj}/n_k. In the multinomial, a class’s θkj\theta_{kj} are linked by ∑jθkj=1\sum_j \theta_{kj} = 1, so maximize using a Lagrange multiplier:

∎
L=∑jNkjlog⁡θkj−λ(∑jθkj−1)\mathcal{L} = \sum_{j} N_{kj} \log \theta_{kj} - \lambda\big(\textstyle\sum_{j} \theta_{kj} - 1\big)
The class k terms: each token of word j contributes a log θ_kj. The multinomial coefficient does not depend on θ.
1/3

Notice what the theorem says: training is counting. There is no iterative optimization, learning rate, or convergence to monitor, and adding a new example means adding its counts. That is why MultinomialNB has an partial_fit method that processes batches and reaches exactly the same model as fit.

With the multinomial (or Bernoulli) model and two classes, the log odds are

log⁡P(Y=1∣x)P(Y=0∣x)=∑j=1Vxjlog⁡θ1jθ0j+log⁡π1π0,\log\frac{\Pr(Y = 1 \given \vb{x})}{\Pr(Y = 0 \given \vb{x})} = \sum_{j=1}^V x_j \log\frac{\theta_{1j}}{\theta_{0j}} + \log\frac{\pi_1}{\pi_0},

a linear function of counts: multinomial Naive Bayes is a linear classifier with weights wj=log⁡(θ1j/θ0j)w_j = \log(\theta_{1j}/\theta_{0j}), the same form as logistic regression on the same features. Each word contributes its weight as often as it appears, and the interactive below plots those exact terms. Bernoulli log odds are also linear in x∈{0,1}V\vb{x} \in \{0, 1\}^V: ∑j[xjlog⁡θ1jθ0j+(1−xj)log⁡1−θ1j1−θ0j]+log⁡π1π0\sum_j \big[x_j \log\frac{\theta_{1j}}{\theta_{0j}} + (1 - x_j)\log\frac{1 - \theta_{1j}}{1 - \theta_{0j}}\big] + \log\frac{\pi_1}{\pi_0}, with one term for each absent word.

Smoothing: the zero problem

The maximum-likelihood estimator has a serious flaw. If the word “tomorrow” never occurs in training spam, θ^spam,man˜ana=0\hat\theta_{\text{spam}, \text{mañana}} = 0, and any message containing it will have p(x∣spam)=0p(\vb{x} \given \text{spam}) = 0 whatever the rest of the message says. One word vetoes all the evidence. With thousands of vocabulary words and a few hundred documents, most counts NkjN_{kj} are zero, so this happens on almost every prediction. And if a message has both a word never seen in spam and one never seen in normal messages, log odds are ∞−∞\infty - \infty: the classifier cannot decide.

Adding one “to avoid zero” looks like a patch, but it is exact Bayesian inference. The tool is the categorical distribution’s conjugate prior, the Dirichlet distribution: θ∼Dir(β1,…,βV)\vb{\theta} \sim \mathrm{Dir}(\beta_1, \dots, \beta_V) has density proportional to ∏jθjβj−1\prod_j \theta_j^{\beta_j - 1} on the simplex, mean βj/∑lβl\beta_j/\sum_l \beta_l and, if all βj>1\beta_j > 1, mode (βj−1)/(∑lβl−V)(\beta_j - 1)/(\sum_l \beta_l - V).

The posterior comes from multiplying likelihood ∏jθkjNkj\prod_j \theta_{kj}^{N_{kj}} by prior ∏jθkjβ−1\prod_j \theta_{kj}^{\beta - 1}: product ∏jθkjNkj+β−1\prod_j \theta_{kj}^{N_{kj} + \beta - 1} is the kernel of the Dirichlet with parameters Nkj+βN_{kj} + \beta. The exercise “Smoothing as Bayesian inference” asks you to prove the two interpretations of the estimator. The practical consequence is an interpretation of α\alpha: it is the number of fictitious observations per word before seeing the data, and αV\alpha V is the total. With a large vocabulary, αV\alpha V can be comparable to the number of real class tokens, and then α\alpha is no longer a detail: it is a regularizer pulling all θ^kj\hat\theta_{kj} toward the uniform 1/V1/V, chosen by cross-validation like any other. N-gram language models have the same zero problem, magnified: additive smoothing is insufficient there and techniques such as Kneser–Ney smoothing are used.

Computing in log space

A message of LL tokens with per-token probabilities of order 10−310^{-3} has likelihood of order 10−3L10^{-3L}. The smallest normal float64 is 2.2⋅10−3082.2 \cdot 10^{-308} and the smallest subnormal is 4.9⋅10−3244.9 \cdot 10^{-324}, so with around a hundred tokens (sooner if words are rare) the product enters subnormal territory, losing significant digits, and soon afterward rounds to 0 in both classes: 0/00/0 and no decision. The usual solution is to work with sk(x)=log⁡πk+∑jxjlog⁡θkjs_k(\vb{x}) = \log\pi_k + \sum_j x_j\log\theta_{kj}, a sum of moderate numbers, and normalize with the log-sum-exp trick,

log⁡P(Y=k∣x)=sk−(m+log⁡∑jesj−m),m=max⁡jsj,\log\Pr(Y = k \given \vb{x}) = s_k - \Big(m + \log\sum_{j} e^{s_j - m}\Big), \qquad m = \max_j s_j,

which does not overflow because the largest exponent is e0=1e^0 = 1. With log-likelihoods, the entire batch calculation is also a matrix product: S=X log⁡Θ^⊤+1nlog⁡π^⊤∈Rn×K\mat{S} = \mat{X}\,\log\hat{\mat{\Theta}}\T + \vb{1}_n\log\hat{\vb{\pi}}\T \in \R^{n \times K}, with X∈Rn×V\mat{X} \in \R^{n \times V} the counts and log⁡Θ^∈RK×V\log\hat{\mat{\Theta}} \in \R^{K \times V}.

The laboratory: Naive Bayes from scratch

The cell implements both variants with the scikit-learn interface, tests them on a corpus of 60 short messages embedded in the lesson (30 spam and 30 normal, written for this lab) and the digits dataset (1797 8×88 \times 8 images with intensities from 0 to 16), and compares them with MultinomialNB and GaussianNB.

[ ]Multinomial and Gaussian Naive Bayes from scratchBrowser
import re
import numpy as np
from scipy.special import logsumexp
from sklearn.naive_bayes import MultinomialNB, GaussianNB
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split

SPAM = [
    "Gana un premio de mil euros ahora, responde GRATIS a este mensaje",
    "Oferta exclusiva: descuento del cincuenta por ciento solo hoy, haz clic aquí",
    "Has sido seleccionado para recibir un móvil gratis, llama ya",
    "Últimas horas de la oferta, compra ahora y ahorra dinero",
    "Tu cuenta tiene un premio pendiente, verifica tus datos en el enlace",
    "Préstamo rápido sin papeles, dinero en tu cuenta en una hora",
    "Felicidades, eres el ganador del sorteo de un viaje gratis",
    "Consigue créditos gratis para tu juego favorito, haz clic ya",
    "Gana dinero desde casa sin experiencia, plazas limitadas",
    "Oferta: dos por uno en todos los productos, solo este fin de semana",
    "Reclama tu regalo gratis antes de medianoche en nuestra web",
    "Promoción especial para ti: tarifa ilimitada a mitad de precio",
    "Tu paquete está retenido, paga la tasa en el enlace para recibirlo",
    "Invierte hoy y duplica tu dinero en una semana, garantizado",
    "Has ganado un cupón de cien euros, canjéalo ahora",
    "Descuento exclusivo para clientes: compra ya y recibe un regalo",
    "Llama ahora y participa en el sorteo de un coche nuevo",
    "Pierde diez kilos en un mes con nuestro producto milagroso",
    "Oferta limitada: suscríbete gratis y gana puntos dobles",
    "Último aviso: tu premio caduca hoy, responde SÍ para reclamarlo",
    "Dinero rápido: aprueba tu préstamo en minutos con un clic",
    "Envía PREMIO al número corto y gana una tableta",
    "Rebajas increíbles en electrónica, precios mínimos solo hoy",
    "Tu tarjeta ha sido bloqueada, verifica tus datos en el enlace",
    "Gana un viaje para dos personas, participa gratis ahora",
    "Compra un seguro barato hoy y llévate un regalo",
    "Ingresos extra garantizados trabajando dos horas al día",
    "Felicidades, tu número ha ganado el premio de la semana",
    "Accede gratis a la promoción y consigue saldo ilimitado",
    "Haz clic aquí para cobrar tu reembolso pendiente",
]
HAM = [
    "¿Quedamos mañana para comer en el sitio de siempre?",
    "Llegaré tarde a la reunión, empezad sin mí",
    "Te mando las fotos del viaje cuando llegue a casa",
    "¿Puedes comprar pan y leche al volver del trabajo?",
    "La reunión de mañana se pasa a las diez",
    "Gracias por la cena de ayer, lo pasamos genial",
    "¿Has visto el partido? Vaya final más increíble",
    "Mi madre pregunta si venís el domingo a comer",
    "Te paso el informe revisado antes de las cinco",
    "¿A qué hora sale tu tren mañana?",
    "He dejado las llaves en la mesa de la entrada",
    "Recuerda que el lunes hay examen de matemáticas",
    "¿Te viene bien que hablemos por la tarde?",
    "Ya estoy en casa, avísame cuando salgas",
    "El médico me ha dado cita para el jueves",
    "¿Me pasas los apuntes de la clase de hoy?",
    "Feliz cumpleaños, que pases un día genial",
    "Vamos al cine el sábado, ¿te apuntas?",
    "He llegado bien, mañana te llamo",
    "El proyecto va bien, mañana enseñamos la demo al equipo",
    "¿Puedes revisar mi código antes de la reunión?",
    "Esta noche cenamos en casa de mis padres",
    "Se me ha olvidado el cargador, ¿me lo traes?",
    "Mañana no hay clase, el profesor está enfermo",
    "Te llamo luego, ahora estoy en el trabajo",
    "¿Quieres que pase a recogerte a las ocho?",
    "Gracias por ayudarme con la mudanza el sábado",
    "Compra entradas para el concierto si quedan",
    "Hoy salgo antes del trabajo, ¿tomamos algo?",
    "Ha llegado el paquete que pediste, lo tienes en la entrada",
]

tokens = lambda s: re.findall(r"[a-záéíóúüñ]+", s.lower())
vocab = sorted({w for d in SPAM + HAM for w in tokens(d)})
columna = {w: j for j, w in enumerate(vocab)}

def bolsa(docs):
    """Matriz de recuentos (documentos × vocabulario); las palabras desconocidas se ignoran."""
    X = np.zeros((len(docs), len(vocab)))
    for i, d in enumerate(docs):
        for w in tokens(d):
            if w in columna:
                X[i, columna[w]] += 1
    return X

X_txt, y_txt = bolsa(SPAM + HAM), np.array([1] * len(SPAM) + [0] * len(HAM))   # 1 = spam

class NBMultinomial:
    def __init__(self, alpha=1.0):
        self.alpha = alpha
    def fit(self, X, y):
        self.classes_ = np.unique(y)
        N = np.stack([X[y == c].sum(0) for c in self.classes_])                    # K × V recuentos N_kj
        self.class_log_prior_ = np.log([np.mean(y == c) for c in self.classes_])
        self.feature_log_prob_ = np.log(N + self.alpha) - np.log(N.sum(1, keepdims=True) + self.alpha * X.shape[1])
        return self
    def joint_log_likelihood(self, X):                                              # s_k(x), sin el coeficiente multinomial
        return X @ self.feature_log_prob_.T + self.class_log_prior_
    def predict_log_proba(self, X):
        J = self.joint_log_likelihood(X)
        return J - logsumexp(J, axis=1, keepdims=True)
    def predict_proba(self, X):
        return np.exp(self.predict_log_proba(X))
    def predict(self, X):
        return self.classes_[self.joint_log_likelihood(X).argmax(1)]

class NBGaussiano(NBMultinomial):
    def __init__(self, var_smoothing=1e-9):
        self.var_smoothing = var_smoothing
    def fit(self, X, y):
        self.classes_ = np.unique(y)
        self.theta_ = np.stack([X[y == c].mean(0) for c in self.classes_])
        eps = self.var_smoothing * X.var(0).max()                                   # como GaussianNB
        self.var_ = np.stack([X[y == c].var(0) for c in self.classes_]) + eps
        self.class_log_prior_ = np.log([np.mean(y == c) for c in self.classes_])
        return self
    def joint_log_likelihood(self, X):
        cuad = ((X[:, None, :] - self.theta_[None]) ** 2 / self.var_[None]).sum(-1)
        return self.class_log_prior_ - 0.5 * np.log(2 * np.pi * self.var_).sum(1) - 0.5 * cuad

mio = NBMultinomial(1.0).fit(X_txt, y_txt)
ref = MultinomialNB(alpha=1.0).fit(X_txt, y_txt)
print(f"corpus: V = {len(vocab)} palabras; {X_txt[y_txt == 1].sum():.0f} tokens de spam y {X_txt[y_txt == 0].sum():.0f} de no spam")
print(f"diferencia máxima con MultinomialNB en log P(y | x): {np.abs(mio.predict_log_proba(X_txt) - ref.predict_log_proba(X_txt)).max():.1e}")
aciertos = sum(NBMultinomial(1.0).fit(np.delete(X_txt, i, 0), np.delete(y_txt, i)).predict(X_txt[i:i + 1])[0] == y_txt[i]
               for i in range(len(y_txt)))
print(f"exactitud dejando uno fuera: {aciertos}/{len(y_txt)}")
nuevos = ["Gana un viaje gratis, llama mañana", "¿Comemos mañana en casa?", "Oferta: compra hoy tu entrada para el concierto"]
for s, p in zip(nuevos, mio.predict_proba(bolsa(nuevos))[:, 1]):
    print(f"  P(spam | «{s}») = {p:.3f}")

Xd, yd = load_digits(return_X_y=True)
Xtr, Xte, ytr, yte = train_test_split(Xd, yd, test_size=0.3, random_state=0, stratify=yd)
g_mio, g_ref = NBGaussiano().fit(Xtr, ytr), GaussianNB().fit(Xtr, ytr)
L_mio = g_mio.predict_log_proba(Xte)
print(f"\ndigits, gaussiano: diferencia máxima con GaussianNB {np.abs(L_mio - g_ref.predict_log_proba(Xte)).max():.1e} "
      f"(con log-probabilidades de hasta {L_mio.min():.1e}), exactitud {np.mean(g_mio.predict(Xte) == yte):.3f}")
print(f"digits, multinomial sobre las intensidades: exactitud {np.mean(NBMultinomial(1.0).fit(Xtr, ytr).predict(Xte) == yte):.3f}")

largo = bolsa([" ".join(HAM * 10)])                                                  # 2500 tokens
directo = np.prod(np.exp(mio.feature_log_prob_) ** largo[0], axis=1) * np.exp(mio.class_log_prior_)
print(f"\nmensaje de {largo.sum():.0f} tokens: p(x, y) por producto directo = {directo}")
print(f"en logaritmos: s_k(x) = {np.round(mio.joint_log_likelihood(largo)[0], 1)}, "
      f"log P(spam | x) = {mio.predict_log_proba(largo)[0, 1]:.1f}")

The implementation agrees exactly with MultinomialNB and with GaussianNB up to a difference of order 10−610^{-6}, which looks large until you consider the scale: some log-probabilities are of order −7⋅109-7 \cdot 10^9, and at that scale 10−610^{-6} is the last bit of a float64. Those huge values are discarded classes for images with pixels constant in another class: their estimated variance is nearly 0, and any deviation costs billions of nats. You will return to them in the scikit-learn section. The corpus has V=270V = 270 distinct words, 299 spam tokens and 250 normal ones; under leave-one-out, the classifier gets 54 of the 60 messages right, not bad for 60 examples and 270 features. The three new messages show the mechanics: “Gana un viaje gratis, llama mañana” (Win a free trip, call tomorrow) is classified as spam with 0.9920.992 even though “mañana” appears only in normal messages; “¿Comemos mañana en casa?” (Shall we eat at home tomorrow?) is normal (0.0920.092); and “Oferta: compra hoy tu entrada para el concierto” (Offer: buy your concert ticket today) is spam (0.9050.905) because “oferta”, “compra” and “hoy” outweigh “concierto” and “entrada”. On digits, Gaussian achieves 84.8% accuracy and multinomial, which treats intensities as counts, 89.6%: neither model is “true” for pixels, and choosing between them is empirical.

The long message is the numerical warning: its 2500 tokens yield a joint likelihood that direct multiplication rounds to exactly 0 in both classes, while log scores are finite numbers of order −1.2⋅104-1.2 \cdot 10^4 and the posterior is computed without trouble.

Naive Bayes on text, word by word

InteractiveNaive Bayes on text
Contribution of each word, mwlog⁡(θ^spam,w/θ^no,w)m_w \log(\hat\theta_{\text{spam},w}/\hat\theta_{\text{no},w}), with θ^c,w=(Nc,w+α)/(Nc+αV)\hat\theta_{c,w} = (N_{c,w} + \alpha)/(N_c + \alpha V)
← no spamspam →gana: counts spam 5, no spam 0; θ̂ spam 1.05e-2, θ̂ no spam 1.92e-3gana5 · 01.70un: counts spam 12, no spam 1; θ̂ spam 2.28e-2, θ̂ no spam 3.85e-3un12 · 11.78viaje: counts spam 2, no spam 1; θ̂ spam 5.27e-3, θ̂ no spam 3.85e-3viaje2 · 10.32gratis: counts spam 8, no spam 0; θ̂ spam 1.58e-2, θ̂ no spam 1.92e-3gratis8 · 02.11llama: counts spam 2, no spam 0; θ̂ spam 5.27e-3, θ̂ no spam 1.92e-3llama2 · 01.01mañana: counts spam 0, no spam 6; θ̂ spam 1.76e-3, θ̂ no spam 1.35e-2mañana0 · 6−2.04total4.88
  • evidence for spam
  • evidence for non-spam
Below each word: token counts in spam · non-spam (299 and 250 tokens; vocabulary of 270 words).
1.00
Event model
prior log-odds0.00
total log-odds4.88
P(spam | message)99.2 %
Rare words (“llama”) are most sensitive to α\alpha: their bars change greatly, while frequent ones hardly change.
The previous cell's corpus (30 spam and 30 normal messages, V=270V = 270, equal priors) with the same tokenization. Each bar is one word's contribution to spam versus non-spam log odds: in the multinomial model, mwlog⁡(θ^spam,w/θ^no,w)m_w \log(\hat\theta_{\text{spam},w}/\hat\theta_{\text{no},w}), with mwm_w its number of occurrences; in Bernoulli, one bar per present word and another summing the V−kV - k absent words. Below each word are its counts in each class. The posterior is σ\sigmoid of the total.

With α=1\alpha = 1, the first example adds +1.70+1.70 for “gana”, +2.11+2.11 for “gratis”, +1.01+1.01 for “llama” and +1.78+1.78 for “un” (12 times in spam and once in normal messages: a stop word that happens to be informative in this corpus), and subtracts 2.042.04 for “mañana”: total +4.88+4.88 and P(spam)=0.992P(\text{spam}) = 0.992, the cell’s value. Now lower α\alpha. Frequent words barely change, but those with a zero in one class shoot up: with α=0.01\alpha = 0.01, “llama” (2 spam occurrences, 0 normal) rises from +1.01+1.01 to +5.13+5.13, and the total from +4.88+4.88 to +13.9+13.9. With small α\alpha, two occurrences of one word are worth more than twelve of another, because the probability ratio matters and one is near zero. With α=0\alpha = 0 the ratio is infinite: “gana”, “gratis” and “llama” are worth +∞+\infty, “mañana” −∞-\infty, and the sum is ∞−∞\infty - \infty. Now write a message using words from just one class: with α=0\alpha = 0, a word unseen in spam suffices for P(spam)=0P(\text{spam}) = 0, whatever the rest says.

The Bernoulli model changes the accounting. A repeated word counts once, and each vocabulary word absent from the message contributes log⁡1−θ^spam,w1−θ^no,w\log\frac{1 - \hat\theta_{\text{spam},w}}{1 - \hat\theta_{\text{no},w}}. Each term is small, but there are 264: in the first example they sum to −1.09-1.09, as much as an informative word. The absence of “gratis” being evidence that a message is normal is reasonable for short messages. For long documents, by contrast, Bernoulli misses how often each word repeats, precisely the signal multinomial uses.

Why it works even when the assumption is false

Conditional independence almost never holds, yet Naive Bayes classifies well on many problems. Domingos and Pazzani (1997) explained why: good classification requires much less than good estimation. With 0–1 loss, only which side of zero the log odds fall on matters, not their value.

Their example is minimal. Two equally likely classes and three attributes AA, BB and CC, with AA and CC independent given the class and B=AB = A: an exact copy. The optimal rule ignores BB because it adds no information, and chooses ++ if P(A∣+)P(C∣+)>P(A∣−)P(C∣−)\Pr(A \given +)\Pr(C \given +) > \Pr(A \given -)\Pr(C \given -). Naive Bayes treats BB as independent of AA and counts AA twice. Write p=P(+∣A)p = \Pr(+ \given A) and q=P(+∣C)q = \Pr(+ \given C) (with equal priors, P(A∣+)/P(A∣−)=p/(1−p)\Pr(A \given +)/\Pr(A \given -) = p/(1 - p)). The optimal rule chooses ++ if pq>(1−p)(1−q)pq > (1 - p)(1 - q), that is, if q>1−pq > 1 - p; Naive Bayes chooses it if p2q>(1−p)2(1−q)p^2 q > (1 - p)^2(1 - q), that is, if

q>(1−p)2p2+(1−p)2.q > \frac{(1 - p)^2}{p^2 + (1 - p)^2}.

The two curves cross at (0,1)(0, 1), (12,12)(\tfrac12, \tfrac12) and (1,0)(1, 0), with only two narrow regions between them. Everywhere else, Naive Bayes makes the optimal decision, although its underlying assumption is unequivocally false. In contrast, its probabilities match the true ones only at those three points.

InteractiveEvidence counted twice
Plane (p,q)(p, q) with p=P(+∣A)p = P(+ \mid A), q=P(+∣C)q = P(+ \mid C): above each curve class + is chosen
p = P(+ | A)q = P(+ | C)
  • optimal rule: q = 1 − p
  • Naive Bayes counting A 2 times
  • decisions disagree
2
True P(+ | E)63.2 %
Naive Bayes P(+ | E)87.3 %
Area where decisions disagree9.7 %
Here both rules choose the same class, although Naive Bayes reports 87.3 % and the true probability is 63.2 %.
The example of Domingos and Pazzani (1997), generalized to mm copies of attribute AA (m=2m = 2 is the paper's example). With equal priors, the true probability is σ(logit⁡p+logit⁡q)\sigmoid(\operatorname{logit} p + \operatorname{logit} q) and Naive Bayes gives σ(mlogit⁡p+logit⁡q)\sigmoid(m \operatorname{logit} p + \operatorname{logit} q). Shaded regions are the (p,q)(p, q) where the two rules choose different classes; their area is computed using Simpson's rule, as a fraction of the square.

With m=2m = 2, regions where decisions disagree occupy 9.7% of the square. With 10 copies, 21.6%, and never more than 25% (the limit, when the curve becomes a step at p=12p = \tfrac12). Meanwhile, Naive Bayes probability moves to extremes: at the initial point, (p,q)=(0.8,0.3)(p, q) = (0.8, 0.3), the true probability of ++ is 0.6320.632 and Naive Bayes gives 0.8730.873; with m=5m = 5, 0.9980.998. Both rules choose ++, and one is much more confident than it should be. This is the general phenomenon: if several features convey the same information, Naive Bayes adds their evidence as though independent, inflating its log odds.

Domingos and Pazzani formalized the idea. For a particular example, with pp the true probability of class ++ and rr, ss the values Naive Bayes computes for ++ and −-, Naive Bayes is locally optimal under 0–1 loss if and only if (p≥12∧r≥s)∨(p≤12∧r≤s)(p \ge \tfrac12 \wedge r \ge s) \vee (p \le \tfrac12 \wedge r \le s): it need only get the side right. Their paper concludes that the region where its probabilities are optimal under squared loss is a “second-order infinitesimal” fraction of the region where its decisions are optimal under 0–1 loss, and proves Naive Bayes is optimal for learning conjunctions and disjunctions, which violate independence. It is not universal: with binary attributes, Naive Bayes is a linear classifier and cannot represent nonlinear concepts (such as exclusive or), and the authors themselves show it is not globally optimal for “mm of nn” concepts (true if at least mm of the nn attributes are true).

The other side is calibration: Naive Bayes probabilities cannot be used as-is when their values matter (to set a cost-based threshold, as in the confusion matrix, or combine them with other sources). The cell measures this on digits using accuracy, log loss and mean confidence, and repeats Domingos and Pazzani’s experiment at scale: copy all features mm times.

[ ]Evidence counted multiple times: accuracy versus calibrationBrowser
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import log_loss

def resumen(P, y):
    """Exactitud, confianza media en la clase elegida, log-pérdida y fracción de predicciones con P > 0.999."""
    conf = P.max(1)
    return np.mean(P.argmax(1) == y), conf.mean(), log_loss(y, np.clip(P, 1e-15, 1), labels=np.arange(10)), np.mean(conf > 0.999)

print("                      exactitud  confianza media  log-pérdida  P > 0.999")
for copias in (1, 2, 4):
    nb = NBGaussiano().fit(np.hstack([Xtr] * copias), ytr)
    P = np.exp(nb.predict_log_proba(np.hstack([Xte] * copias)))
    print(f"NB, {copias} copia(s)          {'%.3f        %.3f            %.2f         %.2f' % resumen(P, yte)}")
lr = LogisticRegression(max_iter=2000).fit(Xtr / 16, ytr)
print(f"regresión logística      {'%.3f        %.3f            %.2f         %.2f' % resumen(lr.predict_proba(Xte / 16), yte)}")

Three observations. First: Gaussian Naive Bayes achieves 84.8% accuracy but its mean confidence is 98.7%, and on 89% of test images it assigns more than 0.9990.999 to the chosen class. Its probabilities are much more extreme than its accuracy: it is overconfident, because an image’s 64 pixels are highly correlated (a stroke occupies neighboring pixels) and the model adds their evidence as though independent. Second: duplicating or quadrupling features multiplies all log-likelihoods by 2 or 4; since the ten class priors are nearly equal and small relative to those sums, the winning class does not change (accuracy is identical), but probabilities are pushed further toward 0 and 1, and log loss rises from 3.22 to 4.40. Third: logistic regression, fitted with conditional likelihood, has 89.9% mean confidence with 97.0% accuracy and log loss 0.16, twenty times lower. Measuring and correcting calibration is the topic of classifier calibration, and recalibrating Naive Bayes using Platt scaling or isotonic regression belongs to the following lesson.

Gaussian discriminant analysis

Gaussian Naive Bayes uses a diagonal covariance per class. The natural step is to allow correlations: model each class with a full multivariate Gaussian.

δk\delta_k is, except for the constant −d2log⁡2π-\frac d2\log 2\pi common to all classes, log⁡πk+log⁡N(x;μk,Σk)\log\pi_k + \log\Normal(\vb{x}; \vb{\mu}_k, \mat{\Sigma}_k): the usual joint log-likelihood. The middle term is minus half the squared Mahalanobis distance between x\vb{x} and the class mean: QDA assigns each point to the “closest” class measured using that class’s geometry, adjusted for the volume of its ellipse (log⁡∣Σk∣\log\abs{\mat{\Sigma}_k}) and its prior.

LDA’s linear form follows from expanding the square: (x−μk)⊤Σ−1(x−μk)=x⊤Σ−1x−2x⊤Σ−1μk+μk⊤Σ−1μk(\vb{x} - \vb{\mu}_k)\T\mat{\Sigma}\inv(\vb{x} - \vb{\mu}_k) = \vb{x}\T\mat{\Sigma}\inv\vb{x} - 2\vb{x}\T\mat{\Sigma}\inv\vb{\mu}_k + \vb{\mu}_k\T\mat{\Sigma}\inv\vb{\mu}_k. Terms x⊤Σ−1x\vb{x}\T\mat{\Sigma}\inv\vb{x} and log⁡∣Σ∣\log\abs{\mat{\Sigma}} are the same across classes and do not affect the argmax, so can be dropped. What remains is affine in x\vb{x}.

The proof of the log odds is the exercise “LDA log odds.” The logistic regression lesson anticipated this: logistic is the exact functional form of this model’s posterior. The interactive lets you see all three families together.

InteractiveFrom class densities to the boundary
LDA decision regions (winning-class color intensifies with posterior probability)
  • class A (2σ ellipse)
  • class B (2σ ellipse)
  • LDA boundary
  • Bayes boundary
  • covariance used by model
Model
Parameters
Scenario
LDA error9.5 %
Bayes error6.8 %
Estimated covariance parameters3
LDA with true parameters: excess over Bayes error of 2.7 points. Shared covariance cancels the quadratic term: boundaries are straight.
Explicit model: two or three Gaussian classes in the plane, with equal priors and parameters you set (solid ellipses are 2σ2\sigma contours). The dashed Bayes boundary is QDA with true parameters. ‘LDA’ uses the mean class covariance; ‘Gaussian NB’, only the diagonal of each covariance (dashed ellipses show the model's covariances). With ‘Estimated’, parameters are fitted by maximum likelihood with nkn_k points per class. Errors are calculated under the true distribution by numerical integration on a grid with step 0.060.06.

The initial state is a case LDA cannot capture: class A is wide and nearly round, B narrow and tilted. The Bayes boundary is a very elongated ellipse partly outside the window, and B’s region is its interior: far from the data, the wide class eventually always wins. LDA’s line only approximates it: 9.5% error versus Bayes’ 6.8%. Switch to QDA and the boundary matches Bayes (they are the same rule). “Concentric” is the extreme case: two classes with the same mean and different dispersion. LDA sees two classes with the same mean and the same mean covariance, cannot separate them and stays at 50%; QDA finds the circle and drops to 19.4%. In “Correlation”, the two classes share a highly tilted covariance: LDA is optimal (3.2%), but Naive Bayes, which sees only marginal variances, draws a vertical boundary suited to two round clouds and rises to 15.5%.

Now switch to “Estimated” with QDA, lower nkn_k to 5 or 10, and press “Another sample” several times. With free covariances, estimated conics jump between shapes: QDA estimates three covariance parameters per class and, with five points, estimates are very noisy. LDA, which pools all points to estimate one covariance, is much more stable even though its model is worse. This is the most visible version of the bias–variance tradeoff, and precisely what regularization exploits.

LDA and logistic regression

LDA and logistic regression produce classifiers of the same form, σ(w⊤x+b)\sigmoid(\vb{w}\T\vb{x} + b), but choose w\vb{w} differently. LDA maximizes joint likelihood, factored as ∏ip(xi) P(yi∣xi)\prod_i p(\vb{x}_i)\,\Pr(y_i \given \vb{x}_i); logistic regression maximizes only the second factor and leaves the distribution of XX unmodeled. If the Gaussian model is true, factor p(xi)p(\vb{x}_i) contains information about parameters that logistic regression discards, and LDA is more efficient; Ng and Jordan summarize Efron’s (1975) analysis by saying logistic regression is asymptotically only “very slightly” less efficient than discriminant analysis in that case, by a factor between 1/3 and 1/2. If the Gaussian model is false, that same factor biases LDA: its estimators are sample means and covariances, which weight distant points equally with those near the boundary, so a few outliers or heavy tails move Σ^\hat{\mat{\Sigma}} and thus the boundary, even if those points are correctly classified. Logistic regression looks only at P(Y∣x)\Pr(Y \given \vb{x}), and distant correctly classified points barely affect its gradient.

How many parameters, and what to do when there are too many

In dd dimensions, a covariance has d(d+1)/2d(d + 1)/2 free parameters. LDA estimates one; QDA, one per class; Gaussian Naive Bayes, only the dd variances of each class. On digits (d=64d = 64, K=10K = 10) that is 2080 covariance parameters for LDA, 20,800 for QDA and 640 for Naive Bayes, with 1797 images overall and about 180 per class. More basic than the number is a problem: the sample covariance of nkn_k points has rank at most nk−1n_k - 1, so if nk≤dn_k \le d it is singular, Σ^k−1\hat{\mat{\Sigma}}_k\inv does not exist, and QDA is undefined. Even with nkn_k somewhat larger than dd, its small eigenvalues are severely underestimated (covariance estimation error in high dimensions) and Σ^k−1\hat{\mat{\Sigma}}_k\inv amplifies them.

The answer is to shrink covariance toward something simpler, just as ridge does with coefficients:

  • Regularized discriminant analysis (Friedman, 1989): a family interpolating between QDA and LDA, Σ^k(α)=αΣ^k+(1−α)Σ^\hat{\mat{\Sigma}}_k(\alpha) = \alpha\hat{\mat{\Sigma}}_k + (1 - \alpha)\hat{\mat{\Sigma}}, and between LDA and scalar covariance, Σ^(γ)=γΣ^+(1−γ)σ^2I\hat{\mat{\Sigma}}(\gamma) = \gamma\hat{\mat{\Sigma}} + (1 - \gamma)\hat\sigma^2\mat{I} (ESL, section 4.3.1). With γ=0\gamma = 0 and equal priors, LDA becomes the nearest-centroid classifier in Euclidean distance.
  • Ledoit–Wolf shrinkage (2004): Σ^λ=(1−λ)Σ^+λtr⁡Σ^dI\hat{\mat{\Sigma}}_\lambda = (1 - \lambda)\hat{\mat{\Sigma}} + \lambda\frac{\tr\hat{\mat{\Sigma}}}{d}\mat{I} with λ\lambda chosen analytically to minimize expected squared estimation error in Frobenius norm. It is LinearDiscriminantAnalysis(solver="lsqr", shrinkage="auto"), which applies it to standardized features.
  • In QDA, scikit-learn offers reg_param, mixing each class covariance with the identity.

All trade a little bias for much lower variance, and all ensure an invertible covariance.

The laboratory: LDA and QDA from scratch

The implementation uses Cholesky factorization Σ^k=LkLk⊤\hat{\mat{\Sigma}}_k = \mat{L}_k\mat{L}_k\T: Mahalanobis distance is ∥Lk−1(x−μk)∥2\norm{\mat{L}_k\inv(\vb{x} - \vb{\mu}_k)}^2, computed with a triangular solve, and 12log⁡∣Σ^k∣=∑ilog⁡(Lk)ii\frac12\log\abs{\hat{\mat{\Sigma}}_k} = \sum_i \log (\mat{L}_k)_{ii}. There is never a need to invert a matrix.

[ ]LDA and QDA from scratch, with shrinkageBrowser
import matplotlib.pyplot as plt
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis, QuadraticDiscriminantAnalysis

class AnalisisDiscriminante:
    """LDA (compartida=True) o QDA por máxima verosimilitud, con shrinkage opcional hacia (tr Σ / d) I."""
    def __init__(self, compartida=True, shrinkage=0.0):
        self.compartida, self.shrinkage = compartida, shrinkage
    def _encoger(self, S):
        d = S.shape[0]
        return (1 - self.shrinkage) * S + self.shrinkage * np.trace(S) / d * np.eye(d)
    def fit(self, X, y):
        self.classes_ = np.unique(y)
        self.priors_ = np.array([np.mean(y == c) for c in self.classes_])
        self.means_ = np.stack([X[y == c].mean(0) for c in self.classes_])
        R = [X[y == c] - m for c, m in zip(self.classes_, self.means_)]           # residuos de cada clase
        if self.compartida:
            S = self._encoger(sum(r.T @ r for r in R) / len(y))                    # covarianza agrupada (divide entre n)
            self.covs_ = [S] * len(self.classes_)
        else:
            self.covs_ = [self._encoger(r.T @ r / len(r)) for r in R]
        for S in self.covs_:
            if np.linalg.eigvalsh(S)[0] <= 1e-12 * np.trace(S):                    # no invertible en la práctica
                raise np.linalg.LinAlgError("covarianza singular")
        self.chol_ = [np.linalg.cholesky(S) for S in self.covs_]
        return self
    def joint_log_likelihood(self, X):
        J = []
        for L, m, p in zip(self.chol_, self.means_, self.priors_):
            Z = np.linalg.solve(L, (X - m).T)                                      # L⁻¹(x − μ): Mahalanobis² = ‖Z‖²
            J.append(np.log(p) - np.log(np.diag(L)).sum() - 0.5 * (Z ** 2).sum(0))
        return np.stack(J, 1)
    def predict_proba(self, X):
        J = self.joint_log_likelihood(X)
        return np.exp(J - logsumexp(J, 1, keepdims=True))
    def predict(self, X):
        return self.classes_[self.joint_log_likelihood(X).argmax(1)]

rng = np.random.default_rng(0)
A0, A1 = np.array([[1.0, 0.0], [0.6, 0.5]]), np.array([[0.4, 0.0], [-0.3, 1.2]])
def muestra(n):
    """Clase 0: N((−1, 0), A0 A0ᵀ); clase 1: N((1, 0.5), A1 A1ᵀ); priors 1/2."""
    y = rng.integers(0, 2, n)
    Z = rng.standard_normal((n, 2))
    return np.where(y[:, None] == 0, Z @ A0.T + [-1, 0], Z @ A1.T + [1, 0.5]), y

X2, y2 = muestra(400)
Xt2, yt2 = muestra(20000)
modelos = {"LDA": AnalisisDiscriminante(True).fit(X2, y2), "QDA": AnalisisDiscriminante(False).fit(X2, y2)}
for (nombre, mio), ref in zip(modelos.items(), (LinearDiscriminantAnalysis(solver="lsqr"), QuadraticDiscriminantAnalysis())):
    ref.fit(X2, y2)
    print(f"{nombre}: diferencia máxima con scikit-learn en P(y | x) {np.abs(mio.predict_proba(Xt2) - ref.predict_proba(Xt2)).max():.1e}, "
          f"error de test {np.mean(mio.predict(Xt2) != yt2):.3f}")
qda = QuadraticDiscriminantAnalysis(store_covariance=True).fit(X2, y2)
n0 = np.sum(y2 == 0)
print(f"covariance_ de QDA en scikit-learn / covarianza MLE (clase 0): {qda.covariance_[0][0, 0] / modelos['QDA'].covs_[0][0, 0]:.5f};"
      f"  n_0/(n_0 − 1) = {n0 / (n0 - 1):.5f}")

g1, g2 = np.meshgrid(np.linspace(-4, 4, 300), np.linspace(-3.5, 4, 300))
rejilla = np.c_[g1.ravel(), g2.ravel()]
fig, ax = plt.subplots(figsize=(6.4, 4.4))
ax.scatter(X2[:, 0], X2[:, 1], c=y2, cmap="coolwarm", s=10, alpha=0.7)
for (nombre, m), estilo in zip(modelos.items(), ("--", "-")):
    ax.contour(g1, g2, m.predict_proba(rejilla)[:, 1].reshape(g1.shape), levels=[0.5], colors="k", linestyles=estilo)
    ax.plot([], [], "k" + estilo, label=nombre)
ax.legend()
ax.set_title("Fronteras de LDA (recta) y QDA (cónica)")
plt.show()

LDA agrees with scikit-learn up to rounding. QDA differs by order 10−310^{-3}, and the third line explains why: the scikit-learn version running in your browser estimates each class covariance with divisor nk−1n_k - 1 (the unbiased covariance) rather than maximum likelihood’s nkn_k, and their ratio is exactly n0/(n0−1)n_0/(n_0 - 1). With around 200 points per class the difference is immaterial; with nkn_k close to dd it is not. In this problem, with two classes with very different covariances, QDA has test error 6.0% and LDA 8.6%: with 400 points to estimate 10 parameters, the conic pays off. The next cell changes the regime: d=50d = 50 features and only 30 examples per class, with a non-diagonal true covariance (eigenvalues between 0.20.2 and 33 in a random basis) and classes separated in the first five coordinates.

[ ]High-dimensional covariance: singularity and shrinkageBrowser
from scipy.stats import norm

d, n_k = 50, 30
rng = np.random.default_rng(1)
Q, _ = np.linalg.qr(rng.standard_normal((d, d)))
Sigma = Q @ np.diag(np.linspace(0.2, 3, d)) @ Q.T
L_v = np.linalg.cholesky(Sigma)
mu1 = np.zeros(d); mu1[:5] = 0.6
def genera(n):
    y = np.arange(n) % 2
    return rng.standard_normal((n, d)) @ L_v.T + np.where(y[:, None] == 1, mu1, 0.0), y

X, y = genera(2 * n_k)
Xt, yt = genera(20000)
print(f"error de Bayes: {norm.cdf(-0.5 * np.sqrt(mu1 @ np.linalg.solve(Sigma, mu1))):.3f}")
print(f"rango de la covarianza de una clase: {np.linalg.matrix_rank(np.cov(X[y == 0].T, bias=True))} de {d}")
for s in (0.0, 0.1, 0.3, 0.6):
    e_lda = np.mean(AnalisisDiscriminante(True, s).fit(X, y).predict(Xt) != yt)
    try:
        e_qda = f"{np.mean(AnalisisDiscriminante(False, s).fit(X, y).predict(Xt) != yt):.3f}"
    except np.linalg.LinAlgError:
        e_qda = "covarianza singular"
    print(f"shrinkage {s:.1f}:   LDA {e_lda:.3f}   QDA {e_qda}")
lw = LinearDiscriminantAnalysis(solver="lsqr", shrinkage="auto").fit(X, y)
print(f"LDA con Ledoit-Wolf (scikit-learn): {np.mean(lw.predict(Xt) != yt):.3f}")

Each class covariance, estimated from 30 points in 50 dimensions, has rank 29: unregularized QDA cannot even be evaluated. The pooled covariance has 60 points and is invertible but ill-conditioned, and unshrunk LDA has 44.0% error, close to chance, versus Bayes error 25.2%. With shrinkage 0.30.3 it falls to 37.1%, and automatic Ledoit–Wolf λ\lambda gives 38.5% without validation. QDA, even shrunk, stays above 43%: 30 points per class do not suffice to estimate two covariances of 1275 parameters each. Notice that even the best shrinkage does not reach Bayes error: 60 examples in 50 dimensions are few for any method, and shrinkage only determines how much of that little is wasted.

What the generative model provides: missing data

One advantage of the generative model is what the opening section promised: if features are missing at prediction time, a Gaussian marginal is another Gaussian with the corresponding submatrices, xobs∣k∼N((μk)obs,Σobs,obs)\vb{x}_{\text{obs}} \given k \sim \Normal\big((\vb{\mu}_k)_{\text{obs}}, \mat{\Sigma}_{\text{obs},\text{obs}}\big), so LDA can classify using observed features without imputing anything. The cell randomly removes a fraction of pixels from digits test images and compares LDA with marginalization to two alternatives imputing the training mean: the same LDA and logistic regression.

[ ]Missing data: marginalization versus imputationBrowser
lda = LinearDiscriminantAnalysis(solver="lsqr", shrinkage="auto").fit(Xtr, ytr)
S, M, lp = lda.covariance_, lda.means_, np.log(lda.priors_)
print(f"sin datos que falten: LDA {lda.score(Xte, yte):.3f}   logística {lr.score(Xte / 16, yte):.3f}")
rng = np.random.default_rng(0)
for frac in (0.25, 0.5, 0.75):
    falta = rng.uniform(size=Xte.shape) < frac
    aciertos = 0
    for x, f, etiqueta in zip(Xte, falta, yte):
        o = ~f                                                                     # variables observadas
        B = np.linalg.solve(S[np.ix_(o, o)], M[:, o].T)                            # Σ_oo⁻¹ μ_k,o (una columna por clase)
        delta = x[o] @ B - 0.5 * np.einsum("kj,jk->k", M[:, o], B) + lp           # δ_k de LDA con la marginal
        aciertos += delta.argmax() == etiqueta
    Ximp = np.where(falta, Xtr.mean(0), Xte)
    print(f"faltan {frac:.0%}:  LDA marginalizando {aciertos / len(yte):.3f}   LDA imputando {lda.score(Ximp, yte):.3f}   "
          f"logística imputando {lr.score(Ximp / 16, yte):.3f}")

With complete data, logistic regression is slightly more accurate (97.0% versus 95.7%). As soon as data are missing this reverses: with half the pixels erased, marginalizing LDA achieves 90.6% and logistic regression with imputation 78.0%; with three quarters erased, 74.6% versus 47.6%. Mean imputation puts an “average digit” in the gaps that resembles no class; marginalization uses the correlation structure LDA learned (neighboring pixels predict one another) so the gaps are unnecessary. The experiment erases pixels completely at random; if missingness depended on the value itself, neither marginalization nor mean imputation would be correct without modeling the mechanism, the topic of EM with missing data. In Naive Bayes, marginalizing is even simpler: as likelihood is a product, simply omit the missing feature’s factor.

Ng and Jordan: two regimes

Which is better, then, generative or discriminative? The usual answer, summarized in Vapnik’s maxim against solving a more general problem as an intermediate step, was “discriminative, almost always.” Ng and Jordan (2002) qualified it with an analysis of the two simplest pairs. In their notation, nn is dimension and mm the number of examples; here we translate them to dd and nn.

Asymptotics. Let hGen,∞h_{\mathrm{Gen},\infty} and hDis,∞h_{\mathrm{Dis},\infty} be classifiers with population parameters (infinite data). Their formal analysis takes as discriminative the linear classifier minimizing training 0–1 error (logistic regression with log loss is its computable approximation). That classifier converges to the best linear classifier, and since Naive Bayes is one of them, ε(hDis,∞)≤ε(hGen,∞)\varepsilon(h_{\mathrm{Dis},\infty}) \le \varepsilon(h_{\mathrm{Gen},\infty}): the discriminative model has the better asymptote. For logistic regression with log loss the inequality is not guaranteed generally (minimizing log loss is not minimizing 0–1 error), but it holds when the logistic model is correct, as in the experiment below where its asymptote is Bayes error.

Discriminative rate. By Vapnik’s theory, with hyperplanes of Rd\R^d (VC dimension of order dd), with high probability ε(hDis)≤ε(hDis,∞)+O((d/n)log⁡(n/d))\varepsilon(h_{\mathrm{Dis}}) \le \varepsilon(h_{\mathrm{Dis},\infty}) + \bigO\big(\sqrt{(d/n)\log(n/d)}\big): n=O(d)n = \bigO(d) suffices to approach the asymptote, and in the worst case a number of order dd is necessary.

Generative rate. Naive Bayes parameters are means and frequencies of a single variable. By Chernoff’s inequality and the union bound over the O(d)\bigO(d) estimates, with n=O(ε−2log⁡(d/δ))n = \bigO\big(\varepsilon^{-2}\log(d/\delta)\big) examples all are within ε\varepsilon of their population values with probability 1−δ1 - \delta. That does not suffice for error to converge (an almost exact parameter can change decisions on examples near the boundary), but their theorem 4 gives ε(hGen)≤ε(hGen,∞)+G(O(log⁡d/n))\varepsilon(h_{\mathrm{Gen}}) \le \varepsilon(h_{\mathrm{Gen},\infty}) + G\big(\bigO(\sqrt{\log d / n})\big), where G(τ)G(\tau) is the probability that population log odds fall within τd\tau d of zero on the correct side. If most features are relevant, those log odds grow as dd and GG is small, and their corollary concludes that n=O(log⁡d)n = \bigO(\log d) suffices.

Logarithmic versus linear in dimension: the generative model approaches its asymptote sooner, even if that asymptote is worse. Hence the prediction: as nn grows there are two regimes, one with little data where Naive Bayes wins and one with much data where logistic regression catches and surpasses it. They tested this on 15 UCI datasets (8 with continuous features and 7 discrete), averaging 1000 random train/test splits, with smoothed Naive Bayes (α=1\alpha = 1) and unregularized logistic regression: most show the crossover, and in the few where logistic regression does not catch Naive Bayes, datasets are small and nn does not grow enough. Zheng et al. (2023) extended the analysis to the multiclass case under other assumptions and found the same separation between O(log⁡d)\bigO(\log d) and O(d)\bigO(d).

The interactive reproduces the situation with a model where everything is exactly calculable: two equally likely Gaussian classes with means ±Δ/2\pm\vb{\Delta}/2, all variances 1, and the first half of the features equicorrelated with correlation ρ\rho. With ρ=0\rho = 0 conditional independence holds and both models are correctly specified; with ρ>0\rho > 0, the first half of the features repeats the same information, like the copies of AA in Domingos and Pazzani’s example, and Naive Bayes counts it repeatedly. Since both classifiers are linear, their exact error under the model is 12Φ(−w⊤Δ/2+bw⊤Σw)+12Φ(−w⊤Δ/2+bw⊤Σw)\frac12\Phi\big(-\frac{\vb{w}\T\vb{\Delta}/2 + b}{\sqrt{\vb{w}\T\mat{\Sigma}\vb{w}}}\big) + \frac12\Phi\big(\frac{-\vb{w}\T\vb{\Delta}/2 + b}{\sqrt{\vb{w}\T\mat{\Sigma}\vb{w}}}\big) and no test set is required.

InteractiveNg and Jordan live
Exact test error versus training size nn (log scale), mean of 0 samples, d=20d = 20, ρ=0.60\rho = 0.60
Dimension dd
0.60
Logistic regression regularization
Repetitions averaged0 of 30
Naive Bayes asymptote25.3 %
Bayes error (logistic asymptote)16.5 %
Logistic regression leads fromno crossing
Calculating the first repetition…
Explicit model, as in the next cell. X∣Y∼N(±Δ/2,Σ)X \given Y \sim \Normal(\pm\vb{\Delta}/2, \mat{\Sigma}) with Δj=2.5631/d\Delta_j = 2.5631/\sqrt d (Bayes error of 10% with ρ=0\rho = 0), Σjj=1\Sigma_{jj} = 1 and correlation ρ\rho among first-half features. Naive Bayes is Gaussian with one per-feature variance shared across classes (the model Ng and Jordan analyze); logistic regression minimizes log loss plus ∥w∥2/(2C)\norm{\vb{w}}^2/(2C) using Newton's method. Each point is mean exact error over up to 30 balanced training samples of size nn, generated in your browser with a fixed seed.

The initial state, d=20d = 20 and ρ=0.6\rho = 0.6, shows both regimes: Naive Bayes leads with 20 and 40 examples (with 10, both are around 30% and ordering depends on samples), quickly plateaus at its asymptote (orange dashes), and logistic regression crosses it and keeps falling toward Bayes error. Move ρ\rho to 0: the two asymptotes coincide and Naive Bayes no longer has anything to lose, so it leads (or ties) for every nn. Increase ρ\rho: the Naive Bayes asymptote rises and crossover comes earlier. Now return to ρ=0.6\rho = 0.6, switch to scikit-learn’s default regularization, C=1C = 1, and look at the first nn: logistic regression no longer loses with little data (at worst it ties). The reason is instructive. With a strong penalty and small w\vb{w}, σ(z)≈12+z4\sigmoid(z) \approx \frac12 + \frac z4 and the log-loss gradient at w=0\vb{w} = \vb{0} is −∑i(yi−12)xi-\sum_i (y_i - \tfrac12)\vb{x}_i, proportional to the class mean difference: heavily regularized logistic regression is nearly a generative centroid classifier, with the same small-sample efficiency. Ng and Jordan already cautioned that regularization changes the model family and lies outside their analysis. The cell reproduces curves with 20 repetitions.

[ ]Ng and Jordan in miniatureBrowser
from scipy.special import expit

def logistica(X, y, C, iters=50):
    """Regresión logística con penalización ‖w‖²/(2C) (sin penalizar el sesgo) por el método de Newton."""
    n, d = X.shape
    A = np.hstack([X, np.ones((n, 1))])
    R = np.eye(d + 1) / C
    R[d, d] = 0.0
    th = np.zeros(d + 1)
    for _ in range(iters):
        p = expit(A @ th)
        paso = np.linalg.solve((A * (p * (1 - p))[:, None]).T @ A + R, A.T @ (p - y) + R @ th)
        th -= paso
        if np.abs(paso).max() < 1e-8:
            break
    return th[:d], th[d]

def nb_gaussiano(X, y):
    """Naive Bayes gaussiano con una varianza por variable común a las dos clases: frontera lineal."""
    m1, m0 = X[y == 1].mean(0), X[y == 0].mean(0)
    var = (((X[y == 1] - m1) ** 2).sum(0) + ((X[y == 0] - m0) ** 2).sum(0)) / len(y)
    w = (m1 - m0) / var
    return w, -0.5 * (m1 + m0) @ w + np.log(np.mean(y) / (1 - np.mean(y)))

def problema(d, rho):
    S = np.eye(d)
    S[: d // 2, : d // 2] = rho + (1 - rho) * np.eye(d // 2)
    return np.full(d, 2.5631 / np.sqrt(d)), S

def error_exacto(w, b, delta, S):
    s = np.sqrt(w @ S @ w)
    return 0.5 * norm.cdf(-(w @ delta / 2 + b) / s) + 0.5 * norm.cdf((-(w @ delta) / 2 + b) / s)

ns = [10, 20, 40, 80, 160, 320, 640]
rng = np.random.default_rng(0)
for d, rho in ((10, 0.0), (20, 0.6)):
    delta, S = problema(d, rho)
    L_s = np.linalg.cholesky(S)
    E = np.zeros((3, len(ns)))
    for r in range(20):
        for j, n in enumerate(ns):
            y = np.arange(n) % 2
            X = rng.standard_normal((n, d)) @ L_s.T + np.where(y[:, None] == 1, delta / 2, -delta / 2)
            E[0, j] += error_exacto(*nb_gaussiano(X, y), delta, S) / 20
            E[1, j] += error_exacto(*logistica(X, y, 100.0), delta, S) / 20
            E[2, j] += error_exacto(*logistica(X, y, 1.0), delta, S) / 20
    bayes = norm.cdf(-0.5 * np.sqrt(delta @ np.linalg.solve(S, delta)))
    print(f"\nd = {d}, rho = {rho}: error de Bayes {bayes:.3f}, asíntota de naive Bayes {error_exacto(delta, 0.0, delta, S):.3f}")
    print("        n " + "".join(f"{n:7d}" for n in ns))
    for nombre, fila in zip(("NB", "LR C=100", "LR C=1"), E):
        print(f"{nombre:9s} " + "".join(f"{e:7.3f}" for e in fila))

With d=10d = 10 and ρ=0\rho = 0, Naive Bayes leads weakly regularized logistic regression at all seven sizes (for example, 0.1280.128 versus 0.1920.192 with n=40n = 40) and both converge to Bayes error, 0.1000.100; here logistic regression with C=1C = 1 also trails Naive Bayes except at n=10n = 10, where they tie (0.1980.198 versus 0.1970.197). With d=20d = 20 and ρ=0.6\rho = 0.6, Bayes error is 0.1650.165 and the Naive Bayes asymptote 0.2530.253: Naive Bayes reaches it around n=40n = 40 (0.2480.248) and remains there, while logistic regression with C=100C = 100, worse until n=40n = 40 (0.2700.270), surpasses it from n=80n = 80 (0.2470.247 versus 0.2530.253) and reaches 0.1740.174 with n=640n = 640. Logistic regression with C=1C = 1 wins at all seven sizes, including n=10n = 10 (0.2870.287 versus 0.2950.295). Ng and Jordan’s two regimes appear when the generative model is misspecified and the discriminative one unregularized; regularization, always used in practice, brings them much closer.

The scikit-learn version

sklearn.naive_bayes has one class per event model, all with fit, partial_fit, predict_proba and predict_log_proba:

  • GaussianNB(var_smoothing=1e-9): adds to all variances ε=\varepsilon = var_smoothing ×\times the largest feature variance, so none is zero.
  • MultinomialNB(alpha=1.0) for counts and BernoulliNB(alpha=1.0, binarize=0.0) for presence (binarizes input with threshold binarize).
  • ComplementNB, by Rennie, Shih, Teevan and Karger (2003), estimates each class’s parameters using counts from all others (its complement), which provides far more data when a class is small; scikit-learn recommends it for imbalanced text classes.
  • CategoricalNB for categorical features with more than two values.

And sklearn.discriminant_analysis has LinearDiscriminantAnalysis (with solver="svd", "lsqr" or "eigen"; the last two support shrinkage) and QuadraticDiscriminantAnalysis(reg_param=...).

[ ]The scikit-learn familyBrowser
import warnings
from sklearn.naive_bayes import BernoulliNB, ComplementNB
from sklearn.model_selection import cross_val_score, StratifiedKFold, RepeatedStratifiedKFold

cv_txt = RepeatedStratifiedKFold(n_splits=5, n_repeats=4, random_state=0)
for nombre, m in (("MultinomialNB", MultinomialNB()), ("BernoulliNB", BernoulliNB()), ("ComplementNB", ComplementNB()),
                  ("LogisticRegression", LogisticRegression())):
    s = cross_val_score(m, X_txt, y_txt, cv=cv_txt)
    print(f"corpus  {nombre:22s} {s.mean():.3f} ± {s.std():.3f}")

cv = StratifiedKFold(5, shuffle=True, random_state=0)
with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    for nombre, m in (("GaussianNB", GaussianNB()), ("MultinomialNB", MultinomialNB()), ("BernoulliNB(binarize=8)", BernoulliNB(binarize=8)),
                      ("LDA", LinearDiscriminantAnalysis()), ("LDA, shrinkage auto", LinearDiscriminantAnalysis(solver="lsqr", shrinkage="auto")),
                      ("QDA", QuadraticDiscriminantAnalysis()), ("QDA, reg_param=0.05", QuadraticDiscriminantAnalysis(reg_param=0.05)),
                      ("QDA, reg_param=0.5", QuadraticDiscriminantAnalysis(reg_param=0.5))):
        try:
            s = cross_val_score(m, Xd, yd, cv=cv, error_score="raise")
            print(f"digits  {nombre:24s} {s.mean():.3f} ± {s.std():.3f}")
        except Exception as e:
            print(f"digits  {nombre:24s} falla: {type(e).__name__}")

print(f"\npares (clase, píxel) de varianza nula en el entrenamiento: {sum(int((Xtr[ytr == c].var(0) == 0).sum()) for c in range(10))} de 640")
with np.errstate(all="ignore"):
    J = NBGaussiano(var_smoothing=0.0).fit(Xtr, ytr).joint_log_likelihood(Xte)
print(f"GaussianNB sin var_smoothing: filas de test con alguna puntuación nan {np.isnan(J).any(1).mean():.0%}")
for vs in (1e-9, 1e-2, 1e-1):
    print(f"var_smoothing = {vs:g}: exactitud {np.mean(NBGaussiano(vs).fit(Xtr, ytr).predict(Xte) == yte):.3f}")

completo = MultinomialNB().fit(X_txt, y_txt)
por_lotes = MultinomialNB()
for lote in np.array_split(np.random.default_rng(0).permutation(len(y_txt)), 3):
    por_lotes.partial_fit(X_txt[lote], y_txt[lote], classes=[0, 1])
print(f"\npartial_fit en 3 lotes frente a fit: diferencia máxima {np.abs(completo.feature_log_prob_ - por_lotes.feature_log_prob_).max():.1e}")

On the corpus, with 60 messages, all three Naive Bayes variants achieve around 91% cross-validation accuracy and logistic regression with default regularization stays at 86%, although standard deviations of 6 to 10 points are inevitable with 12 messages per fold: so little data yields no significant differences between the three Naive Bayes models. On digits the ordering changes. Naive Bayes, whose assumption of independent pixels is very false, stays between 85% and 90%; LDA rises to 95%; unregularized QDA fails because pixels are constant within each class (131 class–pixel pairs of zero variance, such as image borders) and its covariance is singular; and QDA with reg_param=0.5 reaches 98.8%, best in the table. With 180 examples per class, a well-shrunk per-class covariance is worth more than the shared-covariance assumption.

Zero variances also trouble GaussianNB without its smoothing term: with var_smoothing=0 all test rows have some nan score (an 0/00/0 in the quadratic term) and accuracy collapses to 10%. The default, 10−910^{-9}, avoids division by zero but is not necessarily good: raising it to 0.10.1 takes accuracy from 84.8% to 91.3%, because it stops rewarding exact matches in nearly constant pixels. It is a real hyperparameter. Finally, batched partial_fit produces exactly the same model as fit: training Naive Bayes is counting, and counting can be done in parts.

Common mistakes

Exercises

NumericA word never seen
A vocabulary contains 10,000 words and the training documents of one class contain 50,000 tokens in total. One vocabulary word never appears in that class. What probability does multinomial Naive Bayes with Laplace smoothing, α=1\alpha = 1, assign it?
NumericWhen does the product become zero?
You compute a document's likelihood by directly multiplying its per-token probabilities in float64, and they are all 10−310^{-3}. The smallest representable positive value is the subnormal 4.94⋅10−3244.94 \cdot 10^{-324}, and results below half of it round to 0. What is the minimum number of tokens needed for the product to be exactly 0?
QuizQDA parameters
How many covariance parameters does QDA estimate with KK classes in dd dimensions?
QuizDuplicate features
You train Gaussian Naive Bayes on two equally likely classes. You then add an exact copy of each feature (twice as many columns) and retrain. What happens to test predictions?
QuizTwo event models
You classify long documents (thousands of words) with a 50,000-word vocabulary. What difference between Bernoulli and multinomial Naive Bayes matters?
QuizA missing feature
An already-trained Gaussian Naive Bayes model must classify an example missing feature x3x_3. What is correct according to the model itself?
QuizLittle data, many features
You have 40 labeled examples with 5000 binary features, many relevant, and know groups of features are highly correlated. According to Ng and Jordan's analysis, what do you expect from Naive Bayes versus unregularized logistic regression?
ProofLDA log odds
Prove: If X∣Y=k∼N(μk,Σ)X \given Y = k \sim \Normal(\vb{\mu}_k, \mat{\Sigma}) for k∈{0,1}k \in \{0, 1\}, with shared Σ≻0\mat{\Sigma} \succ 0 and priors π0,π1>0\pi_0, \pi_1 > 0, then log⁡P(Y=1∣x)P(Y=0∣x)\log\frac{\Pr(Y = 1 \given \vb{x})}{\Pr(Y = 0 \given \vb{x})} is an affine function of x\vb{x}. Give its coefficients.
0
Write the Gaussian density as N(x;μ,Σ)=(2π)−d/2∣Σ∣−1/2exp⁡(−12(x−μ)⊤Σ−1(x−μ))\Normal(\vb{x}; \vb{\mu}, \mat{\Sigma}) = (2\pi)^{-d/2}\abs{\mat{\Sigma}}^{-1/2}\exp\big(-\tfrac12(\vb{x} - \vb{\mu})\T\mat{\Sigma}\inv(\vb{x} - \vb{\mu})\big).

Step 1 of 4. By Bayes' theorem, the log odds are log⁡π1π0+log⁡N(x;μ1,Σ)N(x;μ0,Σ)\log\frac{\pi_1}{\pi_0} + \log\frac{\Normal(\vb{x}; \vb{\mu}_1, \mat{\Sigma})}{\Normal(\vb{x}; \vb{\mu}_0, \mat{\Sigma})}. Which density factors cancel in the ratio?

ProofSmoothing as Bayesian inference
Prove: Let θ=(θ1,…,θV)\vb{\theta} = (\theta_1, \dots, \theta_V) be the word distribution for a class, with prior Dir(β,…,β)\mathrm{Dir}(\beta, \dots, \beta), and let N1,…,NVN_1, \dots, N_V be observed counts, with N=∑jNjN = \sum_j N_j. The additive estimator θ^j=(Nj+α)/(N+αV)\hat\theta_j = (N_j + \alpha)/(N + \alpha V) is the posterior mean if β=α\beta = \alpha and the MAP if β=α+1\beta = \alpha + 1 (with α>0\alpha > 0).
0
The density of Dir(γ1,…,γV)\mathrm{Dir}(\gamma_1, \dots, \gamma_V) on the simplex is proportional to ∏jθjγj−1\prod_j \theta_j^{\gamma_j - 1}, and its mean is γj/∑lγl\gamma_j / \sum_l \gamma_l.

Step 1 of 3. What is the posterior of θ\vb{\theta}?

CodeStable multinomial Naive Bayes
Implement multinomial_nb_fit(X, y, alpha), returning the tuple (clases, log_prior, log_theta) with log_theta shaped K×VK \times V (additive smoothing), and predict_log_proba(modelo, X), returning log⁡P(y=c∣x)\log P(y = c \mid \vb{x}) with shape n×Kn \times K, classes in np.unique(y) order. The starter code multiplies probabilities directly and does not smooth. Tests compare with MultinomialNB and check for no underflow on documents with hundreds of thousands of tokens and no infinities for words unseen in a class.
import numpy as np

def multinomial_nb_fit(X, y, alpha=1.0):
  """(clases, log_prior, log_theta) del Naive Bayes multinomial con suavizado aditivo alpha."""
  X = np.asarray(X, dtype=float)
  y = np.asarray(y)
  clases = np.unique(y)
  prior = np.array([np.mean(y == c) for c in clases])
  theta = np.stack([X[y == c].sum(0) / X[y == c].sum() for c in clases])     # sin suavizar
  return clases, np.log(prior), np.log(theta)

def predict_log_proba(modelo, X):
  """log P(y = c | x) para cada fila de X (n × K)."""
  clases, log_prior, log_theta = modelo
  X = np.asarray(X, dtype=float)
  p = np.exp(log_prior) * np.prod(np.exp(log_theta)[None] ** X[:, None, :], axis=2)   # producto directo
  return np.log(p / p.sum(1, keepdims=True))
Shift+Enter to run

Summary

Key idea
A generative classifier models how each class generates data and decides using Bayes’ theorem. That extra commitment provides small-sample efficiency, enables marginalizing missing data and sampling, and costs a worse asymptote if the model is false. Classification only requires log odds to fall on the correct side; reliable probabilities require much more.
  • Naive Bayes assumes conditional independence given class: parameters go from exponential to linear in dd and training is counting. Its maximum-likelihood estimators are means and variances (Gaussian), document fractions (Bernoulli) or token fractions (multinomial). With counts it is a linear classifier with weights log⁡(θ1j/θ0j)\log(\theta_{1j}/\theta_{0j}).
  • Additive smoothing (Nkj+α)/(Nk+αV)(N_{kj} + \alpha)/(N_k + \alpha V) prevents an unseen word from eliminating a class, and is the posterior mean with prior Dir(α)\mathrm{Dir}(\alpha) and MAP with Dir(α+1)\mathrm{Dir}(\alpha + 1). Compute everything in logs and normalize with log-sum-exp: direct multiplication is 0 with around a hundred tokens.
  • Naive Bayes decides well even when its assumption is false (Domingos and Pazzani: only the side of the log odds must be correct), but its probabilities are poorly calibrated: it counts the same evidence repeatedly and pushes them toward 0 and 1.
  • QDA models each class with its own Gaussian and produces quadratic boundaries; LDA shares covariance, producing linear boundaries and an exactly logistic posterior, w=Σ−1(μ1−μ0)\vb{w} = \mat{\Sigma}\inv(\vb{\mu}_1 - \vb{\mu}_0). QDA estimates Kd(d+1)/2K d(d + 1)/2 covariance parameters and is singular if nk≤dn_k \le d: in high dimensions it is shrunk (RDA, Ledoit–Wolf, reg_param).
  • Ng and Jordan: the discriminative model has a better asymptote and needs order dd examples; the generative model approaches its own with order log⁡d\log d. The generative model wins with little data, the discriminative with much, and regularization brings them closer.