Skip to content

naive Bayes

learning

Level 2 of 3

Also called the naive Bayes classifier and simple Bayes.

how it works

The idea in short steps and three pictures, then one new point given a class step by step. In the step tables, t, s and c are the classes, 0-10 counts all their points, and x and y are the bands across and up.

Naive Bayes gives a new point a class by counting. Each axis is cut into three bands: 0 to 3, 4 to 6 and 7 to 10. For each class it counts its points, and how many stand in each band across and each band up. A class's score is three shares multiplied. The first is its points over all the points. The next two are its points in the new point's band across, then up, each over the class's own points. Below, five triangles, one square and a new point at 4 across, 9 up. The square scores 1/6 × 1/1 × 1/1, about 0.167. No triangle stands in band 4 to 6 across, so the triangles score 5/6 × 0/5 × 3/5 = 0. The highest score wins: a square. Equal scores go to the class with more points, then to triangle, square, circle in that order. Each point is counted once, so n points cost n counts.

02468100246810
classpointsin band 4 to 6 acrossin band 7 to 10 upscore
triangles5030
squares1110.167
Five triangles, one square and a new point at 4 across, 9 up. Each cell is shaded in the class a new point there would get. The table holds each class's counts and score.
the trianglesmade-up points, one in each bandin band 4 to 6 across
The triangles' 5 points, one box each, and none in band 4 to 6 across, 0 of 5. A smoothing count of 1 adds one made-up point to each of the three bands. Now 1 of 8 stands there. The 0 has turned small, not nothing.
02468100246810
classpointsin band 4 to 6 acrossin band 7 to 10 upscore
triangles50 + 13 + 10.052
squares11 + 11 + 10.042

With a smoothing count of 1, the new point becomes a triangle, with a score of 0.052.

With scripts on, a slider sets the smoothing count from 0 to 5. The cells, the table and this line change with it.

The same points with the smoothing count free to change. At 0 the square wins. At 1 the triangles score 5/6 × (0 + 1)/(5 + 3) × (3 + 1)/(5 + 3), about 0.052, beating the square's, about 0.042. At 2 the triangles' band shares are over 5 + 3 × 2 = 11.
One square, five triangles, no smoothing: 7 moments of its 11 steps, the steps between them left for the watch page
  1. step 1 of 11

    024681002468100-10x 0-3x 4-6x 7-10y 0-3y 4-6y 7-10ts00000000000000

    6 points have a class. Each axis is cut into three bands, 0 to 3, 4 to 6 and 7 to 10, and a point is told by its band across and its band up. There is no smoothing, so a count of 0 stays 0.

    what it remembers to know where it is
    the triangles' score
    not yet
    the squares' score
    not yet
    the circles' score
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

  2. step 2 of 11

    024681002468100-10x 0-3x 4-6x 7-10y 0-3y 4-6y 7-10ts11000010000000

    Point 1, the triangle at 1 9, is in band 0 to 3 across and band 7 to 10 up. Add 1 to its class's points and to those two bands in its row.

    what it remembers to know where it is
    the triangles' score
    not yet
    the squares' score
    not yet
    the circles' score
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

  3. step 7 of 11

    024681002468100-10x 0-3x 4-6x 7-10y 0-3y 4-6y 7-10ts51042031010001

    Point 6, the square at 5 8, is in band 4 to 6 across and band 7 to 10 up. Add 1 to its class's points and to those two bands in its row.

    what it remembers to know where it is
    the triangles' score
    not yet
    the squares' score
    not yet
    the circles' score
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

  4. step 8 of 11

    024681002468100-10x 0-3x 4-6x 7-10y 0-3y 4-6y 7-10ts51042031010001

    The new point at 4 9 is in band 4 to 6 across and band 7 to 10 up. Each class is scored on those two bands alone, one at a time.

    what it remembers to know where it is
    the triangles' score
    not yet
    the squares' score
    not yet
    the circles' score
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

  5. step 9 of 11

    024681002468100-10x 0-3x 4-6x 7-10y 0-3y 4-6y 7-10ts51042031010001

    Triangles: 5 of the 6 points, 0 in the new point's band across, 3 in its band up. The shares in the bands are over its 5 points: 5/6 × 0/5 × 3/5 = 0.

    what it remembers to know where it is
    the triangles' score
    0
    the squares' score
    not yet
    the circles' score
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

  6. step 10 of 11

    024681002468100-10x 0-3x 4-6x 7-10y 0-3y 4-6y 7-10ts51042031010001

    Squares: 1 of the 6 points, 1 in the new point's band across, 1 in its band up. The shares in the bands are over its 1 points: 1/6 × 1/1 × 1/1 = 0.167.

    what it remembers to know where it is
    the triangles' score
    0
    the squares' score
    0.167
    the circles' score
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

  7. step 11 of 11

    024681002468100-10x 0-3x 4-6x 7-10y 0-3y 4-6y 7-10ts51042031010001

    Squares score highest, 0.167, so the new point becomes a square. Each band cell is shaded in the class a new point there would get.

    what it remembers to know where it is
    the triangles' score
    0
    the squares' score
    0.167
    the circles' score
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

