
Understanding AI: Classification
We trade lines for probabilities, and try to answer simple yes-or-no questions, which will take us through some very important probability definitions.
Our first model is now behind us! And oh boy, there was a lot to unpack even for a measly line through a cloud of points, wasn't there? We got to discuss the nitty-gritty details of loss functions, how they relate to our assumptions about noise, and even how linear models can surprisingly handle very non-linear things.
But then, we ended with a nagging question about the kind of problem our model could actually be useful for.
You see, linear regression is designed to spit out a continuous output: a number that can take any value along a certain range, depending on the we feed the model. That's great for things like pinning down a physical value, but it's a little awkward for our recommendations engine. A movie rating of tells us nothing about whether Alice likes or dislikes the movie.
And therein lies the problem: regression answers a different kind of question. What we need here is something much more plain: a simple yes or no.
That's a different problem to tackle, called classification, which deals with discrete outputs: a small, fixed set of categories to choose from.
Which in our case, is just yes/no, or like/dislike, or maybe even /!
It seems drawing a line won't help in this situation.
...Or will it?

With a little twist in perspective, it just might!
Drawing a Boundary
Let's say we're looking at just two features for now: a movie's runtime, and its average rating from other viewers. Every movie Alice has watched becomes a point on a 2D plane, colored by whether she liked it (blue points) or not (red points):

The two sets of points are reasonably well separated in this example. There seems to be a clear pattern... almost as if... wait a second:

Clear as day, we can draw a dividing line!
This is what we call a decision boundary: a boundary that separates one class from the other.
Admittedly, drawing this line is a little more involved than before, and one option we can lean on is a classic algorithm called a Support Vector Machine (SVM), which seeks the best possible line so that it leaves the widest possible margin between the two classes.
Actually finding this optimal margin is gonna be a rabbit hole for another day!
In two dimensions, this separation looks like a simple straight line; if we push things into higher dimensions, the decision boundary will become a hyperplane, but the core idea remains the same.
And this simple trick - splitting a space in two - turns out to be surprisingly useful out there in the real world. Spam filters, credit approvals, medical screenings, fraud detection, even deciding whether an agent should run a certain command... an awful lot of everyday yes/no decisions are, at heart, about telling two groups of points apart. Sometimes a straight line is enough, like the one we just drew for Alice's movie taste.
Cool, isn't it?
That said, a line can only get us so far. Sometimes it isn't enough at all, and even when it is, it comes with some rough edges we can't just ignore. Let's take a closer look.
Thinking Backwards
For starters, there's the matter of meaning. A line separating Alice's tastes in movies gives us an answer, but not much of a story about the data we're working with. It feels more like a means to an end.
Perhaps the question of drawing a boundary is wrong in itself to begin with... but then, just what is the right question to ask?

How about this: rather than asking "where's the line that best separates these points?", we could ask "given a new point, which class is it more likely to have come from?".
That's a fundamentally different way of thinking about classification, because we rely on probability, rather than geometry. And in doing so, we'll see those decision boundaries emerge as a consequence of our framing, as if they were simply there, waiting to be seen and understood.
When put that way, it's easy to see that we're really asking for a very particular kind of number: the probability of a class being the correct one, given that we've observed some points. And since I said "given", that should immediately take you back to the previous article, where we learned how to write that:
A conditional probability: the probability of given .
Think about it. Isn't this exactly what we want out of our classifier? Not a hard yes or no, nor a line splitting a plane in two; we really want something like a score, a plain number telling us how likely each class is, given the information we have!
Compare that to our linear boundary from before: a point either landed on one side or the other, and that was the end of the story. There was no room for nuance, and we could end up with situations that looked somewhat dodgy. They say a picture is worth a thousand words, so for instance, look at this image:

That single blue point on the right seems to be pushing the entire linear decision boundary to the right, and closer to the red dots. But what if it was a wrong measurement? Or wrongly labelled? Or even a correct, but very unlikely result!
Here are a couple further examples where things may get complicated for lines to handle:

