AIML · Lecture 11 · Classification · Part 1Course homeOpen slide deck  
AIML · Lecture 11 · Classification · Part 1

Class probabilities and logistic model fitting

A complete companion to the lecture, with the same chapter sequence, worked mathematics and interactive examples.

Read each explanation before exploring its controls. A hat on y marks a predicted label. A hat on β marks fitted coefficients. Open the slides

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

x

Cholesterol measurement

Classifier

f

Learns from labelled patients

Predicted class

y^∈𝒴={0,1}

0 Absent
1 Present

A numerical input can have a categorical outcome.
Two classes make this a binary classification problem.
x = observed inputf = classifierŷ = predicted label𝒴 = set of possible classes

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.

Open the corresponding slide ↗

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.

Interactive example · Our hospital data: two classes, 0 and 1
Patient cholesterol inputs and binary disease outcomes
The same controls and observations as the slide. Use Larger view for more room. Printing uses the initial-state preview.
Open the corresponding slide ↗

5.1 · From the observations to a modelWhy not fit a line or polynomial?

Interactive example · Compare polynomial degrees
Initial state: the fitted regression line can leave the probability range
The same controls and observations as the slide. Use Larger view for more room. Printing uses the initial-state preview.
Fit the same 100 patients with different polynomial degrees.
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.

Open the corresponding slide ↗

Lecture mapFrom a label to a probability model

ChapterQuestion we will answer
5.1 · A classification problemWhat changes when the target is a category?
5.2 · Probabilistic interpretation of machine learningWhy predict probabilities rather than certainty?
5.3 · Optimal Bayes classifierWhich decision minimizes the chance of an error?
5.4–5.5 · Naive Bayes / Estimating distributionsHow can we estimate class probabilities from data?
5.6 · Logistic regressionCan we model a class probability directly?
5.6.1 · Maximum likelihood estimationWhich 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.

Open the corresponding slide ↗

5.1 · A classification problemRead a dataset: rows are patients, columns are features

𝒟={(xi,yi)}i=1n,yi∈𝒴={0,1}
Patient iFeature 1: cholesterolFeature 2: ageObserved class
1x₁₁ = 0.55x₁₂ = 50y₁ = 1
2x₂₁ = 0.20x₂₂ = 34y₂ = 0
xi=(xi1,…,xij,…,xim),j=1,…,my^i=f(xi)
𝒟 = dataset, with n observationsi = row (patient), from 1 to nj = feature column, from 1 to mm = number of input featuresxᵢⱼ = feature j for patient iyᵢ = observed label, ŷᵢ = predicted labelxᵢ = input vector for patient if = classifier𝒴 = {0,1}, the set of class labelsCholesterol alone gives m = 1. Using cholesterol and age as inputs gives m = 2.The table is illustrative. Cholesterol uses the teaching scale, not clinical units.

𝒟 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.

Check your understanding · L05-C01

Email classes are coded billing = 0, delivery = 1 and technical = 2. A regression predicts 1.4. Which interpretation is best?

  1. Round 1.4 to delivery because the codes define numerical distances.
  2. The codes are arbitrary labels. Estimate class probabilities rather than assuming meaningful distances between codes.
  3. Technical cases are twice as severe as delivery cases.
  4. 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.

Open the corresponding slide ↗

5.2 · Probabilistic interpretation of machine learningFrom regression’s random error to class uncertainty

Before observing(X,Y)(xi,yi)One recorded sample

Regression: add a random error

f(xi)+ϵi=yi
Model value5
+
Random error−1
=
Observation4

Classification: give each label a probability

Each possible label receives a probability.

0: 30%1: 70%
We do not add a numerical ε to a class label.
We describe the uncertainty through the probabilities of the possible classes.
X,Y = random input and outcomexᵢ,yᵢ = values recorded for case if(xᵢ) = regression relationshipεᵢ = random deviation from f(xᵢ)0,1 = the two possible class labelsThe two descriptions model uncertainty. εᵢ is not itself a class probability.

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.

Open the corresponding slide ↗

5.2 · Probabilistic interpretation of machine learningThe same recorded input can have different labels