the steps, in plain words
  1. cut each axis into three bandsPython lines 10 and 11
  2. for each point, count its band across and its band up in its class's rowPython lines 14, 15, 16, 17 and 18
  3. find the new point's bandsPython line 19
  4. score each class: its share of the points times its share in each bandPython lines 21, 24, 25, 26 and 27
  5. give the new point the class with the highest scorePython lines 28, 29, 30, 31 and 32
the same in Python

The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.

def naive_bayes(points, new_point, smoothing):
    """The shape naive Bayes gives new_point.

    Each point is a tuple (across, up, shape), the shape "triangle",
    "square" or "circle"; new_point is (across, up). Each axis is cut in
    three bands, 0 to 3, 4 to 6 and 7 to 10. smoothing is added to each
    band count, and 3 times it to each band share's bottom. A tie goes to
    the shape with more points, then triangle, square, circle.
    """
    def band(v):
        return 0 if v <= 3 else 1 if v <= 6 else 2

    table = {}
    for x, y, shape in points:  # each point once
        row = table.setdefault(shape, [0, [0, 0, 0], [0, 0, 0]])
        row[0] += 1  # its shape's points
        row[1][band(x)] += 1  # its band across
        row[2][band(y)] += 1  # its band up
    across, up = band(new_point[0]), band(new_point[1])  # the new point's bands
    best = None
    for shape in ("triangle", "square", "circle"):  # each shape present
        if shape not in table:
            continue
        mine, xs, ys = table[shape]
        whole = mine + 3 * smoothing
        top = mine * (xs[across] + smoothing) * (ys[up] + smoothing)  # its score,
        bottom = len(points) * whole * whole  # kept whole as top / bottom
        higher = best is None or top * best[1] > best[0] * bottom  # cross multiplied
        tied = best is not None and top * best[1] == best[0] * bottom
        if higher or (tied and mine > best[2]):  # a tie goes to more points
            best = (top, bottom, mine, shape)
    return best[3]  # the highest score

how it scales

How the points counted grow, from ten points to a hundred thousand.

Each step across or up is ten times the one before. The line climbs one step up for each step across: ten times the points, ten times the counts. Every set of nn points counts exactly nn, so the points sit on the line.

points counted, ten times more at each mark up

slope 1102104106101102103104105106107slope 1101102103104105106107101102103104105106107slope 1101102103104105106107101102103104105106107

nn, how many points have a class, ten times more at each mark to the right

  • every set of points, wherever they standsolid where measured by running it; dashed where its formula carries it on to ten millionslope 1: ten times n, 10 times the work
what a set of points costs, at a billion points counted a second
nnpoints countedtime
1,0001,000about 1 microsecond
100,000100,000about 100 microseconds
10,000,00010,000,000about 10 milliseconds

The points counted are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.

make these counts yourself

Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.

"""Count naive Bayes's points yourself, as the plot on this page does.

Run it with Python 3.12 or later. For each n it scatters n points with a
shape each over a square of whole-numbered spots, places a new point on a
spot of its own, and prints how many points the method counts into its
table with a smoothing count of 1, up to n = 100,000. The counts are the same
on any computer; only the time differs.
"""