Yeah, some datasets will not have linear decision boundaries at all. You can clearly see that in the image above, where no straight line will ever separate that blue blob from the ring around it. And even when they might (there are some techniques to draw curves using linear methods, similar to what we saw last time), it could be impossible to cleanly separate all points to either side. For example, where would you draw the line here?

Yeah. Our line is rather rigid.
There's an even subtler issue at play - one that doesn't even need messy data to show up. You see, a hard boundary treats every point the same way, no matter how close they sit to the edge: a point right beside the line gets treated exactly the same as one miles away from it.
There's no room to say "hmm, well, I'm not so sure about this one".
A probability, on the other hand, captures that nuance for free. If we do the calculations and obtain something like , that tells a very different story than , even though both would earn the "yes" label from our old boundary-based approach.
Okay, that sounds rather convincing. We should try it! Oh, wait, right... there's but a tiny problem.

The thing is, we don't know what looks like. All we have is a pile of examples: pairs of drawn from Alice's movie history. So how the heck do we get from the examples to an actual probability?
Probability and Evidence
Luckily, there's a neat little piece of math that answers exactly this question: Bayes' theorem.
Rather than spelling it out however, I think it would be great if we can build an intuition around it first. We'll do it the way I like it best: with nothing more than a simple example and a couple drawings.
For that, let's imagine we flip two coins, and let's denote the number of tails we get by . There are only four equally likely outcomes, so we can just draw all of them:

It's easy to calculate probabilities by just inspecting this chart:
Nothing surprising so far. Now, suppose someone peeks at the result before we do, and gives us a little spoiler: at least one of the coins landed on tails. It's a new piece of evidence we didn't have beforehand! Let's just call it .
What's interesting about this new evidence is that it reduces our possible outcomes:

Aha! Now only 3 possibilities remain, each of those being equally likely. So we can now ask: given this evidence, what are the chances we actually got both tails? Just count, and the answer becomes apparent:
Before any evidence had been presented to us, we would have answered the same question with . Therefore, learning has done something remarkable: it has updated our belief about !

Bayes' Theorem
It seems we're onto something! What would be really useful now is if we could generalize this to some kind of fact about evidence being presented to us in general, regardless of the setting. And sure as hell, there's quite an easy way to do that. Again, by means of a couple drawings, we'll find something that's very general and useful.
Suppose we have two events, and .
In the language of probability and statistics, events are things that may or may not happen.
For instance, could be "Alice likes a movie" and "that movie is longer than two hours". Or, going back to our coins, could be "at least one tails" (our evidence from before!) and "the first flip is heads".
We'll draw them as two rectangles reflecting the probability of their occurrence, with their areas being and respectively:

As you can see, the two rectangles overlap a little. That little section in the middle represents the probability of both and happening at once, so it's what we call their joint probability, which we'll write as . Notice we're borrowing notation from set theory, and that's not a coincidence! Each list of possible outcomes is a set, particularly a subset of all possible outcomes, and two such subsets may just happen to overlap!
In our coin-flipping example, "getting at least one tails" yields the possible results of , and then "getting the first flip to be heads" means are the only remaining possible results. And if both things were to happen at once, all we need to do is take the intersection of those sets, so would be our only outcome matching both conditions.
The trick is quite visible once we have this picture at hand, and it's just the result of viewing the overlap from two different angles.
If we know that has happened, we can ask "what's the probability that also happened?". That's of course the conditional probability we met before. And if we know that happened instead, we just flip the question, and look for .
Both are easy to draw. If we know happened, then anything that's outside the blue rectangle could not have happened, so the probability of also happening is just the overlapping area! The same argument works the other way around, which in our diagram looks like this:

We can describe that overlap in two equivalent ways then, matching these two views. As a slice of , it's how much of 's area is also covered by , which is exactly the probability of given , scaled to the size of (because if we know happened, then we rule out anything that is not ):
But we could just as well look at that same sliver as a slice of instead:
Both expressions describe the exact same overlap, so they have to be equal:
And with nothing more than a small rearrangement:
That's all! And believe it or not, this is so general that it's actually a theorem: Bayes' theorem, pulled out of nothing more than a few overlapping rectangles!

