---
title: 'Understanding AI: Classification'
description: >-
  We trade lines for probabilities, and try to answer simple yes-or-no
  questions, which will take us through some very important probability
  definitions.
author: Frank Mangone
date: '2026-11-26'
lang: en
series: understanding-ai
tags:
  - artificialIntelligence
  - machineLearning
  - mathematics
  - probabilityAndStatistics
  - classification
url: 'https://arkana.blog/en/blog/understanding-ai/classification/'
---

# Understanding AI: Classification

Our [first model](https://arkana.blog/en/blog/understanding-ai/regression) 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 $x$ 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](https://arkana.blog/en/blog/understanding-ai/an-introduction#an-examination-of-data). A movie rating of $6$ 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 $0$/$1$!

It seems drawing a line won't help in this situation.

...Or will it?

<figure>
	<img
		src="https://arkana.blog/images/understanding-ai/classification/let-him-cook.webp"
		alt="Let him cook meme" 
		title="Hollup, let him cook..."
	/>
</figure>

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):

<figure>
	<img
		src="https://arkana.blog/images/understanding-ai/classification/two-class-scatter.png"
		alt="A scatterplot of Alice's preferences" 
		title="[zoom]"
	/>
</figure>

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:

<figure>
	<img
		src="https://arkana.blog/images/understanding-ai/classification/decision-boundary.png"
		alt="A line separating the two sets of points" 
		title="[zoom] Boom shaka lakka!"
	/>
</figure>

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](https://en.wikipedia.org/wiki/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?

<figure>
	<img
		src="https://arkana.blog/images/understanding-ai/classification/to-be.jpg"
		alt="Shakespeare holding a skull" 
		title="To be or not to be... Wait that's lowkey a classification question, no?"
	/>
</figure>

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 $y$ 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](https://arkana.blog/en/blog/understanding-ai/regression#gaussian-errors), where we learned how to write that:

$$
P(y \mid x)
$$

A **conditional probability**: the probability of $y$ given $x$.

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:

<figure>
	<img
		src="https://arkana.blog/images/understanding-ai/classification/outlier.png"
		alt="An outlier skewing the linear decision boundary" 
		title="[zoom] Remember, the y is the label here, so the color of the points"
	/>
</figure>

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:

<figure>
	<img
		src="https://arkana.blog/images/understanding-ai/classification/linear-problems.png"
		alt="Situations where a line is not enough" 
		title="[zoom]"
	/>
</figure>

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](https://arkana.blog/en/blog/understanding-ai/regression#beyond-straight-lines)), it could be impossible to cleanly separate all points to either side. For example, where would **you** draw the line here?

<figure>
	<img
		src="https://arkana.blog/images/understanding-ai/classification/overlapping-classes.png"
		alt="Two overlapping clusters of blue and red points, with a dashed line and a question mark"
		title="[zoom]"
	/>
</figure>

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 $P(\text{like} \mid x) = 0.51$, that tells a very different story than $P(\text{like} \mid x) = 0.99$, 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.

<figure>
	<img
		src="https://arkana.blog/images/understanding-ai/classification/what-now.jpg"
		alt="Stressed guy meme"
		title="Oh no, what now?"
	/>
</figure>

The thing is, we **don't know** what $P(y \mid x)$ looks like. All we have is a pile of examples: pairs of $(x, y)$ 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 $X$. There are only **four equally likely outcomes**, so we can just draw all of them:

<figure>
	<img
		src="https://arkana.blog/images/understanding-ai/classification/two-coins.png"
		alt="Grid of the four equally likely outcomes of flipping two coins, labeled with their X value"
		title="[zoom]"
	/>
</figure>

It's easy to calculate probabilities by just inspecting this chart:

$$
P(X=0) = P(X=2) = \frac{1}{4}, \quad P(X=1) = \frac{1}{2}
$$

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 $A$.

What's interesting about this new evidence $A$ is that it **reduces our possible outcomes**:

<figure>
	<img
		src="https://arkana.blog/images/understanding-ai/classification/two-coins-evidence.png"
		alt="Same grid, with the outcome of two heads crossed out"
		title="[zoom]"
	/>
</figure>

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:

$$
P(X=2 \mid A) = \frac{1}{3}
$$

Before any evidence had been presented to us, we would have answered the same question with $P(X=2) = 1/4$. Therefore, learning $A$ has done something remarkable: it has **updated our belief** about $X$!

<figure>
	<img
		src="https://arkana.blog/images/understanding-ai/classification/wololo.jpeg"
		alt="Priest from AOE2"
		title="We've been wololo'd!"
	/>
</figure>

### 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, $A$ and $B$.

> In the language of probability and statistics, events are things that may or may not happen.
> 
> For instance, $A$ could be "Alice likes a movie" and $B$ "that movie is longer than two hours". Or, going back to our coins, $A$ could be "at least one tails" (our evidence from before!) and $B$ "the first flip is heads".

We'll draw them as two rectangles reflecting the **probability of their occurrence**, with their areas being $P(A)$ and $P(B)$ respectively:

<figure>
	<img
		src="https://arkana.blog/images/understanding-ai/classification/probabilities.png"
		alt="Two overlapping rectangles representing events A and B, with area proportional to their probability"
		title="[zoom]"
	/>
</figure>

As you can see, the two rectangles **overlap** a little. That little section in the middle represents the probability of **both** $A$ and $B$ happening at once, so it's what we call their **joint probability**, which we'll write as $P(A \cap B)$. 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 $\{\text{HT}, \text{TH}, \text{TT}\}$, and then "getting the first flip to be heads" means $\{\text{HH}, \text{HT}\}$ 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 $\{\text{HT}\}$ 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 $B$ has happened, we can ask "what's the probability that $A$ also happened?". That's of course the conditional probability $P(A \mid B)$ we met before. And if we know that $A$ happened instead, we just **flip the question**, and look for $P(B \mid A)$.

Both are easy to draw. If we know $B$ happened, then anything that's **outside the blue rectangle could not have happened**, so the probability of $A$ also happening is just the overlapping area! The same argument works the other way around, which in our diagram looks like this:

<figure>
	<img
		src="https://arkana.blog/images/understanding-ai/classification/conditional.png"
		alt="The same two rectangles, with the overlap highlighted once as a fraction of A and once as a fraction of B"
		title="[zoom]"
	/>
</figure>

We can describe that overlap in **two equivalent ways** then, matching these two views. As a slice of $A$, it's how much of $A$'s area is also covered by $B$, which is exactly the probability of $B$ **given** $A$, scaled to the size of $A$ (because if we know $A$ happened, then we rule out anything that is **not** $A$):

$$
P(A \cap B) = P(B \mid A) \cdot P(A)
$$

But we could just as well look at that same sliver as a slice of $B$ instead:

$$
P(A \cap B) = P(A \mid B) \cdot P(B)
$$

Both expressions describe the **exact same overlap**, so they **have to be equal**:

$$
P(B \mid A) \cdot P(A) = P(A \mid B) \cdot P(B)
$$

And with nothing more than a small rearrangement:

$$
P(A \mid B) = \frac{P(B \mid A) \cdot P(A)}{P(B)}
$$

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!

<figure>
	<img
		src="https://arkana.blog/images/understanding-ai/classification/simple-math.png"
		alt="It's simple math meme"
		title="Yeah, sure"
	/>
</figure>

> See if you can apply this to the coin flip example from before!

Finally, we'll just adjust the notation a bit: we swap $A$ for $y$ (some outcome or **class** we care about), and $B$ for $x$ (the evidence, or **features**, we **actually observe**):

$$
P(y \mid x) = \frac{P(x \mid y) \cdot P(y)}{P(x)}
$$

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 $x_1$ and $x_2$), 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:

