Concepts / Logistic Regression and Linear Support Vector Classifiers

Logistic Regression and Linear Support Vector Classifiers

Naive Bayes classifiers resemble linear models but train and predict faster, usually at a small cost in generalization accuracy.

  • Programming

A Small Dataset to Start With

Naive Bayes classifiers belong to the same broad family as the linear models you have already studied. Their decision rules take a similar shape, and they usually reach a slightly lower generalization accuracy than classifiers such as LogisticRegression and LinearSVC. What they give up in accuracy they recover in speed: Naive Bayes models are noticeably faster to train than those linear methods, and they are very fast to predict as well.

Before any theory, start with a concrete dataset. Imagine four data points, each described by four binary features, where every feature is either 0 or 1. Each data point also carries a class label, and there are two classes. The raw material a Naive Bayes model works with is simply a tally of how often each feature equals 1 within each class. Keep that in mind as you read the table below, because every later idea in this article is built from those tallies.

python
Output (expected)
(4, 4)
[0 0 1 1]
Notes on the code
  • X holds the features: one row per data point, one column per feature.
  • y holds the labels: one class per row of X.
  • Features and labels are separate variables, which is the distinction the program is meant to make clear.

Counting Features Within Each Class

A Naive Bayes model does not look at whole rows at once during training. Instead it takes each feature separately and gathers simple statistics for every class. For each class, it asks: across all rows that belong to this class, how many times does this feature equal 1? In the dataset above, class 0 contains the first two rows and class 1 contains the last two.

What do you think happens?

Within class 1, how many of its two rows have feature 2 equal to 1?

  • 0

  • 1

  • 2

  • 4

Reveal answer
Answer:

2

Both class 1 rows, [0, 1, 1, 1] and [0, 0, 1, 1], have a 1 in the third column (index 2), so the count is 2.

python
Output (expected)
[[2 1 1 0]
 [0 1 2 2]]
Notes on the code
  • counts starts as a 2 by 4 table of zeros: one row per class, one column per feature.
  • The loop visits each data point exactly once; adding the row to counts[label] accumulates its 1s into that class's tally.
  • The result is the raw material for Naive Bayes: how often each feature is set within each class.
Feature 02Feature 00Feature 11Feature 11Feature 21Feature 22Feature 30Feature 32
After one pass over the rows, how many times does each feature equal 1 within each class? Class 0 holds rows one and two, class 1 holds rows three and four.

Read the diagram as a lookup table. The value under Feature 0 for class 0 is 2 because both of its rows have a 1 in that column. The value under Feature 0 for class 1 is 0 because neither class 1 row has a 1 there. These per-class tallies are the entire set of statistics the model needs from the training data.

Why Naive Bayes Trains Fast

The speed comes from how the model learns. A linear model such as LogisticRegression optimizes all of its feature weights together. A Naive Bayes model instead looks at each feature on its own and gathers simple statistics for every class. Because the work for each feature is independent and cheap, the whole training process stays short. The word naive in the name refers to this simplifying choice to treat features separately.

Training a Naive Bayes model is a counting exercise. The model reads the rows once, tallies feature values per class, and stores those tallies. There is no iterative search over weights that repeatedly revisits the data. This single pass is why training is fast, and it is also why Naive Bayes stays fast on very large datasets where training even a linear model might take too long.

Read each row oncefitCount 1s per featureper classfitStore per-classcountsfitLook up per-featurelikelihoodspredictCombine with classpriorspredictPick the best-scoringclasspredictused later
What happens in order during fit, which only counts per class, and during predict, which combines the stored statistics with class priors?

Fit therefore needs only one pass over the data, and it touches each feature in a simple way. Predict then reuses the stored counts rather than recomputing anything from the training rows. Both phases are cheap, which explains why the source describes Naive Bayes models as very fast to predict as well as to train.

Choosing Among GaussianNB, BernoulliNB, and MultinomialNB

scikit-learn implements three Naive Bayes classifiers. They differ mainly in the type of data they assume. GaussianNB is meant for continuous data of any kind. BernoulliNB assumes each feature is binary, meaning it is either present or absent. MultinomialNB assumes count data, where each feature is an integer count of something, such as how often a particular word appears in a sentence.

Continuous valuesany continuous dataBinary featurespresent or absentInteger countshow often a feature occursVery high-dimensionaldatamost common useText classificationsparse text featuresText classificationword counts in documents
Which kind of feature data does each variant assume, and where is it most often used?

The assumed data type changes the per-class distribution the model learns. GaussianNB summarizes each feature within each class as a continuous spread. BernoulliNB records, for each class, how often each binary feature is present. MultinomialNB records, for each class, how the integer counts of each feature are distributed. In every case the learned statistics are still simple per-class summaries, which is what keeps the training fast.

VariantData it assumesTypical useAlpha parameter
GaussianNBContinuous values of any kindVery high-dimensional dataNot one of the two alpha-tuned variants named in the source
BernoulliNBBinary features, present or absentClassifying textYes, controls smoothing
MultinomialNBInteger count data, such as word countsSparse count data such as textYes, controls smoothing

The three scikit-learn Naive Bayes variants, grouped by the kind of data each one assumes.

The Alpha Parameter and Smoothing

MultinomialNB and BernoulliNB each have one main tuning parameter, alpha, which controls model complexity. The mechanism is smoothing. The algorithm adds alpha virtual data points that have positive values for all features, which softens the statistics it collected from the real data. A larger alpha means more smoothing and a less complex model.

