naive 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.
| class | points | in band 4 to 6 across | in band 7 to 10 up | score |
|---|---|---|---|---|
| triangles | 5 | 0 | 3 | 0 |
| squares | 1 | 1 | 1 | 0.167 |
| class | points | in band 4 to 6 across | in band 7 to 10 up | score |
|---|---|---|---|---|
| triangles | 5 | 0 + 1 | 3 + 1 | 0.052 |
| squares | 1 | 1 + 1 | 1 + 1 | 0.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.
| triangles | 5 | 0 | 3 | 0 |
|---|---|---|---|---|
| squares | 1 | 1 | 1 | 0.167 |
| triangles | 5 | 0 + 1 | 3 + 1 | 0.052 |
|---|---|---|---|---|
| squares | 1 | 1 + 1 | 1 + 1 | 0.042 |
| triangles | 5 | 0 + 2 | 3 + 2 | 0.069 |
|---|---|---|---|---|
| squares | 1 | 1 + 2 | 1 + 2 | 0.031 |
| triangles | 5 | 0 + 3 | 3 + 3 | 0.077 |
|---|---|---|---|---|
| squares | 1 | 1 + 3 | 1 + 3 | 0.027 |
| triangles | 5 | 0 + 4 | 3 + 4 | 0.081 |
|---|---|---|---|---|
| squares | 1 | 1 + 4 | 1 + 4 | 0.025 |
| triangles | 5 | 0 + 5 | 3 + 5 | 0.083 |
|---|---|---|---|---|
| squares | 1 | 1 + 5 | 1 + 5 | 0.023 |
step 1 of 11
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.
step 2 of 11
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.
step 7 of 11
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.
step 8 of 11
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.
step 9 of 11
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.
step 10 of 11
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.
step 11 of 11
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.
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- cut each axis into three bandsPython lines 10 and 11
- for each point, count its band across and its band up in its class's rowPython lines 14, 15, 16, 17 and 18
- find the new point's bandsPython line 19
- score each class: its share of the points times its share in each bandPython lines 21, 24, 25, 26 and 27
- 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 points counts exactly , so the points sit on the line.
points counted, ten times more at each mark up
, 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
| points counted | time | |
|---|---|---|
| 1,000 | 1,000 | about 1 microsecond |
| 100,000 | 100,000 | about 100 microseconds |
| 10,000,000 | 10,000,000 | about 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 points costs the same, 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.
| averageevery set of points, wherever they stand | |
|---|---|
| points counted | |
| how the points counted grow in each case | |
| tight, | |
| ceiling, | |
| floor, | |
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.
| points | smoothing count | points counted |
|---|---|---|
| 4 | 0 | 4 |
| 4 | 2 | 4 |
| 6 | 1 | 6 |
where the formula comes from
The count above, and the score, each worked out in small steps naming the line it comes from.
the move: see the counting
the line:point class band across band up 2 8 triangle 0 to 3 7 to 10 7 8 square 7 to 10 7 to 10 6 2 circle 4 to 6 0 to 3 3 2 triangle 0 to 3 0 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.
the move: one for each point
the line:why it is allowed: is the points counted. By line 1, one for each of the points.
guess it, thenthe move: add the ones
the line:why it is allowed: By line 2, ones add up to . For the four points, 4.
guess it, thenthe move: any set, any smoothing
the line: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.
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 3, is , so it is at most . Bounds still matter: they name how fast the count grows, as in section 3's grid.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 5, is at most 1 times .
guess it, thenthe move: a floor
the line:why it is allowed: By line 3, is at least too.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 7, never drops below 1 times .
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 6 and 8 bound by the same growth, .
guess it, then
try it on small inputs: over every set of 4 points, wherever they stand, the average is
the move: the triangles' score
the line:share worked what it is 5/6 5 of 6 the triangles, of all the points (0 + 1)/(5 + 3) 1 of 8 in band 4 to 6 across, smoothed (3 + 1)/(5 + 3) 4 of 8 in 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: is the triangles' score in section 1, with a smoothing count of 1. The table shows where each share comes from.
the move: multiply
the line: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.
guess it, thenthe move: the naive guess
the line: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.
guess it, thenthe move: read it as Bayes' top
the line: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 . Write so that every piece is a chance. the move: count the sits each way
the line:why it is allowed: Question 1's first line, the sits with fruit over all the sits.
the move: write each count as a share of its bags
the line:piece with 10 bags of fruit what it is 0.9 the chance of a sit, given fruit 10 bags with fruit 0.2 the chance of a sit, given no fruit 90 bags 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: is 9 tenths of : the chance of a sit given fruit, times the bags with fruit. In the same way, 2 tenths of the other bags get a sit.
the move: divide top and bottom by 100
the line:why it is allowed: Top and bottom shrink alike, so the share is unchanged. over 100 is the chance of fruit, and 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.
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.
guess it, thenthe move: the same bottom
the line: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.
guess it, thenthe move: score the squares
the line:class top triangles 5/96 squares 4/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.
guess it, thenthe move: divide by the bottom
the line: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.
guess it, then
try it with a small : at , line 1 gives , 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.
| step | what happens | points counted | classes scored |
|---|---|---|---|
| 1 | 4 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. | 0 | 0 |
| 2 | Point 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. | 1 | 0 |
| 3 | Point 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. | 2 | 0 |
| 4 | Point 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. | 3 | 0 |
| 5 | Point 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. | 4 | 0 |
| 6 | The 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. | 4 | 0 |
| 7 | Triangles: 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. | 4 | 1 |
| 8 | Squares: 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. | 4 | 2 |
| 9 | Circles: 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. | 4 | 3 |
| 10 | Circles 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. | 4 | 3 |
In all, 4 points counted. The formula from section 4, , gives at : 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 triangles | count | share |
|---|---|---|
| in band 7 to 10 across | 4 of 5 | 0.8 |
| in band 7 to 10 up | 3 of 5 | 0.6 |
| in both, guessed | 0.8 × 0.6 | 0.48 |
| in both, counted | 2 of 5 | 0.4 |
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.
| class | points | in band 4 to 6 across | in band 7 to 10 up | score |
|---|---|---|---|---|
| triangles | 5 | 0 | 3 | 0 |
| squares | 1 | 1 | 1 | 0.167 |