import random


def naive_bayes(points, new_point, smoothing):
    """The shape naive Bayes gives new_point.

    Each point is a tuple (across, up, shape), the shape "triangle",
    "square" or "circle"; new_point is (across, up). Each axis is cut in
    three bands, 0 to 3, 4 to 6 and 7 to 10. smoothing is added to each
    band count, and 3 times it to each band share's bottom. A tie goes to
    the shape with more points, then triangle, square, circle.
    """
    def band(v):
        return 0 if v <= 3 else 1 if v <= 6 else 2

    table = {}
    for x, y, shape in points:  # each point once
        row = table.setdefault(shape, [0, [0, 0, 0], [0, 0, 0]])
        row[0] += 1  # its shape's points
        row[1][band(x)] += 1  # its band across
        row[2][band(y)] += 1  # its band up
    across, up = band(new_point[0]), band(new_point[1])  # the new point's bands
    best = None
    for shape in ("triangle", "square", "circle"):  # each shape present
        if shape not in table:
            continue
        mine, xs, ys = table[shape]
        whole = mine + 3 * smoothing
        top = mine * (xs[across] + smoothing) * (ys[up] + smoothing)  # its score,
        bottom = len(points) * whole * whole  # kept whole as top / bottom
        higher = best is None or top * best[1] > best[0] * bottom  # cross multiplied
        tied = best is not None and top * best[1] == best[0] * bottom
        if higher or (tied and mine > best[2]):  # a tie goes to more points
            best = (top, bottom, mine, shape)
    return best[3]  # the highest score


def count(points, new_point, smoothing):
    """The same method's first loop on points, counting each point it adds to the table."""
    counted = 0
    for _ in points:
        counted += 1  # one for each point
    return counted


