Class probabilities and logistic model fitting
A complete companion to the lecture, with the same chapter sequence, worked mathematics and interactive examples.
5.1 · A classification problemClassification means predicting a category
We use categories every day. Can a model learn to assign them? Start with a hospital task.
Input
Cholesterol measurement
Classifier
Learns from labelled patients
Predicted class
0 Absent
1 Present
Two classes make this a binary classification problem.
People commonly organize information into categories. Classification asks how a machine learning model can learn those categories from examples and assign a label to a new observation. An observed label may be represented by a word or by a numeric code. The code identifies a class; it does not measure an amount. We begin with a concrete hospital example, formalize the prediction task, and then introduce probabilistic models and classification algorithms. The example follows a hospital research task. For each patient we observe a numerical cholesterol-related predictor and a binary disease label. X denotes the input variable, while x is a particular measured value. Y is the outcome variable, with zero meaning absence of disease and one meaning presence. The set of possible labels is script Y={0,1}. This is a classification problem because we want a category, even though the predictor is numerical. The plot uses an illustrative input scale from approximately zero to one. These values should not be interpreted as a literal cholesterol percentage or a clinical threshold. The example introduces the modeling task, rather than claiming that a single measurement is sufficient for real diagnosis.
5.1 · A classification problemOur hospital data: two classes, 0 and 1
Each dot is one patient. Inspect a point, then compare the two classes and their sharp transition.
This teaching dataset contains one hundred observations: fifty-one have outcome zero and forty-nine have outcome one. The horizontal coordinate is an illustrative cholesterol-related input, and the vertical coordinate is the observed disease class. A point at y=1 indicates presence of disease, not a larger numerical amount of disease.
A point at y=0 indicates absence. Here the observations form two horizontal groups and change sharply from one class to the other as the input increases. Hover or select a point to inspect its input and label.
The numerical values are preserved. This is the same dataset used to motivate a probability model in the following section. The supplied test trace contains no observations, so the plot describes training cases rather than test performance.
Static preview. Open handout.html to use the interactive example.
5.1 · From the observations to a modelWhy not fit a line or polynomial?
Static preview. Open handout.html to use the interactive example.
Ordinary regression can leave the range [0,1], so its outputs are not automatically valid class probabilities.
The observations occupy two levels because the outcome is either zero or one. In this particular teaching sample, the transition between those levels is sharp. A familiar first attempt is to fit a regression line or polynomial to the numerical codes and then round or threshold its output. The purple line is an actual ordinary-least-squares fit to the same one hundred observations. It gives some predictions below zero and above one, so those values cannot be interpreted directly as probabilities. A higher-order polynomial can follow a steep pattern more closely, but it does not automatically enforce valid probabilities either. Regression on binary labels is possible; the point is that we want an explicit, interpretable model of the probabilities of the classes. We will therefore estimate P(Y=0|X=x) and P(Y=1|X=x), and subsequently turn those estimates into a label. This motivates the probabilistic framework introduced after the formal description of the classification task.
Select several polynomial degrees to overlay their fits on the same observations. A higher degree allows more bends and usually fits these training labels more closely, but it does not constrain predictions to [0,1]. The shaded regions mark values that cannot be class probabilities. The purpose is to motivate a probability model rather than to choose the best degree from training fit.
Lecture mapFrom a label to a probability model
| Chapter | Question we will answer |
|---|---|
| 5.1 · A classification problem | What changes when the target is a category? |
| 5.2 · Probabilistic interpretation of machine learning | Why predict probabilities rather than certainty? |
| 5.3 · Optimal Bayes classifier | Which decision minimizes the chance of an error? |
| 5.4–5.5 · Naive Bayes / Estimating distributions | How can we estimate class probabilities from data? |
| 5.6 · Logistic regression | Can we model a class probability directly? |
| 5.6.1 · Maximum likelihood estimation | Which logistic coefficients make the observed labels most likely? |
The lecture moves from the task to a probabilistic description, then to an ideal decision rule, and finally to practical models. This part concludes by fitting logistic regression with maximum likelihood. Each chapter answers the question raised by the preceding one.
5.1 · A classification problemRead a dataset: rows are patients, columns are features
| Patient i | Feature 1: cholesterol | Feature 2: age | Observed class |
|---|---|---|---|
| 1 | x₁₁ = 0.55 | x₁₂ = 50 | y₁ = 1 |
| 2 | x₂₁ = 0.20 | x₂₂ = 34 | y₂ = 0 |
𝒟 is the labelled dataset of n observations. The input xᵢ contains m features for case i. The observed target yᵢ is a class label, and f(xᵢ)=ŷᵢ is the predicted label. In the hospital task, 𝒴={0,1}, with 0 for absence of disease and 1 for presence.
The index i selects a data row, while j selects a feature column. Thus xᵢⱼ is the value of feature j for observation i. Cholesterol alone gives m=1. Cholesterol and age together give m=2. The two-row table illustrates these indices; the interactive dataset contains cholesterol alone.
The numeric class codes identify categories rather than amounts or distances. The table uses an illustrative cholesterol scale and is not a clinical dataset.
Email classes are coded billing = 0, delivery = 1 and technical = 2. A regression predicts 1.4. Which interpretation is best?
- Round 1.4 to delivery because the codes define numerical distances.
- The codes are arbitrary labels. Estimate class probabilities rather than assuming meaningful distances between codes.
- Technical cases are twice as severe as delivery cases.
- Changing the codes would turn the task into regression.
Show the reasoning
Answer B. Class codes name categories. A numeric distance between arbitrary codes has no intrinsic meaning, and recoding the same categories should not change the task.
5.2 · Probabilistic interpretation of machine learningFrom regression’s random error to class uncertainty
Regression: add a random error
Classification: give each label a probability
Each possible label receives a probability.
We describe the uncertainty through the probabilities of the possible classes.
An observation (xᵢ,yᵢ) is a random sample originating from the random variables X,Y. A random variable describes a quantity before we observe its value. A sample gives its recorded values for one case. X can represent a vector of predictors when we measure more than one feature.
Regression introduced a random error ε added to the prediction to describe the discrepancy with the target: yᵢ=f(xᵢ)+εᵢ. In the numerical example, a model value 5 and random deviation −1 give an observed response 4.
In classification, a numerical error added to a class code would not generally describe the uncertainty appropriately. We instead model the possible categorical outcomes and their probabilities. Random input and outcome variables provide a framework for uncertainty beyond additive numerical measurement errors. ε is not itself converted into a probability.
5.2 · Probabilistic interpretation of machine learningThe same recorded input can have different labels
| Case | Recorded cholesterol | Observed disease label |
|---|---|---|
| Patient i | xᵢ = 0.50 | yᵢ = 0 (absent) |
| Patient j | xⱼ = 0.50 | yⱼ = 1 (present) |
Probability describes what our available information leaves uncertain.
In predictors, uncertainty is related to the quality of the measurements. In outcomes it can also arise because relevant predictors were not collected. Consider xᵢ=xⱼ but yᵢ≠yⱼ: two cases have the same recorded inputs but different targets. This can result from an error in the target measurement or from the outcome not being fully explained by the collected inputs.
A die illustrates missing information. Predicting one throw exactly could require the characteristics of the die and surface, the throwing force, air resistance and other influences. We often do not have these measurements, so probabilities describe possible outcomes.
A category itself can also be uncertain. People can disagree about the colour of the same cloth. The probabilistic perspective therefore applies to categorical outcomes as well as numerical outcomes. The hospital rows are illustrative: they show how equal recorded cholesterol inputs can coexist with different labels, without specifying a clinical diagnosis rule.
5.2 · Probabilistic interpretation of machine learningTwo types of uncertainty
Epistemic:
Uncertainty in the measurements that can be controlled, to a certain extent.
Better tools or additional predictors can decrease epistemic uncertainty.
Aleatoric:
Uncertainty intrinsic in the process that cannot be controlled and therefore not decreased.
We can know these probabilities and still be uncertain about the next outcome.
Epistemic: uncertainty in the measurements that can be controlled, to a certain extent. In a predictor, we can adopt more accurate measurement tools. In an outcome, we can also include more predictors. Epistemic uncertainty can be decreased.
Aleatoric: uncertainty intrinsic in the process that cannot be controlled and therefore not decreased. The distinction is labile and depends on the context in which we conduct experiments. What can be controlled depends on the measurement setup and available inputs.
The left plot illustrates more precise measurements through a narrower spread of readings. The right plot describes a fair die within a fixed probabilistic model: each face has probability 1/6, and we are still uncertain about the next outcome.
5.2 · Probabilistic interpretation of machine learningSome data occur more often than others
Suppose we record people’s hair colour during data collection. In this varied illustrative sample, we observe more people with black hair than with red hair.
A probability model should reflect these different frequencies when we analyse the data.
During data collection, we may record a variable such as human hair colour. In a population where black hair is more common than red hair, a varied sample will generally contain more black-haired people. The example illustrates that possible values need not occur equally often.
Some data occur more often than others, and this is important to account for in our analyses. A probability model associates different probabilities with values that occur at different frequencies, rather than treating all possible outcomes as equally common.
The illustrative sample contains 20 people: 12 with black hair, five with brown hair and three with red hair. Dividing by 20 gives the relative frequencies 60%,25%,15%. These counts are invented for the example. They describe the sample and can estimate probabilities for the population it represents. The following section considers probabilities given an observed input.
5.2.1 · In classification problemsConditional probability: how likely is this label for this input?
Read: “The probability that the outcome is yᵢ, given input xᵢ.” Both expressions give that same probability.
Known input: condition on this value
Hypothetical patient input
Possible outcomes under that condition
Illustrative probabilities for this same input.
Because Y has discrete class labels, this function assigns a probability to each possible class.
For example, p(1 | 0.50) = 0.70. The event notation ℙ(Y=1 | X=0.50) gives the same probability.
A categorical outcome can be uncertain: observers can disagree about the colour of a cloth, or recorded predictors may not fully determine a disease label. A classification algorithm therefore often estimates the conditional probability of each class given the input.
Lowercase p names a conditional probability mass function (PMF): for a fixed input, it assigns a probability to each possible class of the discrete outcome Y. Here “mass” means probability assigned to a discrete class. The input X can itself be continuous.
The full function name is . Its value at class y and input x is:
ℙ is a probability operator applied to the stated event. The lowercase p is the name of the function whose value gives that probability. We shorten the full function notation to p(y | x) when the variables are clear. For any fixed input, the probabilities assigned to the possible classes sum to one.
For instance, p(1 | xᵢ)=0.70 means ℙ(Y=1 | X=xᵢ)=0.70. At this same input, p(0 | xᵢ)=0.30. These are hypothetical probabilities, not clinical estimates. They describe possible outcomes for the given input, and they add up to one.
Capital X and Y denote random variables. Lowercase xᵢ and yᵢ denote values recorded for case i. The class set 𝒴 is different from the outcome variable Y. In this hospital task, 𝒴={0,1}. Later, subscripts such as or identify which variables a distribution describes. Those subscripts identify the variables and conditioning of the probability function.
5.2.1 · Why use class probabilities?Why predict probabilities before choosing a class?
1. A smoother learning signal
Probabilities change continuously. Often, optimizing them is simpler than optimizing discrete class labels.
If the observed class is 1, 0.60 to 0.80 strengthens the prediction while its label stays 1.
2. A measure of model confidence
A confident prediction can still be wrong.
Estimating class probabilities offers two advantages. Often, optimizing a model over continuous probabilities is simpler than optimizing it over discrete class labels. A small change in the model can change a probability even when the most likely label stays the same.
The distribution also expresses the model’s confidence. A peaked distribution, such as (0.05,0.95), puts most probability on one class. A flat distribution, such as (0.50,0.50), gives little preference to either class. In a multiclass problem a flat distribution spreads probability approximately evenly among all classes. A confident prediction can still be wrong.
5.3 · Optimal Bayes classifierIf we knew the true probabilities, which label should we choose?
The Optimal Bayes Classifier (OBC) chooses the most probable class. It is a theoretical benchmark: in practice we usually have to estimate those probabilities.
Example: 70% present, 30% absent
Choose class 1.
It is the label with the higher chance of being right.
What does “optimal” mean here?
The lowest expected fraction of wrong labels, using these features and treating every mistake as equally costly.
The Optimal Bayes Classifier (OBC) assumes that we already know the true relationship ℙ(Y | X). Usually this relationship is unknown. The OBC is therefore a theoretical baseline standard, rather than a training procedure.
For two classes, the rule predicts 1 when ℙ(Y=1 | X=xᵢ)≥0.5, and predicts 0 otherwise. It chooses the label associated with the greater probability. At a tie both labels have the same error probability, and the displayed rule chooses 1. Optimality concerns the expected fraction of wrong labels, counting each mistake equally.
5.3 · More than two classesWith several classes, choose the one with greatest probability
| Candidate class c | 1 | 2 | 3 |
|---|---|---|---|
| True probability at this input | 0.10 | 0.70 | 0.20 |
argmax returns the winning class
The prediction is ŷᵢ = 2.
The largest probability is 0.70, but our output is the class label 2.
Why ŷᵢ can differ from yᵢ
Binary example: p(1 | xᵢ) = 0.4.
The OBC predicts 0, but the observed label can still be 1, with probability 0.4.
This 0/1 outcome is called a Bernoulli outcome.
For C classes, 𝒴={1,…,C}. The argmax chooses the class c with the greatest conditional probability. It returns a label, rather than the probability itself. In the table it returns class 2, whose probability is 0.70.
The hat on ŷᵢ marks a prediction. It can differ from the observed target yᵢ because the latter is a random sample. For example, if p(1 | xᵢ)=0.4 in a binary problem, the OBC predicts 0, but a sampled outcome can still be 1 with probability 0.4. A binary random outcome with probability p of being 1 and probability 1−p of being 0 is called a Bernoulli outcome.
5.3 · Measuring classification mistakesThe error rate is the probability that our label is wrong
Even the most likely class can be wrong. To compare classifiers, we average their mistakes over possible inputs and outcomes.
𝟙 is called an indicator function
The expectation averages those 0s and 1s
Toy population: 10 equally likely cases
0 = correct label1 = wrong label
We will show that the Bayes rule gives the smallest possible R(f) for these features.
Risk here means expected classification error under 0–1 loss. It is not an unspecified measure of harm. For each possible observation, the indicator contributes one if the prediction differs from the outcome and zero otherwise. The average of this zero-or-one variable is the probability of an error. The expectation averages with respect to the population distribution of both X and Y, so common observations receive greater weight than rare ones. Exact population risk is usually unknown. The fraction of wrong predictions in representative held-out observations estimates it. The following two sections first compare the two possible predictions at one fixed input and then prove that making the better choice at every input minimizes the population average.
The example uses a toy population of ten equally likely possible cases. Each contributes an indicator: one for an error, zero for a correct prediction. Three of the ten cases have an error, so the expectation of the indicator is 3/10=0.30. For a finite evaluation sample rather than the full population, the same average would estimate the unknown population risk.
5.3 · Why the optimal Bayes classifier worksWhich class gives the smaller chance of a mistake?
Reminder: the OBC chooses the class with the highest true probability. The individual case’s label is still unknown.
Return to two classes, {0,1}. Hold one input x fixed and compare the two possible predictions.
Here p(x) always means the probability of class 1. The class 1 is understood in this shorter notation.
Example at this input: suppose p(x) = 0.70.
If we predict 0
We make a mistake when the actual class is 1.
If we predict 1
We make a mistake when the actual class is 0.
Its chance of a mistake is 30%, the smaller of the two.
We return to a binary problem with class labels {0,1}. Fix one particular input x. We compare two decisions for that same input: predicting 0 and predicting 1.
On these proof slides, p(x) is shorthand for p(1 | x)=ℙ(Y=1 | X=x). The class 1 is already fixed in its definition, so it is left out of the arguments. The other class has probability 1−p(x), because the two possible class probabilities add up to one.
Suppose p(x)=0.70. Class 1 then has probability 70%, and class 0 has probability 30%. If we predict 0, we are wrong whenever the outcome is 1: a 70% chance of a mistake. If we predict 1, we are wrong whenever the outcome is 0: a 30% chance. We choose 1 because 30% is smaller than 70%. These are probabilities, so an individual prediction can still be wrong.
More generally, predicting 0 has error probability p(x), and predicting 1 has error probability 1−p(x). Choose the smaller of these two errors at each input. Minimizing the error separately at every input also minimizes their overall average, which the following section derives.
Lowercase x is a fixed input value, so p(x) is a number for that input. Uppercase X is a random input, so p(X) varies with whichever input occurs. Once X=x is observed, p(X) takes the value p(x). The next derivation uses p(X) while averaging over inputs. In both forms p still denotes the class-1 probability, rather than the input density introduced later.
The Optimal Bayes Classifier chooses the class with the greatest true conditional probability for the input. Its argmax rule returns a class label. It uses the true probability distribution as a theoretical benchmark, while the true label of an individual new observation remains unknown when making the prediction.
5.3 · Interactive derivationWhy does the Bayes rule minimize the error rate?
We prove the two-class case. Let .
Step 1. Start from the error rate
We want to measure how often the classifier gives a wrong label.
For each possible case, the indicator records 1 for a mistake and 0 for a correct prediction.
The expectation averages these results over the population. For example, R(f) = 0.30 means a 30% chance of a mistake.
Step 2. Average in two stages
We calculate the same average in two stages.
First fix an input X and average over the labels Y that can occur there. Then average those results over inputs, weighting them by how often they occur.
Fubini’s theorem allows this rewriting (a double integral can be calculated one variable at a time, and either order gives the same result). The overall error rate has not changed.
Step 3. Write the two possible mistakes
We now write out the two ways the classifier can make a mistake.
If it predicts 0, it is wrong when Y = 1, with probability p(X). If it predicts 1, it is wrong when Y = 0, with probability 1−p(X).
Exactly one indicator is 1. It selects the term for the label f actually predicts.
Example: if p(X) = 0.70 and f predicts 1, the first term is 0 and the second is 0.30.
Step 4. Choose the smaller error at each input
Fix one particular input x and compare the two possible decisions.
Predicting 0 has error probability p(x). Predicting 1 has error probability 1−p(x).
Choose the smaller of these two errors. Doing this at every input also makes their overall average as small as possible.
Step 5. Recover the Optimal Bayes Classifier
Choose class 1 when its error, 1−p(x), is no larger than the error of choosing class 0, p(x).
Adding p(x) to both sides gives 1 ≤ 2p(x), so p(x) ≥ 0.5. Otherwise choose class 0.
This is the Optimal Bayes Classifier: the best decision at each input gives the lowest overall expected error.
5.3 · Limits of predictionOptimal does not mean error-free
Without additional information, no decision rule can improve that expected error.
The OBC can make errors even when it knows the true probabilities. With p(x)=0.7, choosing class 1 has probability 0.3 of being wrong. Across 100 comparable cases that gives 30 mistakes on average. A particular collection need not contain exactly 30 mistakes. This picture illustrates the same error calculation as the proof.
For 100 comparable cases, the true class-1 probability is 0.7. With equal error costs, what does the optimal Bayes classifier achieve on average?
- No errors, because the true probabilities are known.
- About 70 errors, because class 1 occurs most often.
- About 30 errors; no rule using the same information has lower expected 0–1 error.
- Fewer errors by always choosing the less frequent class.
Show the reasoning
Answer C. Predicting class 1 has conditional error 1−0.7=0.3. Over 100 comparable cases this gives 30 expected errors, not necessarily exactly 30 in each sample.
5.3.1 · EvaluationAccuracy: what fraction of labels did we get right?
One indicator for each case
True labels: 0, 1, 1, 0
Predictions: 0, 1, 0, 0
Indicators: 1, 1, 0, 1
Average the correct predictions
Three of four predictions are correct: 75%.
0 means no correct predictions. 1 means all predictions are correct.
Accuracy evaluates how often the classifier returns the correct label on a dataset. The bold symbols 𝐗 and 𝐘 collect the evaluated inputs and their observed labels. For case i, 𝟙(yᵢ=ŷᵢ) is one if the prediction is correct and zero otherwise. The sum counts correct predictions. Dividing by the number n of evaluated cases gives their ratio, a value between zero and one.
In the example the indicators are 1,1,0,1. Their sum is three, so the accuracy is 3/4=0.75, or 75%. This is a dataset average. R(f) in the proof is instead the expected error over possible inputs and outcomes.
5.4 · Naive Bayes classifierNaive Bayes Classifier: using Bayes’ theorem
Weather example: the posterior is , the probability of rain given a cloudy sky.
Likelihood: (x | y)
How are these features distributed within class y?
How often is it cloudy when it rains?
Prior: (y)
How common is class y before seeing this input?
How common is rain before considering clouds?
Evidence: (x)
How common is this input overall?
It normalizes the posterior.
Cloudy days among all days, rainy or dry.
Naive Bayes uses Bayes’ theorem to estimate the posterior probability of a class given the observed input. The word equation and the symbolic equation express the same calculation: multiply likelihood by prior, then divide by evidence.
The subscript on p identifies the distribution. (y) describes the class variable Y. (x) describes the input X. (x | y) describes inputs within a fixed class, and (y | x) describes classes after the input is known. Because the class variable is discrete, (y | x)=ℙ(Y=y | X=x). The earlier shorthand p(y | x) means the same thing.
For a continuous input, and are probability densities. A density describes how probability is distributed over input values. Its value at one point is not the probability of observing that exact value. Bayes’ theorem still produces a class probability through the ratio. To use the rule, we must estimate the likelihood, prior and evidence, or show which terms can be omitted for class selection.
In the weather example, X records cloud condition and Y records rain status. The posterior is the probability of rain given that it is cloudy. The likelihood reverses the conditioning: probability of cloudy skies given rain. The prior is the overall probability of rain before considering the cloud condition. The evidence is the overall probability of cloudy skies, across rainy and dry cases.
5.4 · Naive Bayes classifierA common clue is not the same as a likely class
| 100 emails | Contain the word “offer” | Do not contain it |
|---|---|---|
| 10 spam | 8 | 2 |
| 90 ordinary | 18 | 72 |
Read down the clue column
26 emails contain “offer”.
Only 8 of those are spam.
The same calculation with Bayes
Likelihoods: read within each class
Priors: read the class totals
Evidence: “offer” occurs in 8 + 18 = 26 of all 100 emails, so .
That does not mean 80% of emails containing the clue are spam.
This small count example makes Bayes’ reversal concrete. Of 100 emails, ten are spam. Eight spam emails and eighteen ordinary emails contain “offer”, so there are 26 emails with the clue. The probability of spam given the clue is therefore 8/26, about 0.31.
The same result follows from likelihood×prior/evidence: the spam likelihood is 8/10=0.8, its prior is 10/100=0.1, and the evidence is 0.8×0.1+0.2×0.9=0.26. The 80% likelihood of the clue within spam is different from the 31% posterior probability of spam given the clue.
Every number in the Bayes expression is read from the table. Within spam, 8 of 10 emails contain “offer”, giving 0.8. Within ordinary mail, 18 of 90 contain it, giving 0.2. The class priors are 10/100=0.1 for spam and 90/100=0.9 for ordinary mail. The weighted terms 0.8×0.1 and 0.2×0.9 equal 8/100 and 18/100. Adding them gives the evidence 26/100=0.26. Dividing the spam-and-clue probability 0.08 by that evidence gives approximately 0.31.
Among 1,000 emails, 100 are spam. The word “offer” appears in 60 spam emails and 90 ordinary emails. What is P(spam | “offer”)?
- 60/(60 + 90) = 40%.
- 60/100 = 60%.
- 100/1,000 = 10%.
- 90/(60 + 90) = 60%.
Show the reasoning
Answer A. Conditioning on the word restricts attention to the 150 emails containing it. Of those, 60 are spam. The prior and the reverse conditional are different quantities.
5.5 · Estimating the distributionsThe “naive” assumption makes the likelihood simpler
Let . We leave out the observation index i to focus on one input.
Under this assumption, model each feature separately within class c, then multiply. These are easier, one-variable distributions.
Estimating the complete joint likelihood of many predictors can be difficult. For one observation write x=(x₁,…,xₘ), omitting the observation index i. The first line expands the vector x into its m feature values.
Naive Bayes assumes that the predictors are conditionally independent given the class. With class c fixed, this assumption lets us replace the joint likelihood by the product of the individual feature likelihoods. That is the second line, and it is the only line here that requires the independence assumption.
The third line writes exactly the same multiplication with ∏. The index j runs from 1 to m, giving one factor (xⱼ | c) for each feature. Xⱼ is the random variable for feature j. Each factor is a one-variable, or univariate, distribution and is easier to model. The equalities describe the Naive Bayes model. Real features can violate the assumption, as the question’s numerical example illustrates.
Within class 1, P(A)=0.8 and P(B)=0.5, but P(A and B)=0.5. Naive Bayes would use 0.8 × 0.5 = 0.4. What does this mismatch show?
- The features must be independent when all classes are pooled.
- The class priors must be equal.
- Conditional independence fails within this class, so multiplying the feature likelihoods misstates their joint evidence.
- Every label predicted by Naive Bayes must be wrong.
Show the reasoning
Answer C. Naive Bayes assumes feature independence given a class. Under independence the joint probability is the product, but here 0.5 differs from 0.4. This does not imply every classification decision fails.
5.5 · Estimating the distributionsEstimate the prior by counting the class examples
Count the class
n꜀ is the number of training observations with label c.
n is the total number of training observations.
Turn the count into a proportion
Example: 10 spam emails out of 100 emails.
Here (c) is estimated from the training data.
The prior (c) can be estimated as the ratio of training observations belonging to class c. Let n꜀ count those observations and n count the complete training dataset. The ratio n꜀/n estimates how common class c is before considering the current input.
For ten spam emails among one hundred emails, the estimated spam prior is 10/100=0.10. We keep the distribution notation (c) in the formulas, and state explicitly when it is estimated rather than known.
5.5 · Estimating the distributionsPrediction: choose the class with the largest posterior
First line: compare the classes
For this fixed input x, evaluate each candidate class c.
argmax returns the winning class label.
Second line: use Bayes’ theorem
Replace each posterior with likelihood × prior / evidence.
The input x stays fixed while c changes.
The next derivation shows why it does not affect which class wins.
Prediction uses the same rule as the OBC: choose the class with the greatest posterior probability for the observed input. In the first line, argmax compares the possible labels c in 𝒴 and returns a label. The second line substitutes the Bayes expression for each posterior.
The input x stays fixed throughout this comparison. The evidence (x) is therefore identical for every candidate class. We do not need to calculate it just to decide which class wins. The logarithmic derivation below shows the removal of this common term one step at a time. The model distributions here are estimated from data, rather than assumed to be the known true relationship.
5.5 · Estimating the distributionsWhy can we use log scores and omit the evidence?
01 · Start from the Bayes decision
For one fixed input x, compute a posterior score for every possible class c.
The numerator is likelihood × prior. The denominator is the evidence.
argmax returns the class label with the largest value, not that value itself.
02 · Apply a logarithm
For positive values, log is strictly increasing: if a > b, then log(a) > log(b).
It preserves the order of the class scores, so the winning class does not change.
We can therefore compare logarithms instead of the original ratios.
03 · Expand the logarithm
Use log(ab/d) = log(a) + log(b) − log(d).
Multiplication in the numerator becomes addition. Division by the evidence becomes subtraction.
Nothing has been dropped: this is exactly the preceding score, written as three terms.
04 · Remove the common evidence
For this fixed input x, the negative log evidence is the same number for every class c.
Removing the same number from all class scores cannot change their order.
We therefore need the likelihood and prior to select a class, but not the evidence.
05 · Use the feature factorization
Naive Bayes writes the likelihood as a product of one factor per feature.
The logarithm of a product is a sum: log(a₁⋯aₘ) = log(a₁) + ⋯ + log(aₘ).
Add the feature log likelihoods and the log prior, then choose the class with the largest total.
5.5.1 · Estimating the feature distributionsHow do we estimate each feature distribution?
We still need , the likelihood of the observed value of feature j within class y. To estimate it, group the training values by class first.
| Type of feature xⱼ | Method | Intuition |
|---|---|---|
| Quantitative | Parametric, such as a Gaussian | Choose a shape and estimate its parameters. |
| Quantitative | Nonparametric, such as kernel density estimation (KDE) | Estimate a smooth density from the observed values. |
| Categorical | Class-conditional proportions | Count how often each category occurs within each class. |
The remaining task is to estimate the individual distributions (xⱼ | y). Here y is a fixed class value, and j identifies a feature. The same role is denoted by c when comparing candidate classes.
For a quantitative feature, parametric estimation chooses a family such as a Gaussian and estimates its parameters from observations within each class. Nonparametric estimation, such as kernel density estimation, instead builds a smooth density from the observed feature values.
For a categorical feature, estimate the proportion of training observations with that category within each class. These choices complete the feature likelihoods needed in the preceding Naive Bayes rule.
Open the corresponding slide ↗5.5.1 · Estimating a feature likelihoodFrom labeled measurements to a Gaussian likelihood
We need , the density of feature value xj within a fixed class c. For a quantitative feature, one option is to assume a Gaussian shape and estimate its center and spread from labeled training data.
Group. Suppose feature is petal length. Here are two illustrative groups of labeled training measurements. Species 0 has lengths 2.5, 3.5, 4, 4.5, 5.5 cm. Species 1 has lengths 4.5, 5.5, 6, 6.5, 7.5 cm.
Fit. Average the lengths separately in each group to estimate μⱼ. This gives 4 cm and 6 cm, respectively. To fit the variance σⱼ², average the squared distances from each group’s own mean. For species 0 that gives (2.25 + 0.25 + 0 + 0.25 + 2.25) / 5 = 1 cm². Species 1 has the same spread here. The two fitted parameters define the Gaussian curve . The class is implicit in μⱼ and σⱼ², so re-estimate both for each species and each feature.
Evaluate. A new flower measures 5.6 cm. At that same horizontal coordinate on both curves, the fitted density is about 0.111 per cm for species 0 and 0.368 per cm for species 1. The heights measure how compatible this length is with each species. To obtain a class probability, combine the feature densities and the class prior, then normalize across classes as in the next example.
5.5.1 · Try Naive BayesNaive Bayes: classify one flower
One new flower has petal length x₁ and width x₂, measured in cm. Change its measurements and predict species 0 or 1.
The task is to predict the species of one new flower. Its two features are petal length x₁ and petal width x₂, both in centimetres. The class variable Y takes values in {0,1}. These are illustrative measurements and model assumptions, rather than a dataset of actual flowers.
This example uses prefilled Gaussian parameters for each feature within each species. For petal length, these match the values fitted in the previous example. Species 0 has mean length 4 cm and mean width 1 cm. Species 1 has mean length 6 cm and mean width 2 cm. The standard deviation is 1 cm for length and 0.5 cm for width in both species. In the plot labels, μ denotes a mean and σ denotes a standard deviation. Subscripts 0 and 1 identify the species. The blue curves describe species 0 and the orange curves describe species 1.
First choose the new flower’s length and width. The green dotted line in each plot marks that measurement. Read the height of each species’ Gaussian curve at that position. This gives the feature likelihood for that species. A curve height is a probability density, so it is not itself a class probability.
For each species c, compute its unnormalized score as P(Y=c) × p(length | c) × p(width | c). The prior slider controls P(Y=1), and P(Y=0) is one minus that value. Multiplying the two feature likelihoods uses the Naive Bayes assumption that length and width are independent within each species.
To obtain the posterior for species 1, divide its product score by the sum of both product scores. The remaining posterior belongs to species 0. Predict the species with the larger posterior. At the default measurements, length 5.6 cm and width 1.4 cm, equal priors give approximately 69.0% for species 1 and 31.0% for species 0.
The calculation selector also shows log scores. For each species, log(score) = log(prior) + log(length density) + log(width density). A larger log score identifies the same winning species because logarithms preserve order. The final posterior still normalizes the original product scores, rather than dividing the log scores. Displayed values are rounded, while the calculation uses full precision.
Here c is a candidate species, X is the pair of feature random variables (X₁,X₂), and x=(x₁,x₂) is the pair of measurements from the new flower. The subscript on each p identifies the variable and the conditioning. The posterior probabilities sum to one across the two species.
If the two unrounded class scores are equal, the example displays “Tie: 50% each” because neither species is more probable. With equal costs for mistakes, either prediction is equally valid. A classifier that must return one label can use a fixed tie-breaking rule, such as choosing species 1. Equal rounded numbers on screen do not always mean that the underlying scores are exactly equal.
In these two plots, μ₀ and μ₁ identify the mean of the feature being plotted for species 0 and species 1. In the preceding general Gaussian notation, μⱼ instead identifies feature j while the class is held fixed. The plain symbol σ here is a Gaussian standard deviation. The function σ(xᵢ) introduced in logistic regression is a different use of the same Greek letter: it returns a class probability.
Static preview. Open handout.html to use the interactive example.
5.6 · Logistic regressionCan we predict the class probability directly?
Naive Bayes
First model the feature values within each class.
Estimate how the features are distributed for each class c and how common that class is (its prior).
Then use Bayes’ theorem to compute the probability of class c for the observed input xᵢ:
This combines the feature likelihood, class prior and evidence.
Logistic regression
Model the probability of a class directly from the feature values.
For input xᵢ, calculate a weighted sum of its features: a linear score.
An S-shaped logistic function converts that score into a probability between 0 and 1:
The coefficients are learned from labelled examples. The following section gives the formula for σ(xᵢ).
Logistic regression is closely related to regression models, although it is most often used for classification. Here we consider binary classification. Instead of first estimating feature distributions within each class, we choose a formula directly for ℙ(Y=1 | X=xᵢ).
A familiar linear combination of the inputs can take any real value. The logistic function transforms this score into a value between zero and one, which can represent the probability of class 1.
In the Naive Bayes formula, describes the distribution of the input features within class c, while describes the probability of class c after the input xᵢ is known. Bayes’ theorem relates the two conditional distributions. Logistic regression chooses a parametric formula for the class probability directly. Here σ(xᵢ) includes both the linear score and its logistic transformation, as written in the following section.
5.6 · Logistic regressionLogistic regression turns a linear score into a probability
Inside: a familiar linear score
Set xᵢ₀=1 to include the intercept β₀.
Outside: the sigmoid
σ(xᵢ) is the model’s class-1 probability.
The exponential keeps it between 0 and 1.
The class-0 probability is 1−σ(xᵢ).
The formula models the probability of class 1 for observation i. The notation σ(xᵢ) names the logistic function applied using that observation’s predictors and the coefficients β. The learnable parameters are β₀,…,βₘ, and the inputs are xᵢ₁,…,xᵢₘ. Setting xᵢ₀=1 includes the intercept β₀ in the sum from j=0.
The expression inside the exponential is the familiar linear combination ∑ⱼ₌₀ᵐ βⱼxᵢⱼ. The first fraction applies the sigmoid transformation 1/(1+e⁻ᶻ) to that score. To get the second fraction, multiply both numerator and denominator by eᶻ, where z is this sum. The numerator becomes eᶻ, and the denominator becomes eᶻ+1. This is an algebraic rewriting of the same probability.
The logistic function is also called the sigmoid because its graph has an S shape. It maps any real score to a probability in (0,1), approaching 0 and 1 at the extremes. This lies within the stated probability range [0,1]. The class-0 probability is 1−σ(xᵢ).
The error term is not explicit as an added ε. Uncertainty is intrinsic: at a given input, either class can occur according to these probabilities. The coefficients keep the form of the linear regression score, but they appear inside an exponential. The probability model is therefore not linear in its parameters. Section 5.6.1 shows how to fit these parameters by maximum likelihood.
This binary model can be extended to multiclass problems, but that extension is not covered here.
5.6 · Read the sigmoidThe score tells us which side of 50% we are on
Negative: class 1 probability below 0.5.
Zero: probability 0.5.
Positive: class 1 probability above 0.5.
The score is linear in β. The probability is nonlinear because β is inside the exponential.
No ε is added to a label. The class probabilities describe the uncertainty.
To read the sigmoid plot, call the linear sum z. The horizontal coordinate is this score, not necessarily one raw feature. The vertical coordinate is σ(xᵢ), the probability produced from the score for an observation.
At z=0 the formula gives 1/(1+1)=0.5. Negative scores give probabilities below one half. Positive scores give probabilities above one half. The S shape approaches the two probability limits without crossing them.
5.6 · Logistic regressionFrom a logistic probability to a class label
Probability first
Example: σ(xᵢ)=0.70.
The model assigns 70% to class 1 and 30% to class 0.
Then choose the more probable class
Since 0.70≥0.5, predict ŷᵢ=1.
If σ(xᵢ)=0.30 instead, predict ŷᵢ=0.
The prediction ŷᵢ is a class label, either 0 or 1.
Once the model gives a probability, apply the binary decision rule. Predict 1 when σ(xᵢ)≥0.5 and predict 0 otherwise. The output is now a class label. The rule selects the class with the greater modelled probability, just as the OBC does with true probabilities.
For σ(xᵢ)=0.70 the model gives 70% to class 1 and 30% to class 0, so ŷᵢ=1. For σ(xᵢ)=0.30, ŷᵢ=0. At exactly 0.5 the stated convention chooses 1. A prediction need not match the observed outcome because the outcome is uncertain.
5.6 · Try logistic predictionsTry the sigmoid: change the score, then read the label
Move the midpoint and slope to change the curve. Compare the class-1 probability with the fixed 0.5 cutoff and read the resulting accuracy.
This example uses the same 100 teaching observations as the opening. The controls set a one-feature linear score z=slope×(x−midpoint). Expanding it gives β₁=slope and β₀=−slope×midpoint. These are illustrative coefficient choices, not fitted estimates.
The S-shaped curve gives the modelled probability of class 1. The fixed horizontal line marks probability 0.5. Inputs whose curve value is at or above that line receive class 1, and the others receive class 0. Accuracy is the number of correct labels divided by 100.
Changing the midpoint moves the curve sideways. Changing the slope changes its steepness and can reverse which side favours class 1. With slope zero the probability is 0.5 for every input, and the displayed rule chooses class 1 throughout. The following section fits the coefficients by maximum likelihood.
Static preview. Open handout.html to use the interactive example.
5.6.1 · Maximum likelihood estimationA good probability model makes the observed labels plausible
Why multiply? We want the probability of both recorded labels occurring together. Given the inputs, the model treats the two patients’ labels as independent, so it multiplies the probability it assigns to each recorded label.
| Two fixed labels: y₁ = 1, y₂ = 0 | Model A | Model B |
|---|---|---|
| Model’s class-1 probabilities | (0.9, 0.9) | (0.6, 0.4) |
| Patient 1 has label 1: use σ(x₁) | 0.9 | 0.6 |
| Patient 2 has label 0: use 1−σ(x₂) | 1−0.9 = 0.1 | 1−0.4 = 0.6 |
| Joint likelihood: σ(x₁) × (1 − σ(x₂)) | 0.9 × 0.1 = 0.09 | 0.6 × 0.6 = 0.36 |
Model A gives only 0.10 to patient 2’s recorded label.
Hold both inputs fixed. For patient 1, the recorded label is 1, so the model assigns it probability σ(x₁). For patient 2, the recorded label is 0, so its probability is 1 − σ(x₂). The model assumes the two labels are independent given their inputs. The probability of observing both labels in that order is therefore σ(x₁) × (1 − σ(x₂)). We call this product the likelihood for the candidate model.
For model A the product is 0.9×0.1=0.09. For model B it is 0.6×0.6=0.36. Model B assigns four times as much likelihood to the observed pair, even though model A is more confident about its second, incorrect label. This is a concrete example of the two-product MLE formula.
Two labels are (1, 0). Model A predicts class-1 probabilities (0.9, 0.9); model B predicts (0.6, 0.4). Assuming independent outcomes, which has greater likelihood for the observed labels?
- A, because its two probabilities are larger.
- B: its likelihood is 0.36, four times A’s likelihood of 0.09.
- They tie because each predicts one positive probability above 0.5.
- A: its likelihood is 0.81, versus 0.24 for B.
Show the reasoning
Answer B. For y=1 use p, and for y=0 use 1−p. Thus A gives 0.9×0.1=0.09 and B gives 0.6×0.6=0.36. A high class-1 probability is unfavorable for an observed zero.
5.6.1 · Maximum likelihood estimationChoose coefficients that make the observed labels likely
If the recorded label is 1
This is the probability assigned to what actually happened.
Example: σ(xᵢ)=0.8 gives a factor of 0.8. Increasing it toward 1 makes the observed label more likely.
If the recorded label is 0
Use the probability of class 0, because that is what happened.
Example: σ(xᵢ′)=0.2 gives 1−0.2=0.8. Moving σ(xᵢ′) toward 0 increases this factor.
Maximum Likelihood Estimation (MLE) chooses the coefficients with the largest joint likelihood. argmax returns those coefficients, rather than the product value.
= m feature coefficients + 1 intercept∏ = multiply all indicated observationsi,i′ = observation indices, yᵢ,yᵢ′ = their observed labelsσ(x) = class-1 probability for candidate 𝛃
Maximum Likelihood Estimation (MLE) chooses coefficients that maximize the likelihood of the observed data. Inputs and labels stay fixed while we compare candidate coefficient vectors 𝛃=(β₀,…,βₘ). The vector belongs to ℝᵐ⁺¹ because it contains m feature coefficients and an intercept.
For each observation with yᵢ=1, the probability assigned to the observed label is σ(xᵢ). For each observation with yᵢ′=0, that probability is 1−σ(xᵢ′). The two products include the two label groups, with i and i′ serving as observation indices. Assuming independent observations under the model, multiply all their contributions.
The factors depend on 𝛃 through the logistic function. Maximizing the product encourages σ(xᵢ) toward 1 for positive labels and toward 0 for negative labels. We write argmax because the output is a vector of coefficients, not the maximum likelihood value itself.
5.6.1 · Maximum likelihood estimationHow do we find those coefficients?
1. Try coefficients
Start with a candidate 𝛃.
Use the logistic formula to compute σ(xᵢ) for every training input.
2. Calculate the likelihood
For each label 1 use σ(xᵢ).
For each label 0 use 1−σ(xᵢ).
Multiply those contributions.
3. Improve the candidate
A numerical optimizer adjusts the coefficients to seek a larger likelihood.
Repeat until its stopping criterion is met.
We use numerical optimization: improve candidate coefficients through calculations.
The likelihood objective tells us which coefficients we want, but it does not provide a closed-form solution. Unlike the ordinary least-squares formula seen in regression, logistic regression generally requires numerical optimization.
Conceptually, try a coefficient vector, compute the class probabilities and their likelihood, then adjust the vector to seek a larger likelihood. A numerical routine repeats calculations until its stopping rule is met. This description explains the role of the optimizer without introducing a separate optimization algorithm.
After fitting, the model still has the same S-shaped logistic probability form. The following graph illustrates that form against the observed binary labels.
5.6.1 · Maximum likelihood estimationTry coefficients and read the likelihood
The inputs and labels stay fixed. Select a patient, read the probability assigned to their observed label, then see how all 100 contributions combine.
This example uses the same 100 hospital teaching observations as Part 1. Each input xᵢ is a cholesterol-related measurement on an illustrative scale. The recorded label yᵢ is 0 for disease absent and 1 for disease present. Neither the measurements nor the labels change when the coefficients change.
The controls try candidate intercepts β₀ and slopes β₁. For a selected patient i, calculate the score β₀+β₁xᵢ and pass it through the logistic formula to obtain σ(xᵢ). This is the model’s probability of class 1, not the patient’s recorded label.
The contribution to likelihood depends on the label that was actually recorded. If yᵢ=1, use σ(xᵢ). If yᵢ=0, use 1−σ(xᵢ). Multiplying these contributions across all 100 independent observations gives the likelihood of the observed labels under those candidate coefficients.
The default candidate is β₀=−7.5 and β₁=15.5. The first recorded input is approximately 0.5488 and has label 1. Its score is about 1.0066 and its class-1 probability about 0.7324, so this observation contributes about 0.7324 to the product. Other patients supply the remaining factors. Displayed numbers are rounded, while the calculation uses full precision.
Choose a flat, reversed or steeper candidate, or adjust the coefficients yourself. A numerical fitting routine would seek coefficients with a larger joint likelihood. This explorer makes the objective visible and lets you compare candidates manually. It does not claim to run a fitting algorithm or to have found a finite maximizer.
Static preview. Open handout.html to use the interactive example.
Before you leaveFrom observed categories to probability-based predictions
Explain without symbols
Choose a worked example and describe what each step achieves.
Connect the symbols
Name every quantity in the corresponding formula, then explain why the formula does that job.
Then explain how Naive Bayes and logistic regression obtain class probabilities and how maximum likelihood fits the logistic coefficients.
The thread of this part is: define a categorical prediction task, describe uncertainty using class probabilities, choose the label with smallest expected error, estimate distributions with Naive Bayes, and model a binary class probability with logistic regression.
Use the numerical examples to explain the meaning of every formula. Distinguish the outcome Y, an observed value yᵢ and a prediction ŷᵢ. Explain each Bayes derivation step and the role of conditional independence. Part 2 introduces nearest-neighbor models.
Further readingFurther reading on classification and probability
- An Introduction to Statistical Learning · Classification
- Pattern Recognition and Machine Learning · Probability and classification
The textbooks listed here provide further background on classification and probability models. The lecture definitions, formulas and examples are explained in this handout.
Notation at a glance
| Symbol | Meaning |
|---|---|
| 𝒟, n, m | Dataset, number of observations, number of input features. |
| i, j, c, C | Observation index, feature index, candidate class, number of classes. |
| X, Y, 𝒴 | Random input, random outcome, set of possible class labels. |
| xᵢ, yᵢ, ŷᵢ | Recorded input, observed label, predicted label for case i. |
| ℙ(Y=y | X=x), p(y | x) | ℙ evaluates an event. Lowercase p names the conditional probability mass function of the discrete class Y given X. Its value p(y | x) is the same conditional class probability. |
| , , , | Posterior, likelihood, prior and evidence. Subscripts identify the variables and conditioning. |
| p(X), p(x) in the Bayes proof | The shorthand ℙ(Y=1 | X) or ℙ(Y=1 | X=x). It is not (x), the input distribution. |
| f, R(f), 𝔼ₓᵧ, 𝟙(A) | Classifier, expected error rate, average over inputs and outcomes, indicator equal to 1 when A is true and 0 otherwise. |
| 𝐗, 𝐘, Acc(𝐗,𝐘) | Evaluated input dataset, observed labels and fraction of correct predictions. |
| n꜀ | Number of training observations belonging to class c. |
| μⱼ, σⱼ, σ²ⱼ, 𝒩 | Gaussian mean, standard deviation and variance of feature j within the class held fixed, and the normal distribution. In the flower plots, subscripts 0 and 1 instead identify species for the feature being plotted. |
| β₀, βⱼ, xᵢ₀=1 | Intercept, coefficient of feature j, and the constant input that includes the intercept in the sum. |
| σ(xᵢ), z, e | Logistic class-1 probability, the linear score used to read the sigmoid plot, exponential base about 2.718. |
| ∏, ∑, log, argmax | Multiply indexed terms, sum indexed terms, natural logarithm, return the maximizing class. |