$$
P(\text{like} \mid x_1, x_2) \quad \quad P(\text{dislike} \mid x_1, x_2)
$$

> I'll write $P(\text{like} \mid x)$ 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:

$$
P(y \mid x) = \frac{P(x \mid y) \cdot P(y)}{P(x)}
$$

So to actually get our hands on $P(\text{like} \mid x)$, we'll need $P(x \mid \text{like})$. And here's the good news: unlike $P(\text{like} \mid x)$, **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** $P(x \mid \text{like})$.

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 $x_1$ and $x_2$ 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.

<figure>
	<img
		src="https://arkana.blog/images/understanding-ai/classification/one-category.png"
		alt="What we'd be looking at if we focus on only one category at a time"
		title="[zoom]"
	/>
</figure>

That quantity has a name you might remember from [last time](https://arkana.blog/en/blog/understanding-ai/regression#maximum-likelihood): 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:

- $P(y)$ is just **how common each class is** to begin with. If Alice liked 4 out of every 10 movies she's watched, then $P(\text{like}) = 0.4$. It's called the **prior** or **a priori probability**: what we'd guess before looking at any features.
- $P(x)$ is how common a movie with those features ($x$) 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 $1$, 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, $P(\text{like} \mid x)$ and $P(\text{dislike} \mid x)$, 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:

$$
P(\text{like} \mid x) = P(\text{dislike} \mid x)
$$

Since the two must add up to $1$, that means both are exactly $0.5$. 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**?

<figure>
	<img
		src="https://arkana.blog/images/understanding-ai/classification/krillin.jpg"
		alt="Krillin with a serious face"
		title="I already know where this is going..."
	/>
</figure>

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](https://arkana.blog/en/blog/understanding-ai/humble-beginnings#probability-and-statistics) 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, $x$ isn't just one number in our little example, but actually **two** bundled together: runtime and rating. So $P(x \mid y)$ 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 $y$. Using the same overlap trick from before (with $y$ just tagging along in every term), we can write that as:

$$
P(x_1 \cap x_2 \mid y) = P(x_1, x_2 \mid y) = P(x_2 \mid x_1, y) \cdot P(x_1 \mid y)
$$

And that $P(x_2 \mid x_1, y)$ 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).