def scatter(n, seed):
    """n points with a shape each on distinct spots, and a new point on a spot of its own."""
    rng = random.Random(seed)
    side = max(10, int((2 * (n + 1)) ** 0.5) + 1)
    spots = rng.sample(range((side + 1) ** 2), n + 1)
    at = [(s % (side + 1), s // (side + 1)) for s in spots]
    shapes = ("triangle", "square", "circle")
    return [(x, y, rng.choice(shapes)) for x, y in at[:n]], at[n]


if __name__ == "__main__":
    print(f"{'n':>7} {'counted':>8}")
    for n in (10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10_000, 20_000, 50_000, 100_000):
        points, new_point = scatter(n, n)
        print(f"{n:>7} {count(points, new_point, 1):>8}")

best, worst and average

Any set of nn points costs the same, nn counts, so best, worst and average are one column.

A case is one kind of input, the thing the method is given, such as a set of points. A bound says how fast that case's cost grows as more points come in.

The count is in the grid: one count for each point, n in all, on every set of points, so the three bounds all grow as n.

what each case costs, and how fast that cost grows; section 4 works out every formula in it
averageevery set of points, wherever they stand
points countednn
how the points counted grow in each case
tight, Θ\ThetaΘ(n)\Theta(n)
ceiling, OOO(n)O(n)
floor, Ω\OmegaΩ(n)\Omega(n)

extra memory: a table of 1 + 3 + 3 = 7 counts for each class (its points, three bands across, three bands up), 3 classes at most, whatever n is

Extra memory is the room it needs on top of the input itself, while it runs.

pointssmoothing countpoints counted
404
424
616
Four points with no smoothing and with a smoothing count of 2, and six points with 1. The counts follow the points, never the smoothing count.

where the formula comes from

The count above, and the score, each worked out in small steps naming the line it comes from.

Why does naive Bayes count exactly nn points, on every set of points?
  1. the move: see the counting

    the line:
    each point goes onceinto its class’s row\begin{gathered} \text{each point goes once} \\ \text{into its class's row} \end{gathered}
    pointclassband acrossband up
    2 8triangle0 to 37 to 10
    7 8square7 to 107 to 10
    6 2circle4 to 60 to 3
    3 2triangle0 to 30 to 3
    Four points, each read once, its class and its two bands. Four counts.

    why it is allowed: The run reads every point in turn, once, and adds 1 to its class's points and to its two bands. The table shows four.

  2. the move: one for each point

    the line:
    C=1+1+⋯+1C = 1 + 1 + \dots + 1

    why it is allowed: CC is the points counted. By line 1, one for each of the nn points.

  3. the move: add the ones

    the line:
    C=nC = n

    why it is allowed: By line 2, nn ones add up to nn. For the four points, 4.

  4. the move: any set, any smoothing

    the line:
    the same for every setand every smoothing count\begin{gathered} \text{the same for every set} \\ \text{and every smoothing count} \end{gathered}

    why it is allowed: In line 1, how many points are counted never depends on where they stand or on the smoothing count, only on their being there.

  5. the move: a ceiling

    the line:
    C≤nC \le n

    why it is allowed: By line 3, CC is nn, so it is at most nn. Bounds still matter: they name how fast the count grows, as in section 3's grid.

  6. the move: read it as a bound

    the line:
    C∈O(n)C \in O(n)

    why it is allowed: By line 5, CC is at most 1 times nn.

  7. the move: a floor

    the line:
    C≥nC \ge n

    why it is allowed: By line 3, CC is at least nn too.

  8. the move: read it as a bound

    the line:
    C∈Ω(n)C \in \Omega(n)

    why it is allowed: By line 7, CC never drops below 1 times nn.

  9. the move: ceiling and floor together

    the line:
    C∈Θ(n)C \in \Theta(n)

    why it is allowed: Lines 6 and 8 bound CC by the same growth, nn.

try it on small inputs: over every set of 4 points, wherever they stand, the average is C=4C = 4

Why is a class's score the top of Bayes' rule, and why does the highest score win?
  1. the move: the triangles' score

    the line:
    S=56×0+15+3×3+15+3S = \frac{5}{6} \times \frac{0 + 1}{5 + 3} \times \frac{3 + 1}{5 + 3}
    shareworkedwhat it is
    5/65 of 6the triangles, of all the points
    (0 + 1)/(5 + 3)1 of 8in band 4 to 6 across, smoothed
    (3 + 1)/(5 + 3)4 of 8in band 7 to 10 up, smoothed
    The three shares. The first is over all 6 points and is not smoothed. Each band share is over the triangles' own 5 points, plus 3, one made-up point for each band.

    why it is allowed: SS is the triangles' score in section 1, with a smoothing count of 1. The table shows where each share comes from.

  2. the move: multiply

    the line:
    S=596S = \frac{5}{96}

    why it is allowed: By line 1, 5 × 1 × 4 is 20 over 6 × 8 × 8, which is 384. 20/384 is 5/96, about 0.052.

  3. the move: the naive guess

    the line:
    both bands together:guessed, never counted\begin{gathered} \text{both bands together:} \\ \text{guessed, never counted} \end{gathered}

    why it is allowed: Bayes' rule, opened at line 4, needs the chance of both bands at once, given a triangle. The run never counts that pair; here 0 of the 5 triangles stand in both. Counting every pair would need 9 cells for each class, most of them 0 with so few points. Line 1 multiplies the two band shares instead, as if across said nothing about up. Section 6 sets the guess beside a count.

  4. the move: read it as Bayes' top

    the line:
    S=chance of the bands,given a triangle,×chance of a triangle\begin{gathered} S = \text{chance of the bands,} \\ \text{given a triangle,} \\ \times \text{chance of a triangle} \end{gathered}
    where does this come from?
    question 2 of the page chances, and Bayes' ruleThe same bags, with chances in place of counts. The chance of fruit is n100\frac{n}{100}. Write SS so that every piece is a chance.
    1. the move: count the sits each way

      the line:
      S=9n109n10+2(100−n)10S = \frac{\frac{9n}{10}}{\frac{9n}{10} + \frac{2(100 - n)}{10}}

      why it is allowed: Question 1's first line, the sits with fruit over all the sits.

    2. the move: write each count as a share of its bags

      the line:
      S=910×n910×n+210×(100−n)S = \frac{\frac{9}{10} \times n}{\frac{9}{10} \times n + \frac{2}{10} \times (100 - n)}
      piecewith 10 bags of fruitwhat it is
      910\frac{9}{10}0.9the chance of a sit, given fruit
      nn10bags with fruit
      210\frac{2}{10}0.2the chance of a sit, given no fruit
      100−n100 - n90bags without fruit
      The four pieces of this line with 10 bags of fruit. 0.9 times 10 is the 9 sits with fruit, and 0.2 times 90 is the 18 without.

      why it is allowed: 9n10\frac{9n}{10} is 9 tenths of nn: the chance of a sit given fruit, times the bags with fruit. In the same way, 2 tenths of the other 100−n100 - n bags get a sit.

    3. the move: divide top and bottom by 100

      the line:
      S=910×n100910×n100+210×100−n100S = \frac{\frac{9}{10} \times \frac{n}{100}}{\frac{9}{10} \times \frac{n}{100} + \frac{2}{10} \times \frac{100 - n}{100}}

      why it is allowed: Top and bottom shrink alike, so the share is unchanged. nn over 100 is the chance of fruit, and 100−n100 - n over 100 is the chance of no fruit. So the top is the chance of a sit given fruit, times the chance of fruit. Underneath, the same for no fruit is added to it, which makes the chance of a sit. This is Bayes' rule. For 10 bags with fruit the top is 0.9 times 0.1, which is 0.09: the 9 bags with fruit and a sit, out of 100. Underneath, 0.2 times 0.9 is 0.18, and 0.09 + 0.18 is 0.27, the 27 sits out of 100. 0.09 over 0.27 is a third again.

    the whole page: chances, and Bayes' rule

    why it is allowed: Bayes' rule is a fraction, and its ladder opens in place below. Its top is the chance of the evidence given the class, times the chance of the class. Here the evidence is the new point's two bands. 5/6 is the chance of a triangle. By line 3, 1/8 × 4/8 is the guessed chance of the bands, given a triangle.

  5. the move: the same bottom

    the line:
    every class sharesthe bottom of Bayes’ rule\begin{gathered} \text{every class shares} \\ \text{the bottom of Bayes' rule} \end{gathered}

    why it is allowed: Bayes' rule divides each class's top by the chance of the bands. The new point's bands turn up with a triangle or with a square, so, under the guess, their chance is the two tops added. It is the same for every class, so the highest top has the highest chance.

  6. the move: score the squares

    the line:
    the squares’ top:4 in 96\begin{gathered} \text{the squares' top:} \\ \text{4 in 96} \end{gathered}
    classtop
    triangles5/96
    squares4/96
    The two tops, worked from the run's scores, the triangles' by line 2 and the squares' here.

    why it is allowed: As lines 1 and 2 did for the triangles. The square at 5 8 stands in both of the new point's bands. So its top is 1/6 × (1 + 1)/(1 + 3) × (1 + 1)/(1 + 3) = 1/24, or 4/96.

  7. the move: divide by the bottom

    the line:
    a triangle, guessed 5 in 9;a square, 4 in 9\begin{gathered} \text{a triangle, guessed 5 in 9;} \\ \text{a square, 4 in 9} \end{gathered}

    why it is allowed: By line 5, the bottom is the two tops added, 5/96 + 4/96 = 9/96. Dividing each top by it, the guess puts a triangle's chance at 5/9 and a square's at 4/9.

try it with a small nn: at n=6n = 6, line 1 gives SS, about 0.05

count it yourself

Count every step on four points, smoothing count 1. A point such as 2 8 t is a triangle at 2 across, 8 up (s is a square, c a circle). After the semicolons come the new point, then the smoothing count. Then check the counts against the formula.

2 8 t, 7 8 s, 6 2 c, 3 2 t; 5 4; 1, every step written down
stepwhat happenspoints countedclasses scored
14 points have a class. Each axis is cut into three bands, 0 to 3, 4 to 6 and 7 to 10, and a point is told by its band across and its band up. Every count will have 1 added, so no count is 0.00
2Point 1, the triangle at 2 8, is in band 0 to 3 across and band 7 to 10 up. Add 1 to its class's points and to those two bands in its row.10
3Point 2, the square at 7 8, is in band 7 to 10 across and band 7 to 10 up. Add 1 to its class's points and to those two bands in its row.20
4Point 3, the circle at 6 2, is in band 4 to 6 across and band 0 to 3 up. Add 1 to its class's points and to those two bands in its row.30
5Point 4, the triangle at 3 2, is in band 0 to 3 across and band 0 to 3 up. Add 1 to its class's points and to those two bands in its row.40
6The new point at 5 4 is in band 4 to 6 across and band 4 to 6 up. Each class is scored on those two bands alone, one at a time.40
7Triangles: 2 of the 4 points, 0 in the band across, 0 in the band up. Add 1 to each count and 3 × 1 to its points: 2/4 × (0 + 1)/5 × (0 + 1)/5 = 0.02.41
8Squares: 1 of the 4 points, 0 in the band across, 0 in the band up. Add 1 to each count and 3 × 1 to its points: 1/4 × (0 + 1)/4 × (0 + 1)/4 = 0.016.42
9Circles: 1 of the 4 points, 1 in the band across, 0 in the band up. Add 1 to each count and 3 × 1 to its points: 1/4 × (1 + 1)/4 × (0 + 1)/4 = 0.031.43
10Circles score highest, 0.031, so the new point becomes a circle. Each band cell is shaded in the class a new point there would get.43

In all, 4 points counted. The formula from section 4, nn, gives C=4C = 4 at n=4n = 4: the same.

where you meet it

The method is old, quick to train, and still offered by toolkits such as scikit-learn.

  • scikit-learn, a Python library for machine learning

    Its CategoricalNB tool counts, for each class, how often each value of each feature turns up. A feature is what is measured about each item; here, a point's band across and up. A smoothing number, alpha, is added to every count, and it is 1 unless told otherwise.

    source: scikit-learn's documentation, the user guide's section on naive Bayes and the CategoricalNB reference

  • junk mail

    In 1998 Mehran Sahami, Susan Dumais, David Heckerman and Eric Horvitz sorted email into junk and not junk this way. Each word was a feature, present or absent in a message. Adding hand-made phrases and clues beyond the words, such as the kind of address it came from, made the filter better still.

    source: Sahami, Dumais, Heckerman and Horvitz, A Bayesian Approach to Filtering Junk E-Mail, AAAI Workshop on Learning for Text Categorization, 1998

  • adding one

    Adding 1 to every count is old. In 1814 Pierre-Simon Laplace asked how likely the sun is to rise tomorrow, given it has risen every day so far. His answer adds 1 to the risings and 2 to the days, one for each outcome, rise or not, as this page adds 3 for its three bands.

    source: Laplace, Essai philosophique sur les probabilités, 1814, the rule of succession

the trianglescountshare
in band 7 to 10 across4 of 50.8
in band 7 to 10 up3 of 50.6
in both, guessed0.8 × 0.60.48
in both, counted2 of 50.4
The independence guess on section 1's triangles. Multiply their share across by their share up, and you guess 0.48 of them stand in the top right cell. Count them, and 2 of 5 do, 0.4. Close, but a guess.

what is used instead

When the features do depend on each other, the independence guess can mislead. k-nearest neighbours, on this site, looks at the points nearest the new point instead, so it needs no guess. It measures every point for each new point, where naive Bayes reads only its table.

how it compares

Naive Bayes beside k-nearest neighbours on the same points. One plane, two answers.

02468100246810
classpointsin band 4 to 6 acrossin band 7 to 10 upscore
triangles5030
squares1110.167
Naive Bayes with no smoothing. The triangles' empty band gives them 0, so the new point becomes a square.
02468100510
k-nearest neighbours with k = 3: the 3 points nearest the new point vote. The square is nearest, but the triangles at 1 9 and 8 9 come next and outvote it, so the new point becomes a triangle.

race them on one row of your own