See if you can apply this to the coin flip example from before!
Finally, we'll just adjust the notation a bit: we swap for (some outcome or class we care about), and for (the evidence, or features, we actually observe):
Which is the exact form we'll be using from here on.
Fantastic! That wraps up the theory. Fun stuff, but how do we build a classifier out of this?
Building a Classifier
Armed with Bayes' theorem, we can bring it back to the question of determining whether Alice will like a movie or not. Pay attention to the question we're asking: based on the average rating and runtime (which we can call and ), will Alice like or dislike the movie?
And since we now have a new language to describe this, let's put it to good use! What we're really after then are these probabilities:
I'll write for simplicity, but bear in mind there are two variables at play here.
Except, we already know we can't just read these numbers off directly, and that's exactly where Bayes' theorem will be helpful. Here's the recipe once again:
So to actually get our hands on , we'll need . And here's the good news: unlike , its counterpart we can get from our pile of examples!
Why? Simple - because it answers a different question, one that's easy to look at directly: what does a movie that Alice liked look like?
Or in even more straightforward terms:
Given a movie that Alice liked, what's the probability it has a given runtime and rating?
The key idea is that we already know which movies she liked, so we can focus on those, momentarily forget about the disliked movies, and study one cloud of points in isolation. In other words, that cloud of points is our window into .
And that cloud of points tells us a story about what's typical among the movies she enjoys, and what's unusual. In our diagram below, the liked movies seem to cluster around a point where both and are low, so you can already get the feeling that a liked movie with high runtime and rating is unlikely on its own!
And of course, we can do the very same with the movies she didn't enjoy.

That quantity has a name you might remember from last time: the likelihood. Back then, it told us how well some parameters explained our data. Here, it's the class that does the explaining!
Of course, we'll be using Bayes' theorem as the bridge to get to our desired result. And for that, we need the two other pieces of the recipe, which are much more straightforward:
- is just how common each class is to begin with. If Alice liked 4 out of every 10 movies she's watched, then . It's called the prior or a priori probability: what we'd guess before looking at any features.
- is how common a movie with those features () is overall, whether Alice likes it or not. It's the same number for both classes, so it scales both results equally and can never change which one comes out bigger. Its only job is turning them into proper probabilities that add up to , and we'll deal with it at the very end.
Notice how the prior sort of pulls on the result. Say Alice is a picky viewer, and only liked 1 out of every 10 movies she's watched. Then a movie that looks equally typical for both classes should still lean toward "dislike", simply because dislikes are far more common to begin with. That's actually a great way to summarize what we're doing:
Bayes balances how typical a result looks against how common its class is
So once we have all the ingredients, we compute the probabilities for both classes, and , and we just pick whichever comes out bigger. These two are called posteriors or a posteriori probabilities: our belief about the class after looking at the features, as opposed to the prior, which is what we believed before. Two numbers packed with meaning, and no line to draw by hand!
That said, a boundary still exists, only that it's implicit: it's comprised of all the points where both probabilities are tied:
Since the two must add up to , that means both are exactly . Cross that curve, and the winner flips. And while the curve sure as hell exists, we never have to draw it explicitly, because it's much easier to calculate a couple probabilities, and simply compare them.
That's also why this approach is much better suited for the situations that gave our straight line a hard time. The boundary has no shape of its own: it simply follows wherever the probabilities tie, so it can bend, or even wrap around a whole cluster, depending on how each class is distributed.
Plus, as an added bonus, nothing in the recipe cares about having only two classes! With three genres, we'd compute three posteriors and pick the biggest one, while a single line can only split a plane in two.
Okay, that was surely a mouthful, but once the dust settles, it looks quite simple! We just compute some probabilities, and we're done!
For once, it could really be this simple, right? Right?

