Skip to content
AI360XpertBeta
Playgrounds

Supervised Learning

Naive Bayes Classifier

A class prior and count-weighted token likelihoods determine a model posterior, provided some class supports the evidence.

Guided steps 1 / 4

Stage 1 of 4: Prior

Normalise after each evidence prefix

Supplied multinomial model. Query urgent 1, win 0, meeting 0, unseen 0. Spam prior 0.5. Current evidence: both classes have positive support. Spam posterior 0.8387096774193549. No measured accuracy or calibration.

Left hatched bar = Spam; right solid bar = Normal. Missing bars mean unavailable, never zero probability for both. Prefixes disclose calculation order, not a claim that real evidence is independent.

Exact cumulative beliefs
PrefixSpam ○Normal □
0: Prior0.50.5

Change the model prior

Manual Spam prior 0.5

The diamond changes the manual prior. It is not a training observation. No generated messages or evaluation partition exist here.

  • Spam (hatched)
  • Normal (solid)
Model settings
Adjust parameters

Overrides the supplied message fraction; Normal prior is one minus this.

Full query retained across stages: urgent 1, win 0, meeting 0, unseen 0. Supplied message counts: 10 Spam / 10 Normal. Token totals: 30 / 40; vocabulary: 20.

Current evidence: both classes have positive support.

Model probability is not measured correctness or calibration. Exact supported ties select Normal.

What would you predict before reading any tokens?

The first pair of bars shows the prior. Changing it is a manual model choice; the supplied message counts remain ten per class.

  1. Supplied counts
  2. Token likelihoods
  3. Prior × factors
  4. Supported normalisation
Prior

Class probability before reading the query. It defaults to the supplied 10/20 message fraction; manual edits override it.

Check this stage

Check your understanding

Combine a supplied multinomial token model with a query. Inspect exact likelihoods, class scores and normalised posteriors, then test zero counts and smoothing.

A spam-associated word can shift a message towards Spam. A word with zero Spam likelihood can rule Spam out completely. This lab shows the calculation inside a supplied multinomial Naive Bayes model; it does not train on visible messages or measure real spam-filter performance.

Start with the counts

Open Model settings and move the manual Spam prior, or drag its diamond in Prior. The first pair of bars changes before any evidence is read. The default 0.5 comes from ten supplied messages per class. Editing the prior overrides that fraction; it does not change the message counts.

The supplied token ledger is:

Vocabulary entriesSpam countNormal count
urgent122
win101
meeting015
unseen00
Remaining 16 entries, combined822
Total3040

The vocabulary has twenty entries. The remaining counts are aggregate mass, not sixteen additional query controls. Their individual allocation is illustrative and does not affect these queries, which have zero counts there. The Supplied Spam meeting count control adds meeting tokens to the original Spam total; the denominator changes with it. These are sufficient statistics supplied to the estimator, without an individual-message dataset or validation split.

Count tokens, then normalise

In Single feature, drag the query diamond or change Query urgent count. In Multiple features, select win or meeting and edit that count. Selection only chooses the handle; it never changes the query or fits a model. All model and query settings survive stage changes. The full current query remains printed beside the controls.

For class cc and vocabulary word ww, let NcwN_{cw} be its supplied token count, NcN_c the class token total, VV the vocabulary size and α\alpha the smoothing strength. The estimated token probability is

θcw=Ncw+αNc+αV.\theta_{cw}=\frac{N_{cw}+\alpha}{N_c+\alpha V}.

At α=1\alpha=1, urgent has Spam probability 13/50=0.2613/50=0.26 and Normal probability 3/60=0.053/60=0.05. With equal priors and one urgent token, the reduced class scores are 0.5(0.26)=0.130.5(0.26)=0.13 and 0.5(0.05)=0.0250.5(0.05)=0.025. Divide by their sum, 0.1550.155: Spam receives 26/31≈0.8387126/31\approx0.83871, Normal 5/31≈0.161295/31\approx0.16129.

For query token counts xwx_w and class prior πc\pi_c, the general score and posterior are

sc=πc∏wθcwxw,P(c∣x)=sc∑ksk.s_c=\pi_c\prod_w\theta_{cw}^{x_w},\qquad P(c\mid x)=\frac{s_c}{\sum_k s_k}.

The common multinomial coefficient is omitted from every score and cancels in this ratio. Consequently, the displayed reduced normaliser is not the full probability of the count vector. Scores are neither calibrated probabilities nor Gaussian densities. For the empty query, every token factor is one and the posterior equals the prior.

The chart normalises after each prefix: prior, urgent, win, meeting and unseen. The native table names every visible prefix and retains its raw posterior. Hatched left bars represent Spam; solid right bars represent Normal. Order changes the intermediate beliefs but not the final product. Predict the current full query’s result, then reveal it and inspect the same calculation under the hood. Exact supported class-score ties select Normal.

What does “naive” assume?

The model assumes class-conditional token draws share a fixed word distribution. It does not assert that words are marginally independent. Multinomial counts at a fixed length also have a sum constraint; treating their coordinates as unconstrained independent Bernoulli features would be a different model.