CaseRecorded cholesterolObserved disease label
Patient ixᵢ = 0.50yᵢ = 0 (absent)
Patient jxⱼ = 0.50yⱼ = 1 (present)
xi=xjbutyi≠yj
Missing informationAge, history, measurement noise
Ambiguous labelsThe same cloth: “blue” or “green”?
Think of a die: without the details of the throw and surface, we use probabilities.
Probability describes what our available information leaves uncertain.
i,j = two different casesxᵢ,xⱼ = recorded inputsyᵢ,yⱼ = observed labels

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.

Open the corresponding slide ↗

5.2 · Probabilistic interpretation of machine learningTwo types of uncertainty

Epistemic:

Uncertainty in the measurements that can be controlled, to a certain extent.

Better measurement precision reduces uncertaintyLess precise toolMore precise toolReference value
More precise tools give a narrower spread of readings.

Better tools or additional predictors can decrease epistemic uncertainty.

Aleatoric:

Uncertainty intrinsic in the process that cannot be controlled and therefore not decreased.

Fair die: six equally likely outcomes123456
Fair-die model: each outcome has probability 1/6.

We can know these probabilities and still be uncertain about the next outcome.

The distinction depends on the context and on what we measure.

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.

Open the corresponding slide ↗

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.

Illustrative hair-colour frequencies in a sample of twenty peopleBlack12/20 = 60%Brown5/20 = 25%Red3/20 = 15%
Some values occur more often than others.
A probability model should reflect these different frequencies when we analyse the data.
Illustrative sample of 20 peopleRelative frequency = count / sample sizeThe three relative frequencies sum to 100%.

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.

Open the corresponding slide ↗

5.2.1 · In classification problemsConditional probability: how likely is this label for this input?

ℙ(Y=yi∣X=xi)=p(yi∣xi)

Read: “The probability that the outcome is yᵢ, given input xᵢ.” Both expressions give that same probability.

Known input: condition on this value

X=xi=0.50

Hypothetical patient input

Possible outcomes under that condition

0: 30%1: 70%
p(0∣xi)=0.30,p(1∣xi)=0.70

Illustrative probabilities for this same input.

Lowercase p names the conditional probability mass function (PMF) of Y given X.
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.
ℙ = probability operator, applied to an eventp(yᵢ | xᵢ) = the PMF evaluated at these valuesX,Y = random input and outcomexᵢ,yᵢ = recorded values for case i𝒴 = {0,1}, the class setPMF values sum to 1 at each input.

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 pY∣X. Its value at class y and input x is:

pY∣X(y∣x)=ℙ(Y=y∣X=x)=p(y∣x)

ℙ 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 pY or pX∣Y identify which variables a distribution describes. Those subscripts identify the variables and conditioning of the probability function.

Open the corresponding slide ↗

5.2.1 · Why use class probabilities?Why predict probabilities before choosing a class?

1. A smoother learning signal

0.60 ⟶ 0.80

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

Model confidence: concentrated and evenly spread probabilitiesConfident predictionClass 0: 5% Class 1: 95%Uncertain prediction
Second bar: class 0 = 50%, class 1 = 50%.
Concentrated probabilities express more confidence. Similar probabilities express less.
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.

Open the corresponding slide ↗

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.