Well... in general, it isn't.
Independence
Yeah, sorry, there's always a catch. I don't do this on purpose though! It's just how things are!
This time, the catch has to do with the number of random variables at play.
I know we didn't formally define what random variables are, but we need not worry too much about this now, and we'll come back to this definition soon.
For now, just imagine it's a placeholder for a value that will later be sampled. Like the result of a die roll: we don't know what value we'll obtain. But we know what to expect from it, as we've already studied the distribution of the possible results! That is a property of the random variable - the placeholder - rather than of the observed result.
As I noted earlier, isn't just one number in our little example, but actually two bundled together: runtime and rating. So is really asking how those two behave together, for each class.
Knowing each of them on its own isn't enough. Here's a little mental exercise to make sense of this idea: say half of the movies Alice liked are long, and half of them are high-rated. How many are both long and high-rated?
- It could be a quarter, if the two have nothing to do with each other...
- But half, if every long movie happens to be a high-rated one.
As you can see, we can have two very different stories here! And which is the correct one is a matter of dependence (or independence) between the features.
Indeed, what we need is the joint probability of observing a movie with a given runtime and rating, given it has class . Using the same overlap trick from before (with just tagging along in every term), we can write that as:
And that factor is the catch: how the second feature behaves can change depending on the value of the first, so we'd need to know it for every possible value, and for each class.
It only gets worse as features pile up: with twenty of them, we'd be mapping a landscape we'd never have enough data to cover. That nastier consequence has a spooky name: the curse of dimensionality.
I know this might be a little confusing at this point. We'll continue working on our understanding of probability as we move forward, but the important takeaway for now is easy to subscribe to.
We're gonna need a shortcut.
The classic escape hatch is as simple as it is bold: just assume the features are independent, given the class we're studying. Yes, just like you heard! We turn a blind eye and pretend that within the movies Alice liked, rating and runtime have nothing to do with each other (and the same goes for the movies she didn't like).