<figure>
	<img
		src="https://arkana.blog/images/understanding-ai/classification/sure.png"
		alt="I have no idea what I'm doing meme"
		title="Sure, sure"
	/>
</figure>

Since knowing one tells us nothing new about the other, so that troublesome last factor collapses:

$$
P(x_2 \mid x_1, y) = P(x_2 \mid y)
$$

And the joint probability turns into a plain **product of individual chances**:

$$
P(x_1, x_2 \mid y) \approx P(x_1 \mid y) \cdot P(x_2 \mid y)
$$

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](https://arkana.blog/en/blog/understanding-ai/regression#why-squares)! 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** $\mu$ (the center) and its **standard deviation** $\sigma$ (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:

```python
import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(42)

n = 40

x1_like = rng.normal(100, 15, n)
x2_like = rng.normal(7.5, 0.8, n)

x1_dislike = rng.normal(130, 20, n)
x2_dislike = rng.normal(5.5, 1.0, n)

plt.scatter(x1_like, x2_like, color="teal", label="liked")
plt.scatter(x1_dislike, x2_dislike, color="magenta", label="disliked")
plt.xlabel("runtime (minutes)")
plt.ylabel("average rating")
plt.legend()
plt.show()
```

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:

```python
# x1_like, x2_like, x1_dislike, x2_dislike defined above

mu_x1_like, sigma_x1_like = x1_like.mean(), x1_like.std()
mu_x2_like, sigma_x2_like = x2_like.mean(), x2_like.std()

mu_x1_dislike, sigma_x1_dislike = x1_dislike.mean(), x1_dislike.std()
mu_x2_dislike, sigma_x2_dislike = x2_dislike.mean(), x2_dislike.std()
```

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:

1. 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.
2. Multiply that score by the class's **prior**, meaning how common that class was to begin with.
3. 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 $1$: just divide each by the total. That total is what $P(x)$ was there for!

Here's all of that, in code :

```python
from scipy.stats import norm

# mu_*, sigma_* defined above

def posterior_like(x1, x2, prior=0.5):
    # norm.pdf(x, mu, sigma) reads the height of the bell curve at x
    typical_like = norm.pdf(x1, mu_x1_like, sigma_x1_like) * norm.pdf(x2, mu_x2_like, sigma_x2_like)
    typical_dislike = norm.pdf(x1, mu_x1_dislike, sigma_x1_dislike) * norm.pdf(x2, mu_x2_dislike, sigma_x2_dislike)

    # we generated as many liked as disliked movies, so both classes start out equally common
    score_like = typical_like * prior
    score_dislike = typical_dislike * (1 - prior)
    return score_like / (score_like + score_dislike)
```

Let's try it out on three new movies: a short, highly rated one, a long, poorly rated one, and something in between:

```python
# Uses posterior_like from the cell above

movies = {
    "short and highly rated": (95, 7.8),
    "in between": (115, 6.5),
    "long and poorly rated": (140, 4.5),
}

for name, (runtime, rating) in movies.items():
    p = posterior_like(runtime, rating)
    print(f"{name:>24}: P(like | x) = {p:.2f}")
```

As promised, each answer is a plain number between $0$ and $1$, 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 $0.34$ 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 $P(\text{like} \mid x) = 0.5$) against our points, here's what we get:

```python
# Uses the data, imports and posterior_like from the cells above

# A grid of (runtime, rating) pairs covering the whole plot
g1, g2 = np.meshgrid(np.linspace(50, 190, 300), np.linspace(2, 10, 300))
p_like = posterior_like(g1, g2)

# Tint each side, and draw the curve where P(like | x) = 0.5
plt.contourf(g1, g2, p_like, levels=[0, 0.5, 1], colors=["magenta", "teal"], alpha=0.1)
plt.contour(g1, g2, p_like, levels=[0.5], colors="black")

plt.scatter(x1_like, x2_like, color="teal", label="liked")
plt.scatter(x1_dislike, x2_dislike, color="magenta", label="disliked")
plt.xlabel("runtime (minutes)")
plt.ylabel("average rating")
plt.legend()
plt.show()
```

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](https://arkana.blog/en/blog/understanding-ai/how-to-train-your-model-part-1), 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!

## Key concepts

### Classification
Predicts a **category** instead of a number. A **decision boundary** splits the classes, but says nothing about how **confident** we are.

### Conditional probability
$P(y \mid x)$ is the probability of a class **given** the features we observe. It's what we really want from a classifier.

### Bayes' theorem
Turns the **likelihood** $P(x \mid y)$, which we can read off our data, into the $P(y \mid x)$ we care about.

### Prior and posterior
The **prior** is how common a class is to begin with. The **posterior** is our belief about it **after** seeing the features.

### Naive Bayes
Assume the features are **independent** given the class. It's technically wrong, but it makes the likelihood simple to estimate, and works remarkably well.

### Probabilities over boundaries
Comparing posteriors gives a boundary that can **curve**, plus a measure of **confidence**. Just remember: it tends to be a bit overconfident.