y^i=f(xi)={1if ℙ(Y=1∣X=xi)≥0.50otherwise

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.

𝒴 = {0,1}, the class setxᵢ = input for observation iŷᵢ = predicted labelf = Optimal Bayes ClassifierAt exactly 50%, either label has the same expected error. This rule chooses 1.

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.

Open the corresponding slide ↗

5.3 · More than two classesWith several classes, choose the one with greatest probability

𝒴={1,…,C},y^i=argmaxc∈𝒴ℙ(Y=c∣X=xi)
Candidate class c123
True probability at this input0.100.700.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.

Y = random class variable, taking one label from 𝒴𝒴 = {1,…,C}, the set of all possible class labelsC = number of classesc = a candidate label from 𝒴i = observation indexThe numbers 1,…,C are category codes. They do not describe distances or severity.

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.

Open the corresponding slide ↗

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.

R(f)=𝔼XY[𝟙(Y≠f(X))]

𝟙 is called an indicator function

𝟙(Y≠f(X))={1wrong label0correct label

The expectation averages those 0s and 1s

Toy population: 10 equally likely cases

R(f)=3 wrong10 cases=0.30

0 = correct label1 = wrong label

R(f) is called risk or expected classification error. It lies between 0 and 1.
We will show that the Bayes rule gives the smallest possible R(f) for these features.
f = any classifierf(X) = predicted labelY = outcomeX = input𝟙(…) = 1 when the condition is true, otherwise 0𝔼ₓᵧ = average over X and Y

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.

Open the corresponding slide ↗

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.

p(x)=p(1∣x)=ℙ(Y=1∣X=x)

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.

Error probability=p(x)=0.70

If we predict 1

We make a mistake when the actual class is 0.

Error probability=1−p(x)=0.30
The OBC therefore predicts class 1 here.
Its chance of a mistake is 30%, the smaller of the two.
y^=argmaxc∈𝒴 ℙ(Y=c∣X=x)
X = random input, x = one fixed input valueY = actual class, 𝒴 = {0,1} = possible class labelsŷ = predicted label, c = candidate class from 𝒴p(X) = the same class-1 probability function evaluated at the random input X

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 pX(x) 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.

Open the corresponding slide ↗

5.3 · Interactive derivationWhy does the Bayes rule minimize the error rate?

We prove the two-class case. Let p(X)=ℙ(Y=1∣X).

p(X) = probability that Y = 1 given Xf = the classifier being chosenR(f) = expected classification error𝔼 = average over the indicated variables𝔼ᵧ|ₓ = average over labels with input fixed𝟙(A) = 1 if A is true, otherwise 0X,Y = random input and outcomex = one particular input value

Step 1. Start from the error rate

R(f)=𝔼XY[𝟙(Y≠f(X))]

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

=𝔼X[𝔼Y∣X[𝟙(Y≠f(X))]]

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

=𝔼X[p(X)𝟙(f(X)=0)+(1−p(X))𝟙(f(X)=1)]

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

p(x)𝟙(f(x)=0)+(1−p(x))𝟙(f(x)=1)

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

f(x)={1if 1−p(x)≤p(x)0otherwise={1if p(x)≥0.50otherwise

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.

Open the corresponding slide ↗

5.3 · Limits of predictionOptimal does not mean error-free

Expected class proportions among 100 comparable cases100 comparable cases at the same observed inputClass 1: 70 expectedClass 0: 30 expected
For 100 comparable cases with p(x) = 0.7, always predicting 1 gives about 30 mistakes on average.
Without additional information, no decision rule can improve that expected error.
p(x) = ℙ(Y=1 | X=x)The 100 cases illustrate expected proportions, not an exact guarantee.

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.

Check your understanding · L05-C02

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?

  1. No errors, because the true probabilities are known.
  2. About 70 errors, because class 1 occurs most often.
  3. About 30 errors; no rule using the same information has lower expected 0–1 error.
  4. 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.

Open the corresponding slide ↗

5.3.1 · EvaluationAccuracy: what fraction of labels did we get right?

Acc(𝐗,𝐘)=1n∑i=1n𝟙(yi=y^i)

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

Acc=1+1+0+14=0.75

Three of four predictions are correct: 75%.

Accuracy lies in [0,1].
0 means no correct predictions. 1 means all predictions are correct.
𝐗,𝐘 = evaluated inputs and observed labelsn = number of evaluated casesyᵢ = observed label, ŷᵢ = predicted label𝟙(A) = 1 if A is true, otherwise 0

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.

Open the corresponding slide ↗

5.4 · Naive Bayes classifierNaive Bayes Classifier: using Bayes’ theorem

Weather example: the posterior is ℙ(rain∣cloudy), the probability of rain given a cloudy sky.

posterior=likelihood×priorevidence
pY∣X(y∣x)=pX∣Y(x∣y)pY(y)pX(x)

Likelihood: pX∣Y(x | y)

How are these features distributed within class y?

ℙ(cloudy∣rain)

How often is it cloudy when it rains?

Prior: pY(y)

How common is class y before seeing this input?

ℙ(rain)

How common is rain before considering clouds?

Evidence: pX(x)

How common is this input overall?
It normalizes the posterior.

ℙ(cloudy)

Cloudy days among all days, rainy or dry.

pY∣X(y | x) = posterior class probabilityX = input (cloud condition), Y = class (rain status)Example values: x = cloudy, y = rainSubscripts say which variables the distribution describes.Because Y is discrete: pY∣X(y | x) = ℙ(Y=y | X=x).For continuous X, pX and pX∣Y are densities.

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. pY(y) describes the class variable Y. pX(x) describes the input X. pX∣Y(x | y) describes inputs within a fixed class, and pY∣X(y | x) describes classes after the input is known. Because the class variable is discrete, pY∣X(y | x)=ℙ(Y=y | X=x). The earlier shorthand p(y | x) means the same thing.

For a continuous input, pX and pX∣Y 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.

Open the corresponding slide ↗

5.4 · Naive Bayes classifierA common clue is not the same as a likely class

100 emailsContain the word “offer”Do not contain it
10 spam82
90 ordinary1872

Read down the clue column

26 emails contain “offer”.
Only 8 of those are spam.

ℙ(spam∣offer)=826≈0.31

The same calculation with Bayes

Likelihoods: read within each class

ℙ(offer∣spam)=8/10=0.8
ℙ(offer∣ordinary)=18/90=0.2

Priors: read the class totals

ℙ(spam)=10/100=0.1
ℙ(ordinary)=90/100=0.9

Evidence: “offer” occurs in 8 + 18 = 26 of all 100 emails, so ℙ(offer)=26/100=0.26.

0.8×0.10.8×0.1+0.2×0.9=0.080.26≈0.31
80% of spam contains the clue.
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.

Check your understanding · L05-C03

Among 1,000 emails, 100 are spam. The word “offer” appears in 60 spam emails and 90 ordinary emails. What is P(spam | “offer”)?

  1. 60/(60 + 90) = 40%.
  2. 60/100 = 60%.
  3. 100/1,000 = 10%.
  4. 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.

Open the corresponding slide ↗

5.5 · Estimating the distributionsThe “naive” assumption makes the likelihood simpler

Let x=(x1,…,xm). We leave out the observation index i to focus on one input.

pX∣Y(x∣c)=pX∣Y(x1,…,xm∣c)=pX1∣Y(x1∣c)⋯pXm∣Y(xm∣c)=∏j=1mpXj∣Y(xj∣c)
Assume the predictors are conditionally independent given the class.
Under this assumption, model each feature separately within class c, then multiply. These are easier, one-variable distributions.
Xⱼ = random variable for feature jxⱼ = its value in this inputm = number of featuresj = feature index, from 1 to mc ∈ 𝒴 = a candidate class∏ = multiply one term per feature

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 pXj∣Y(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.

Check your understanding · L05-C04

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?

  1. The features must be independent when all classes are pooled.
  2. The class priors must be equal.
  3. Conditional independence fails within this class, so multiplying the feature likelihoods misstates their joint evidence.
  4. 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.

Open the corresponding slide ↗

5.5 · Estimating the distributionsEstimate the prior by counting the class examples

pY(c)=ncn

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.

pY(spam)=10100=0.10
The prior describes how common a class is before we use this particular input.
Here pY(c) is estimated from the training data.
Y = random class variablec ∈ 𝒴 = the class being countedn꜀ = number of class-c training casesn = total training cases

The prior pY(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 pY(c) in the formulas, and state explicitly when it is estimated rather than known.

Open the corresponding slide ↗

5.5 · Estimating the distributionsPrediction: choose the class with the largest posterior

y^=argmaxc∈𝒴 pY∣X(c∣x)=argmaxc∈𝒴 pX∣Y(x∣c)pY(c)pX(x)

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.

Do we have to calculate the evidence pX(x)?
The next derivation shows why it does not affect which class wins.
ŷ = predicted classc ∈ 𝒴 = candidate class in the class setx = the input being classifiedpY∣X, pX∣Y, pY, pX = posterior, likelihood, prior, evidence

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 pX(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.

Open the corresponding slide ↗

5.5 · Estimating the distributionsWhy can we use log scores and omit the evidence?

01 · Start from the Bayes decision

y^=argmaxc∈𝒴 pX∣Y(x∣c)pY(c)pX(x)

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

y^=argmaxc∈𝒴 log(pX∣Y(x∣c)pY(c)pX(x))

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

y^=argmaxc∈𝒴 [log(pX∣Y(x∣c))+log(pY(c))−log(pX(x))]

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

y^=argmaxc∈𝒴 [log(pX∣Y(x∣c))+log(pY(c))]

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

y^=argmaxc∈𝒴 [∑j=1mlog(pXj∣Y(xj∣c))+log(pY(c))]

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.

log = natural logarithm, applied to positive scoresargmax = return the class that gives the largest scorex = fixed input, c ∈ 𝒴 = candidate classj = feature index, m = number of featurespX∣Y = likelihood, pY = prior, pX = evidence
Open the corresponding slide ↗

5.5.1 · Estimating the feature distributionsHow do we estimate each feature distribution?

We still need pXj∣Y(xj∣y), 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ⱼMethodIntuition
QuantitativeParametric, such as a GaussianChoose a shape and estimate its parameters.
QuantitativeNonparametric, such as kernel density estimation (KDE)Estimate a smooth density from the observed values.
CategoricalClass-conditional proportionsCount how often each category occurs within each class.
Xⱼ = random variable for feature jxⱼ = observed value of feature jy = a fixed class, also denoted c when comparing classesParametric = choose a family with parametersNonparametric = estimate without choosing that fixed family

The remaining task is to estimate the individual distributions pXj∣Y(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 pXj∣Y(xj∣c), 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 Xj 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 Xj∣Y=c∼𝒩(μj,σj2). 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.

Fitting and reading two petal-length densities Density (per cm) 0 0.2 0.4 1 2 3 4 5 6 7 8 9 Petal length (cm) New flower: 5.6 cm 0.111 Species 0 0.368 Species 1 Labeled training lengths
Open the corresponding slide ↗

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.

score(c)=pY(c)pX1∣Y(x1∣c)pX2∣Y(x2∣c)
ℙ(Y=1∣X=x)=score(1)score(0)+score(1)

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.

Interactive example · Naive Bayes: classify one flower
Two Gaussian plots show the new flower measurements. A table multiplies the prior and curve heights, then normalizes the class scores.
The same controls and observations as the slide. Use Larger view for more room. Printing uses the initial-state preview.
Open the corresponding slide ↗

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ᵢ:

pY∣X(c∣xi)=pX∣Y(xi∣c)pY(c)pX(xi)

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:

ℙ(Y=1∣X=xi)=σ(xi)

The coefficients are learned from labelled examples. The following section gives the formula for σ(xᵢ).

X = input features, xᵢ = their values for observation iY = class variable, c = a candidate class labelσ(xᵢ) = logistic model’s probability of class 1p = probability or density function identified by its subscript

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, pX∣Y(xi∣c) describes the distribution of the input features within class c, while pY∣X(c∣xi) 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.

Open the corresponding slide ↗

5.6 · Logistic regressionLogistic regression turns a linear score into a probability

ℙ(Y=1∣X=xi)=σ(xi)=11+e−(∑j=0mβjxij)=e∑j=0mβjxij1+e∑j=0mβjxij

Inside: a familiar linear score

∑j=0mβjxij=β0+∑j=1mβjxij

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 two fractions are equal: multiply the first numerator and denominator by e∑j=0mβjxij.
i = observation indexj = feature index, m = number of featuresxᵢⱼ = feature j for observation iβⱼ = learnable coefficient, β₀ = intercepte ≈ 2.718 = exponential baseσ(xᵢ) = logistic function evaluated using input 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.

Open the corresponding slide ↗

5.6 · Read the sigmoidThe score tells us which side of 50% we are on

Sigmoid: a linear score becomes a probability0.119-20.50000.8812Score z10
Read the score
Negative: class 1 probability below 0.5.
Zero: probability 0.5.
Positive: class 1 probability above 0.5.
What happens to the regression form?
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.
z=∑j=0mβjxij = linear score on the horizontal axisσ(xᵢ) = modelled class-1 probability on the vertical axisAt z=0, σ(xᵢ)=0.5.

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.

Open the corresponding slide ↗

5.6 · Logistic regressionFrom a logistic probability to a class label

y^i={1if σ(xi)≥0.50otherwise

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 output σ(xᵢ) is a probability.
The prediction ŷᵢ is a class label, either 0 or 1.
xᵢ = input for observation iσ(xᵢ) = modelled class-1 probabilityŷᵢ = predicted label𝒴={0,1} = binary class set

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.

Open the corresponding slide ↗

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.

Interactive example · Try the sigmoid: change the score, then read the label
Initial state of the interactive example: Try the sigmoid: change the score, then read the label
The same controls and observations as the slide. Use Larger view for more room. Printing uses the initial-state preview.
Open the corresponding slide ↗

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₂ = 0Model AModel B
Model’s class-1 probabilities(0.9, 0.9)(0.6, 0.4)
Patient 1 has label 1: use σ(x₁)0.90.6
Patient 2 has label 0: use 1−σ(x₂)1−0.9 = 0.11−0.4 = 0.6
Joint likelihood: σ(x₁) × (1 − σ(x₂))0.9 × 0.1 = 0.090.6 × 0.6 = 0.36
Model B assigns four times the likelihood to the observed pair (0.36 / 0.09).
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.

Check your understanding · L05-C06

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?

  1. A, because its two probabilities are larger.
  2. B: its likelihood is 0.36, four times A’s likelihood of 0.09.
  3. They tie because each predicts one positive probability above 0.5.
  4. 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.

Open the corresponding slide ↗

5.6.1 · Maximum likelihood estimationChoose coefficients that make the observed labels likely

𝛃^=argmax𝛃∈ℝm+1 ∏i:yi=1σ(xi)∏i′:yi′=0(1−σ(xi′))

If the recorded label is 1

Use the factor σ(xi)

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 factor 1−σ(xi′)

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.

The same coefficients determine every probability in the product.
Maximum Likelihood Estimation (MLE) chooses the coefficients with the largest joint likelihood. argmax returns those coefficients, rather than the product value.
𝛃=(β₀,…,βₘ) = coefficients, β₀ is the intercept𝛃^ = the fitted coefficient vectorm = number of features
ℝm+1 = 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.

Open the corresponding slide ↗

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.

This problem has no closed-form coefficient formula like ordinary least squares.
We use numerical optimization: improve candidate coefficients through calculations.
𝛃 = coefficients currently being triedσ(xᵢ) = probability computed from those coefficients𝛃^ = resulting fitted coefficientsNumerical optimization = repeated calculations to improve candidate coefficients

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.

Open the corresponding slide ↗

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.

Interactive example · Try coefficients and read the likelihood
Initial worked example: Try coefficients and read the likelihood. The preview uses the same values and calculations as the slide.
The same controls and observations as the slide. Use Larger view for more room. Printing uses the initial-state preview.
Open the corresponding slide ↗

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.

Explain the conditional probabilities, the Bayes decision rule and its derivation.
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.

Open the corresponding slide ↗

Further readingFurther reading on classification and probability

The textbooks listed here provide further background on classification and probability models. The lecture definitions, formulas and examples are explained in this handout.

Open the corresponding slide ↗

Notation at a glance

SymbolMeaning
𝒟, n, mDataset, number of observations, number of input features.
i, j, c, CObservation 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.
pY∣X, pX∣Y, pY, pXPosterior, likelihood, prior and evidence. Subscripts identify the variables and conditioning.
p(X), p(x) in the Bayes proofThe shorthand ℙ(Y=1 | X) or ℙ(Y=1 | X=x). It is not pX(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ᵢ₀=1Intercept, coefficient of feature j, and the constant input that includes the intercept in the sum.
σ(xᵢ), z, eLogistic class-1 probability, the linear score used to read the sigmoid plot, exponential base about 2.718.
∏, ∑, log, argmaxMultiply indexed terms, sum indexed terms, natural logarithm, return the maximizing class.
Continue learning