Since knowing one tells us nothing new about the other, so that troublesome last factor collapses:
And the joint probability turns into a plain product of individual chances:
That simplification allows us to treat each feature separately, and gives us the ability to estimate those probabilities from the data quite easily, one dimension at a time.
Is this actually a good assumption? Probably not! Longer movies might map to certain genres, which might in turn affect their ratings... but the curious thing is that this strategy, wrong as it may be, tends to work remarkably well in practice anyway!
Remember, reality is not perfect!
If you picture each class as a cloud of points, independence means the cloud can stretch sideways or up and down, but never tilt along a diagonal. Models that allow tilting do exist, but they take some extra work.
This assumption is what gives the method we're about to look at its name: Naive Bayes. The "naive" is a polite way of saying "we know this assumption is wrong, but we'll run with it regardless".
Gaussian Naive Bayes
Before we jump into an example though, we need a way to describe what a "typical" liked movie looks like, one feature at a time. Independence lets us treat features separately, but it doesn't tell us how to describe each one! That's a separate choice!
And we already have the perfect tool for the job: the normal distribution from last time! Using it here is what's known as Gaussian Naive Bayes, though in principle, any other distribution would work too.
A movie's average rating is quite literally an average over many opinions, so it's not a stretch to expect ratings to cluster around some typical value and thin out the further we stray from it. Runtimes aren't averages of anything, but most movies still hover around some typical length, with very short and very long ones being rare, so a bell is a reasonable guess there too. To be clear, this is a modeling choice rather than a law of nature: it's convenient, and it tends to be good enough. All we need is a normal distribution per feature and per class, each described by its mean (the center) and its standard deviation (the spread).
We'll be reading off the height of these bells at a given point, and as we already know, strictly speaking, that height is not a probability. For a measurement that can take any value, the chance of landing on one exact number is essentially zero. But we don't need probabilities, since we'll only be comparing heights for different classes at the same point.
In fact, Bayes' theorem works just as well when densities take the place of probabilities, so we can plug those heights straight into the recipe.
A Worked Example
Alright, it's time to see this in action!
First, we're gonna need some data to work with: movies Alice liked, and movies she didn't, each with their own runtime and rating. Let's generate some synthetic points, drawing each feature from a bell curve of its own:
The two numbers in each rng.normal call are just the mean and the standard deviation. So in this made-up world, movies Alice likes tend to be shorter and better rated than the ones she doesn't, and the plot shows it: teal for the movies she liked, magenta for the ones she didn't.
It's the same kind of picture we started this article with, only now we know how it was made.
All that's left is to figure out which bell fits best for each feature and each class, meaning a center and a spread. And the natural way to find them is to just measure the data we have: its average, and how much it spreads around that average. Without going into much more detail, we can do this with a couple handy functions:
That's the entire "training" step! Notice there's no loss function to minimize: we're just describing what each class looks like.
And admittedly, those
.mean()and.std()are doing some heavy lifting in all this mess. We'll see what exactly they are doing in a couple articles time.
Still, this information is enough to classify a brand new movie. Here's the plan:
- For each class, check how typical the new movie's runtime is, by reading the height of that class's runtime bell at that point. Do the same for the rating. Since we assume the features are independent, we just multiply the two heights, and get a single "typicality score" for the class.
- Multiply that score by the class's prior, meaning how common that class was to begin with.
- We're left with one number per class, each proportional to the probability we're after. And since a movie is either liked or disliked (never both), all that's left is to rescale them so they add up to : just divide each by the total. That total is what was there for!
Here's all of that, in code :
Let's try it out on three new movies: a short, highly rated one, a long, poorly rated one, and something in between:
As promised, each answer is a plain number between and , not a side of a line. The first movie is an easy yes, and the last one an easy no.
But look at the one in the middle: about is a leaning no, with a fair amount of doubt attached to it. A hard boundary would have given it the exact same "dislike" as the last movie, no questions asked. So that's precisely the nuance we were missing before!
Take those numbers with a grain of salt though. Since our independence assumption isn't really true, Naive Bayes tends to be a little overconfident. But the ranking is usually right, and that's all we need to pick the bigger one.
If we plot the resulting decision boundary (the curve where ) against our points, here's what we get:
Would you look at that! A curved boundary, emerging naturally out of comparing two probabilities! Nobody drew this line by hand, nor searched for the widest margin between classes. It just... emerged out of the math, once we framed the problem differently.
It isn't perfect, though. A few movies end up on the wrong side, and with these numbers the classifier gets roughly 94% of them right. But that's perfectly fine, because as we've noted multiple times (and will continue to do so):
Real data is noisy, and no model will ever be perfect.
And so, we've successfully answered this new question of classification, without having to draw any lines. Our machinery is probability itself, and we've now shown it can do the job just fine!
Granted, we cooked up this data to follow our assumptions to the letter, so this was the best-case scenario. Real data won't be this cooperative, though as we saw, Naive Bayes tends to cope remarkably well anyway.
Summary
I believe that's enough for today!
Our plain yes or no question definitely threw us for a loop, as we had to delve into new probability concepts in the form of the powerful Bayes' theorem. It's a handy tool, although it might feel a bit unintuitive at times.
A good way to remember its expression is through the overlapping boxes! I can assure you that diagram has saved me a time or two.
While a line could be useful as a decision boundary after all, our main motivation to switch to probabilities had to do with confidence, as a line treats points close to and far from the boundary exactly the same. Sure, it splits the data - but it doesn't tell us how sure we can be.
We glossed over a few things along the way, on purpose: how to actually estimate a good prior when we don't have Alice's entire history to lean on, and what happens when the independence assumption fails badly. These are very much real topics, just not for today.
Clearly, not everything is about drawing lines, as this article shows. But that doesn't mean we need to abandon our little friends just yet!
In fact, next time, we'll go back to lines for a bit - but with a twist that turns them into proper probabilities too. And along the way, we'll get to meet the tool that will enable us to minimize loss functions, even when we can't find closed-form solutions.
Until then!
Did you find this content useful?
Support Frank Mangone by sending a coffee. All proceeds go directly to the author.