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
- 11Logistic regressionSoftmax (multinomial logistic) regressionStatistical functional elicited by a lossConfusion matrix and derived metricsLearning curve
- 04Conditional probabilityBayes' theoremMultivariate Gaussian distributionBeta and Dirichlet distributions
- 05Maximum likelihood estimator (MLE)Conjugate priors
- 09Log-sum-exp trick and stable softmax
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 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, . Naive Bayes and discriminant analysis do something else: they model how each class generates data, , and each class’s frequency, , 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 classes and priors , conditional probability and Bayes’ theorem give
The rule on the right is the Bayes rule for 0–1 loss when and 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 , 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 , but the generative model obtains from means, variances or frequencies, while logistic regression optimizes it.
Modeling is more work than modeling the boundary, but in return gives things a discriminative model does not have:
- Sampling. With you can generate synthetic examples from each class. With you cannot.
- Missing data. If is missing at prediction time, the generative model can marginalize: . Logistic regression needs the values and forces you to impute. You will measure this in the lab.
- Detecting unusual examples. says whether an example resembles anything seen; a posterior of 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 without retraining.
The cost is twofold. Statistical: if 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 with large is much harder to estimate than a boundary. With binary variables, each class’s joint distribution has free parameters: with there are more than . 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, , modeling each factor with a neural network: this is the autoregressive factorization of deep generative models, which model in millions of dimensions.
Naive Bayes
The conditional independence assumption
With binary features, the number of parameters per class goes from to : 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 .
Three models for each feature
- Gaussian, for continuous features: . This is Gaussian discriminant analysis with diagonal covariance matrices, one per class.
- Bernoulli, for binary features (in text, whether word appears): . Each document is described by the words in the vocabulary, including absent ones.
- Multinomial, for counts (in text, how often each word appears): a document of tokens is a sequence of independent draws from a categorical distribution with parameters , with :
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 ), 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 be the number of examples in class , the number of times word appears in documents of class , the total tokens in the class, and the number of documents in class containing word .
Proof
By independence of examples and the Naive Bayes factorization, joint log-likelihood is
a sum of terms that share no parameters: priors appear only in the first and each pair only in its own. Maximizing means maximizing each term separately. The first, under constraint , is that of a categorical distribution, whose maximum is (the same calculation as the multinomial case below). Each Gaussian term is the log-likelihood of observations from a univariate normal, maximized by sample mean and variance with divisor . Each Bernoulli term is , whose derivative vanishes at . In the multinomial, a class’s are linked by , so maximize using a Lagrange multiplier:
∎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
a linear function of counts: multinomial Naive Bayes is a linear classifier with weights , 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 : , 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, , and any message containing it will have 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 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 : 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: has density proportional to on the simplex, mean and, if all , mode .
The posterior comes from multiplying likelihood by prior : product is the kernel of the Dirichlet with parameters . The exercise “Smoothing as Bayesian inference” asks you to prove the two interpretations of the estimator. The practical consequence is an interpretation of : it is the number of fictitious observations per word before seeing the data, and is the total. With a large vocabulary, can be comparable to the number of real class tokens, and then is no longer a detail: it is a regularizer pulling all toward the uniform , 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 tokens with per-token probabilities of order has likelihood of order . The smallest normal float64 is and the smallest subnormal is , 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: and no decision. The usual solution is to work with , a sum of moderate numbers, and normalize with the log-sum-exp trick,
which does not overflow because the largest exponent is . With log-likelihoods, the entire batch calculation is also a matrix product: , with the counts and .
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 images with intensities from 0 to 16), and compares them with MultinomialNB and GaussianNB.
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 , which looks large until you consider the scale: some log-probabilities are of order , and at that scale 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 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 even though “mañana” appears only in normal messages; “¿Comemos mañana en casa?” (Shall we eat at home tomorrow?) is normal (); and “Oferta: compra hoy tu entrada para el concierto” (Offer: buy your concert ticket today) is spam () 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 and the posterior is computed without trouble.
Naive Bayes on text, word by word
With , the first example adds for “gana”, for “gratis”, for “llama” and for “un” (12 times in spam and once in normal messages: a stop word that happens to be informative in this corpus), and subtracts for “mañana”: total and , the cell’s value. Now lower . Frequent words barely change, but those with a zero in one class shoot up: with , “llama” (2 spam occurrences, 0 normal) rises from to , and the total from to . With small , two occurrences of one word are worth more than twelve of another, because the probability ratio matters and one is near zero. With the ratio is infinite: “gana”, “gratis” and “llama” are worth , “mañana” , and the sum is . Now write a message using words from just one class: with , a word unseen in spam suffices for , whatever the rest says.
The Bernoulli model changes the accounting. A repeated word counts once, and each vocabulary word absent from the message contributes . Each term is small, but there are 264: in the first example they sum to , 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 , and , with and independent given the class and : an exact copy. The optimal rule ignores because it adds no information, and chooses if . Naive Bayes treats as independent of and counts twice. Write and (with equal priors, ). The optimal rule chooses if , that is, if ; Naive Bayes chooses it if , that is, if
The two curves cross at , and , 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.
With , 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 ). Meanwhile, Naive Bayes probability moves to extremes: at the initial point, , the true probability of is and Naive Bayes gives ; with , . 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 the true probability of class and , the values Naive Bayes computes for and , Naive Bayes is locally optimal under 0–1 loss if and only if : 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 “ of ” concepts (true if at least of the 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 times.
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 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.
is, except for the constant common to all classes, : the usual joint log-likelihood. The middle term is minus half the squared Mahalanobis distance between 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 () and its prior.
LDA’s linear form follows from expanding the square: . Terms and are the same across classes and do not affect the argmax, so can be dropped. What remains is affine in .
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.
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 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, , but choose differently. LDA maximizes joint likelihood, factored as ; logistic regression maximizes only the second factor and leaves the distribution of unmodeled. If the Gaussian model is true, factor 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 and thus the boundary, even if those points are correctly classified. Logistic regression looks only at , and distant correctly classified points barely affect its gradient.
How many parameters, and what to do when there are too many
In dimensions, a covariance has free parameters. LDA estimates one; QDA, one per class; Gaussian Naive Bayes, only the variances of each class. On digits (, ) 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 points has rank at most , so if it is singular, does not exist, and QDA is undefined. Even with somewhat larger than , its small eigenvalues are severely underestimated (covariance estimation error in high dimensions) and 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, , and between LDA and scalar covariance, (ESL, section 4.3.1). With and equal priors, LDA becomes the nearest-centroid classifier in Euclidean distance.
- Ledoit–Wolf shrinkage (2004): with 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 : Mahalanobis distance is , computed with a triangular solve, and . There is never a need to invert a matrix.
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 , and the third line explains why: the scikit-learn version running in your browser estimates each class covariance with divisor (the unbiased covariance) rather than maximum likelihood’s , and their ratio is exactly . With around 200 points per class the difference is immaterial; with close to 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: features and only 30 examples per class, with a non-diagonal true covariance (eigenvalues between and in a random basis) and classes separated in the first five coordinates.
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 it falls to 37.1%, and automatic Ledoit–Wolf 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, , 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.
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, is dimension and the number of examples; here we translate them to and .
Asymptotics. Let and 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, : 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 (VC dimension of order ), with high probability : suffices to approach the asymptote, and in the worst case a number of order 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 estimates, with examples all are within of their population values with probability . 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 , where is the probability that population log odds fall within of zero on the correct side. If most features are relevant, those log odds grow as and is small, and their corollary concludes that suffices.
Logarithmic versus linear in dimension: the generative model approaches its asymptote sooner, even if that asymptote is worse. Hence the prediction: as 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 () and unregularized logistic regression: most show the crossover, and in the few where logistic regression does not catch Naive Bayes, datasets are small and does not grow enough. Zheng et al. (2023) extended the analysis to the multiclass case under other assumptions and found the same separation between and .
The interactive reproduces the situation with a model where everything is exactly calculable: two equally likely Gaussian classes with means , all variances 1, and the first half of the features equicorrelated with correlation . With conditional independence holds and both models are correctly specified; with , the first half of the features repeats the same information, like the copies of in Domingos and Pazzani’s example, and Naive Bayes counts it repeatedly. Since both classifiers are linear, their exact error under the model is and no test set is required.
The initial state, and , 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 to 0: the two asymptotes coincide and Naive Bayes no longer has anything to lose, so it leads (or ties) for every . Increase : the Naive Bayes asymptote rises and crossover comes earlier. Now return to , switch to scikit-learn’s default regularization, , and look at the first : logistic regression no longer loses with little data (at worst it ties). The reason is instructive. With a strong penalty and small , and the log-loss gradient at is , 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.
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 and , Naive Bayes leads weakly regularized logistic regression at all seven sizes (for example, versus with ) and both converge to Bayes error, ; here logistic regression with also trails Naive Bayes except at , where they tie ( versus ). With and , Bayes error is and the Naive Bayes asymptote : Naive Bayes reaches it around () and remains there, while logistic regression with , worse until (), surpasses it from ( versus ) and reaches with . Logistic regression with wins at all seven sizes, including ( versus ). 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 variancesvar_smoothingthe largest feature variance, so none is zero.MultinomialNB(alpha=1.0)for counts andBernoulliNB(alpha=1.0, binarize=0.0)for presence (binarizes input with thresholdbinarize).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.CategoricalNBfor 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=...).
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 in the quadratic term) and accuracy collapses to 10%. The default, , avoids division by zero but is not necessarily good: raising it to 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
float64, and they are all . The smallest representable positive value is the subnormal , and results below half of it round to 0. What is the minimum number of tokens needed for the product to be exactly 0?Step 1 of 4. By Bayes' theorem, the log odds are . Which density factors cancel in the ratio?
Step 1 of 3. What is the posterior of ?
multinomial_nb_fit(X, y, alpha), returning the tuple (clases, log_prior, log_theta) with log_theta shaped (additive smoothing), and predict_log_proba(modelo, X), returning with shape , 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))Summary
- Naive Bayes assumes conditional independence given class: parameters go from exponential to linear in 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 .
- Additive smoothing prevents an unseen word from eliminating a class, and is the posterior mean with prior and MAP with . 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, . QDA estimates covariance parameters and is singular if : in high dimensions it is shrunk (RDA, Ledoit–Wolf,
reg_param). - Ng and Jordan: the discriminative model has a better asymptote and needs order examples; the generative model approaches its own with order . The generative model wins with little data, the discriminative with much, and regularization brings them closer.