Smoothing matters because raw counts can be zero. In the example table, class 1 never has a 1 in feature 0, and class 0 never has a 1 in feature 3. A raw count of zero produces a raw probability of zero, which would let a single missing feature veto a class entirely. Adding alpha to every count keeps every estimate above zero.

Count of 1s0Count of 1s1Estimate0.00Estimate0.25add alpha = 1renormalize
When alpha equals 1 is added to the counts, how do the zero count and its probability estimate change?
Worked example

Smoothing a zero count

Class 1 has two rows. Feature 1 equals 1 in neither of them, so the raw count is 0. Estimate the probability that feature 1 equals 1 within class 1, before and after smoothing with alpha = 1.

  1. 1
    Raw estimate

    The raw count is 0 out of 2 rows in the class, so the raw estimate is $\frac{0}{2} = 0$. A zero estimate would eliminate class 1 for any row where feature 1 is 1.

  2. 2
    Add alpha to the count

    Alpha = 1 adds one virtual positive value for this feature, so the smoothed numerator is $0 + 1 = 1$.

  3. 3
    Adjust the denominator

    Each of the two binary feature values receives alpha, so the denominator grows by $2 \times 1$, giving $2 + 2 = 4$.

  4. 4
    Smoothed estimate

    The smoothed estimate is $\frac{1}{4} = 0.25$, which is small but no longer zero.

Result

Smoothing turns a zero estimate into 0.25. Because alpha is only a softening term, changing its value slightly usually shifts predictions only a little.

Strengths and Weaknesses in Practice

Naive Bayes models share many strengths and weaknesses with linear models. They train and predict very quickly, the training procedure is easy to follow, and they handle high-dimensional sparse data well. They are also relatively robust to their parameters. Because of this, they serve as strong baseline models.

  • Strength: very fast training and prediction, because each feature is handled on its own with cheap counting.
  • Strength: a short, easy-to-follow training procedure that is easy to explain to others.
  • Strength: good performance on high-dimensional sparse data such as text.
  • Weakness: the independence treatment of features gives up some generalization accuracy compared with LogisticRegression and LinearSVC.
  • Weakness: its accuracy usually improves only modestly when its single alpha parameter is tuned.

Among the variants, MultinomialNB usually performs better than BernoulliNB, particularly on datasets with a relatively large number of nonzero features, such as large documents. GaussianNB is mostly used for very high-dimensional data, while the other two variants are widely used for sparse count data such as text.

Mistakes Beginners Make with Naive Bayes

  • Common mistake

    Treating Naive Bayes as the most accurate option by default

    What it looks like

    Choosing BernoulliNB on a problem where a LogisticRegression baseline would have scored higher, just because it trains quickly.

    Why it fails

    The source states that Naive Bayes generalization is often slightly worse than that of linear classifiers, because speed is what it trades accuracy for.

    Do this instead

    Use Naive Bayes as a fast baseline, then compare it against a linear model before committing.

  • Common mistake

    Choosing the variant by name instead of by data type

    What it looks like

    Using GaussianNB on word counts because the name sounds like a general default.

    Why it fails

    GaussianNB is meant for continuous data, while word counts are integer counts that MultinomialNB assumes.

    Do this instead

    Match the variant to the feature type: continuous to GaussianNB, binary to BernoulliNB, integer counts to MultinomialNB.

  • Common mistake

    Forgetting that alpha is a smoothing term, not a feature

    What it looks like

    Passing a raw count such as 0 and expecting it to be treated as evidence against the class without any adjustment.

    Why it fails

    Alpha adds virtual positive values to every feature so that zero counts do not produce zero estimates.

    Do this instead

    Leave alpha at its default first, then tune it modestly if the baseline needs improvement.

  • Common mistake

    Assuming that the per-feature counts describe interactions between features; each feature is counted separately, so they do not capture relationships between columns.

Reading the Counts Yourself

EASY

Suppose a fifth training row, [1, 0, 0, 1], is added with class label 1. Without rerunning the code, work out the new counts for class 1 in every feature column. Which feature count changes from 2 to 3, and which stays the same?

Hints
  • Class 1 currently has counts [0, 1, 2, 2]. Only the new row's 1s need to be added to these counts.
  • The new row has 1s in feature 0 and feature 3 only.
  • Features 1 and 2 of the new row are 0, so their counts do not change.
MEDIUM

Explain in two sentences why a Naive Bayes model can be trained with one pass over the rows, while a linear model is usually trained by repeatedly adjusting all of its weights together.

Hints
  • Think about how many times each row must be visited under each approach.
  • Connect the phrase 'each feature on its own' to the per-class counts.

Key Takeaways

  • Naive Bayes learns by examining each feature separately and collecting simple per-class statistics, mainly how often each feature takes a given value within each class.
  • Its training needs one pass over the data, which makes both training and prediction very fast, usually at a small cost in generalization accuracy compared with LogisticRegression and LinearSVC.
  • GaussianNB assumes continuous data, BernoulliNB assumes binary features, and MultinomialNB assumes integer count data such as word counts.
  • Alpha controls smoothing by adding virtual positive values, which keeps zero counts from producing zero probabilities; performance is relatively robust to its value.

Related concepts

More concepts starting with L