A zero query count contributes no token factor. There is no extra probability for the absence of meeting here: Bernoulli NB would model presence and absence. A missing measurement is not automatically an observed absence. This lab accepts complete nonnegative integer count vectors, not missing values.

The word unseen is a known vocabulary member with zero supplied count in both classes. A word outside this fixed vocabulary would be discarded before classification under the stated vectorisation policy. Other systems can introduce an explicit unknown token; ignoring every new category is not a universal Bayes rule.

Real text has dependencies. Counting a deterministic copy as new evidence can exaggerate support and can change the winning class. This aggregate table contains no joint observations, so it cannot measure those dependencies or demonstrate a calibration penalty. A posterior near one proves neither correctness nor calibration. The logistic regression lab offers a different score construction; the train/test lab explains why evaluation labels must stay out of fitting and model selection.

Break the support, then repair it

In Zero frequency, press Load zero-count preset. Five urgent and five win tokens favour Spam, but one meeting token at alpha zero gives it a zero score. Normal still supports the query, so its model posterior is one. This says what the model permits, not the true label of a real message.

Now add one unseen token with alpha still zero. Both classes have zero likelihood for it: neither supports the query. The lab prints unavailable instead of inventing a posterior or silently choosing Normal. Missing bars mean unavailable. Setting the prior to zero can also rule a class out; smoothing its word probabilities cannot undo that choice.

Raise alpha above zero. Adding alpha to every vocabulary count, and αV\alpha V to the denominator, makes the token probabilities positive for these nonempty supplied classes. Alpha one is Laplace (add-one) smoothing; other positive strengths use additive smoothing. Large finite alpha moves likelihoods towards uniformity; only the limit makes the posterior equal the prior for every fixed query. Smoothing does not repair dependence or certify good predictions.

Back to working restores the complete preceding experiment, including stage, model/query controls, selected word, guided/free mode and prediction. Its banner distinguishes the loaded preset from current support after further edits. Recovery stays available in free exploration. Reset controls restores defaults at the current stage and clears recovery. Load challenge establishes a fixed task: changing the prior, supplied training counts or unseen token cannot bypass its goal.

Why keep log scores?

Long products can round to zero even when every factor is positive. The implementation adds natural logarithms instead:

ℓc=log⁡πc+∑wxwlog⁡θcw.\ell_c=\log\pi_c+\sum_w x_w\log\theta_{cw}.

Under the hood, inspect the prior contribution, each count-weighted token contribution, raw reduced scores, class log scores and log odds ℓSpam−ℓNormal\ell_{Spam}-\ell_{Normal}. A genuine zero factor gives negative infinity. When both log scores are negative infinity, log odds and the posterior are unavailable. Finite logs with underflowed raw exponentials are a different numerical condition; the stable posterior still exists.

For supported evidence, subtract the largest log score mm before exponentiating:

P(c∣x)=exp⁡(ℓc−m)∑kexp⁡(ℓk−m).P(c\mid x)=\frac{\exp(\ell_c-m)}{\sum_k\exp(\ell_k-m)}.

For one urgent token at the default settings, the log odds are log⁡(5.2)\log(5.2). The table retains infinite values explicitly rather than clipping a waterfall. Adding logs changes the numerical representation, not the independence assumption. No asynchronous fit, autoplay or optimiser history is needed for this bounded calculation.

Share copies the guided display stage, supplied-model controls, query and selected word for deterministic recomputation. It transfers no random dataset, prediction answer, free-mode identity, completion or recovery snapshot. Progress stays on this device. No training accuracy, exploratory validation score, untouched final test or calibration assessment is computed here.

Sources and limits

The scikit-learn Naive Bayes guide distinguishes multinomial counts, Bernoulli absence and Gaussian density models. Its implementation uses count-weighted logs and log-space normalisation. The calibration guide explains why probability quality needs separate assessment. This lab’s fixed aggregate fixture supplies no empirical accuracy or calibration evidence, and no independent final test.

Stage recap

  1. Prior

    The first pair of bars shows the prior. Changing it is a manual model choice; the supplied message counts remain ten per class.

  2. Single feature

    Drag the diamond or change the query count. The next pair of bars normalises the prior times the urgent likelihood raised to that count.

  3. Multiple features

    Each prefix adds count-weighted log likelihoods. This multinomial model counts tokens; an absent token adds zero, without a Bernoulli absence factor.

  4. Zero frequency

    Try the zero-count preset, then add the known-unseen token. Smoothing adds alpha to each of twenty vocabulary counts.

Reference

Model family
Multinomial token counts from supplied sufficient statistics; no individual messages are fitted here.
Likelihood
(Ncw + alpha)/(Nc + alpha V); V includes every vocabulary entry.
Score
Prior times token likelihoods raised to query counts. The common multinomial coefficient is omitted.
Posterior
Normalise supported class scores in log space. All-impossible evidence is unavailable.
Independence
A conditional model assumption, not marginal independence or a calibration certificate.

Break it on purpose

With alpha zero, meeting rules out Spam in the supplied table. A vocabulary token unseen in both classes rules out both: no posterior exists. Positive smoothing repairs token zeros, not zero priors or dependence.