Python + AI/ML · Tutorial 9 of 12
Classification Models, explained for beginners
By the FUTEAC Team · 23 November 2026 · 14 min read · Beginner
In short
Classification sorts records into categories. You show a model labelled examples, and it learns the boundary between them. This tutorial fits a logistic regression model on twelve students: study hours and practice tests predict pass or fail. You will read its probabilities, check it with a confusion matrix, and see why 75 percent accuracy can still be a useless model.
- Classification predicts a category, regression predicts a number. Pass or fail, spam or not spam, setosa or versicolor: classification. Exam score, house price, temperature: regression.
- A classifier draws a boundary, not a line through the points. Logistic regression finds the line that best separates the passing students from the failing ones, then reports a probability for each side.
- A probability is more useful than a bare label. Our model does not just say "pass", it says "99 percent chance of passing" for one student and "12 percent" for another. The number tells you how sure it is.
- Accuracy alone can lie. A model that predicts "pass" for every student scores 75 percent on our data and catches none of the three failing students. A single accuracy number hides that failure completely.
- A confusion matrix shows what accuracy hides. It counts the four outcomes separately: correct passes, correct fails, and the two kinds of mistake. Read it before you trust any accuracy.
- This tutorial feeds the AI & Machine Learning: First Steps course (/course/ai-ml-first-steps) and the Classification Models (/skill/classification) skill.
Before you start
What is classification, in one sentence?
Classification answers a question whose answer is a category. Is this email spam or not spam? Does this student pass or fail? Is this flower a setosa, a versicolor or a virginica? The answer is a label, not a number, and that single fact decides the whole approach.
Think of a teacher sorting exam scripts into two piles. She has marked a hundred scripts before, and she knows each student's study hours and practice tests. A new script arrives, and she needs a pile for it: pass or fail. She does not predict a score. She looks at the pattern in her marked scripts and sorts the new one. Classification is that habit, written as code.
The simplest picture is a boundary. Plot the twelve students with study hours on one axis and practice tests on the other, and colour each dot pass or fail. The failing students cluster in one corner, the passing students everywhere else. A classifier draws a line between the two clusters. A new student lands on one side of the line or the other, and that side is the prediction. The model is the boundary. Training is finding where the boundary should sit.
That is also the difference from regression, which you met in item 67. Regression fits a line through the points and reads a number off it. Classification draws a boundary between groups and reads a label off it. Same data, same two inputs, different question, different answer. If your answer is a label, reach for classification. If it is a number, reach for regression.
Binary or multi-class: how many categories?
Classification comes in two shapes, and the shape decides what the output looks like.
Binary classification has two categories: pass or fail, spam or not spam, sick or healthy. This tutorial is binary. The model answers one question, "which of the two?", and it can also answer a richer question, "how likely is each?", which is where probabilities come in.
Multi-class classification has three or more: the iris flowers from item 33 have three species, setosa, versicolor and virginica. The idea is the same, one boundary per pair of categories, but the bookkeeping grows. Start binary, as this tutorial does, and multi-class is the same idea with more boundaries.
There is one more shape beginners meet and should recognise: multi-label, where one record can carry several labels at once, such as a news article tagged both "sport" and "local". This tutorial does not cover it. If your problem allows more than one true label per record, you have a multi-label problem, and the binary tools here need adapting.
The data: the same twelve students, a new question
The data is the same twelve students from item 67: hours studied, practice tests taken, and the exam score out of 100. Only the question changes. Instead of predicting the score, sort each student into pass or fail, with 50 marks as the pass line.
import numpy as np
import pandas as pd
hours = np.array([1, 2, 3, 4, 5, 6, 7, 8, 2, 5, 9, 10], dtype=float)
tests = np.array([0, 1, 1, 2, 2, 3, 3, 4, 0, 1, 4, 5], dtype=float)
score = np.array([38, 45, 52, 58, 63, 71, 76, 82, 41, 66, 88, 93], dtype=float)
passed = (score >= 50).astype(int)
df = pd.DataFrame({"hours": hours, "practice_tests": tests,
"score": score, "passed": passed})
print(df.head())
print("Pass count:", int(passed.sum()), "| Fail count:", int((passed == 0).sum()))Expected behaviour: the first five rows print exactly as below, and the counts print Pass count: 9 | Fail count: 3. The first two students fail, the next three pass, and the pattern is visible before any model runs: the failing students are the ones with the fewest hours and tests.
hours practice_tests score passed
0 1.0 0.0 38.0 0
1 2.0 1.0 45.0 0
2 3.0 1.0 52.0 1
3 4.0 2.0 58.0 1
4 5.0 2.0 63.0 1Two things to notice. First, the label is a 0 or a 1, and that is a deliberate choice: scikit-learn classifiers want the categories as numbers, and 0 for fail and 1 for pass is the plainest encoding. Second, the classes are unbalanced: nine passes against three fails. That imbalance is the trap this tutorial ends on, so keep the numbers 9 and 3 in mind.
Step 1: fit a logistic regression model
Logistic regression is the plainest classifier to start with, and its name is a small trap: despite the word regression, it is a classifier. It fits a boundary between the two groups and reports, for each student, the probability of belonging to class 1, pass. The model is LogisticRegression in scikit-learn, and the workflow is the same five steps from item 33: load, split, train, evaluate, predict.
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
X = df[["hours", "practice_tests"]].values
X_train, X_test, y_train, y_test = train_test_split(
X, passed, test_size=0.25, random_state=42)
model = LogisticRegression(max_iter=1000)
model.fit(X_train, y_train)
print("Predictions:", model.predict(X_test))
print("Actual: ", y_test)Expected behaviour: the three test students are the same three as in item 67, because the split uses the same random_state=42: (9 hours, 4 tests, pass), (5 hours, 1 test, pass) and (1 hour, 0 tests, fail). The code prints Predictions: [1 1 0] and Actual: [1 1 0]. All three are right.
The max_iter=1000 is a small piece of housekeeping. Logistic regression refines its boundary in repeated steps, and the default limit of 100 steps is sometimes too few, which produces a warning rather than an error. Setting 1000 gives it room. On this data the model fits with no warnings at all, which the code confirms: fitting prints nothing extra.
Note what the model did not do. It never saw the three test students during training, so three correct predictions mean it learned a real boundary, not memorised answers. But three students is a tiny test, and a perfect score on three rows is a demonstration, not proof. Item 69 shows how to test on more data and what to do when the score is not perfect.
Step 2: read the probabilities, not just the label
A bare label hides how sure the model is. predict gives the label, predict_proba gives the probability behind it, and the probability is the more useful answer.
print("Probabilities of passing:", np.round(model.predict_proba(X_test)[:, 1], 2))
print("New student, 6 hours, 3 tests:",
model.predict([[6, 3]])[0],
"| P(pass) =", round(float(model.predict_proba([[6, 3]])[0, 1]), 2))
print("New student, 1 hour, 0 tests:",
model.predict([[1, 0]])[0],
"| P(pass) =", round(float(model.predict_proba([[1, 0]])[0, 1]), 2))Expected behaviour: the code prints Probabilities of passing: [1. 0.91 0.12]. The new student with 6 hours and 3 tests is predicted pass, with P(pass) 0.99. The new student with 1 hour and 0 tests is predicted fail, with P(pass) 0.12.
Read those three test probabilities in order. The 9-hour student gets 1.00, a certain pass. The 5-hour student gets 0.91, a confident pass. The 1-hour student gets 0.12, a confident fail. The model's rule is simple: a probability above 0.5 means pass, below 0.5 means fail, and 0.5 itself is the boundary. But the number carries more than the label does: 0.91 and 0.51 are both "pass", yet the first is a safe bet and the second is a coin toss. In real work, that difference decides what you do next: a 0.51 goes to a human for review, a 0.99 goes straight through.
One honest caution: these probabilities are well behaved because the two groups separate cleanly in this small dataset. On messy real data, a logistic regression probability of 0.9 does not always mean the event happens 90 times in 100. Checking that match is called calibration, and it belongs to the evaluation tutorial, item 69.
Step 3: check it with a confusion matrix
Accuracy, the share of correct predictions, is 1.0 here: three out of three right. But accuracy is one number, and one number can hide the shape of the mistakes. The confusion matrix splits the result into four counts, and it is the check you should reach for first with any classifier.
from sklearn.metrics import accuracy_score, confusion_matrix
print("Accuracy:", round(accuracy_score(y_test, model.predict(X_test)), 3))
print("Confusion matrix:")
print(confusion_matrix(y_test, model.predict(X_test)))Expected behaviour: the code prints Accuracy: 1.0 and the matrix below.
[[1 0]
[0 2]]Read the matrix as a small table. Rows are the truth, columns are the prediction. Top left, 1: one failing student correctly called fail. Bottom right, 2: two passing students correctly called pass. The two off-diagonal cells, both 0, are the mistakes: no failing student was called pass, and no passing student was called fail. A perfect matrix has zeros off the diagonal, and this one does.
The habit to build is this: never quote accuracy without looking at the matrix. Accuracy says "three out of three". The matrix says "the one fail was caught, and both passes were caught". On a tiny test set the two sound the same. On a real dataset they do not, and the next section shows how badly they can differ.
The wrong turn: 75 percent accuracy, zero failing students caught
Here is the trap that catches beginners and, frankly, plenty of working teams. Take the laziest possible model: predict "pass" for every student, no matter the hours or the tests. No training, no boundary, just one fixed answer. Score it on all twelve students.
Nine of the twelve pass, so the lazy model is right nine times out of twelve. Its accuracy is 0.75, or 75 percent. On a slide, "75 percent accurate" sounds like a working model. In reality it is useless: it catches zero of the three failing students, the very students a teacher would want to find. A model that never spots a failing student has learned nothing, and its accuracy is an accident of the class balance, not evidence of skill.
The same trap, run on the three test students, scores 0.667: two passes right, one fail missed. The lesson is identical at both scales. Whenever one category outnumbers the other, accuracy rewards the lazy answer, and the more unbalanced the data, the better the lazy model looks. A spam filter that calls everything "not spam" is 95 percent accurate on an inbox that is 95 percent genuine mail, and it catches no spam at all.
The fix is not a cleverer model. The fix is a better check: the confusion matrix from step 3, which would show the lazy model catching zero fails, and the measures from item 69, precision and recall, which score each category separately. Accuracy is a starting point, never a verdict.
, [0, 2]] labelled "real model: the fail was caught", the second the lazy model's [[0, 1], [0, 2]]` labelled "always predict pass: 75 percent accurate, zero fails caught", with the missed fail circled.]
Regression vs classification, side by side
The two tutorials used the same twelve students and the same two inputs. Only the question changed, so the comparison is exact.
| Regression (item 67) | Classification (item 68) | |
|---|---|---|
| Question | What score will this student get? | Will this student pass or fail? |
| Answer type | A number | A category |
| Model used | LinearRegression | LogisticRegression |
| What the model finds | A line through the points | A boundary between the groups |
| Main output | Predicted value, 69.6 for 6 hours and 3 tests | Predicted label plus probability, pass at 0.99 |
| Honest check | R-squared 0.964 and mean error 2.68 marks on unseen students | Confusion matrix [[1, 0], [0, 2]] on unseen students |
| Classic mistake | Trusting predictions outside the data's range | Trusting accuracy on unbalanced data |
The rule for picking between them is one sentence: if the answer you want is a number, use regression; if it is a category, use classification. And if you ever find yourself predicting 0.7 of a pass, you picked regression for a classification problem, and the model is answering a question nobody asked.
Try it yourself
1. Change the pass line from 50 to 60 and refit the model. How many students pass now, and does the model still get all three test students right? The boundary moves when the definition of pass moves, and that is a decision about the problem, not about the code. 2. Drop practice tests and fit the model on hours alone. Compare the test probabilities with the two-input model: does the 5-hour student's probability move closer to 0.5? One input carries less information, and the model's confidence should show it. 3. Build the lazy model yourself: predict 1 for every test student and compute its accuracy and confusion matrix. Write down, in one sentence, what the accuracy hides. 4. Predict for a student with 3 hours and 2 tests, and read the probability, not just the label. Then explain in one sentence what you would do differently if the probability were 0.99 instead of 0.54.
Continue in the free course: AI & Machine Learning: First Steps →
Common mistakes
- Quoting accuracy on unbalanced data. The always-pass model scores 75 percent on our twelve students and catches none of the three failing students. Always read the confusion matrix next to the accuracy.
- Treating the label as the whole answer.
predictsays pass,predict_probasays how sure: 0.99 and 0.54 are both pass, but only one is a safe bet. Report the probability when the decision matters. - Passing a flat list to
predict.model.predict([6, 3])raisesValueError: Expected 2D array, got 1D array instead. Wrap one sample in double brackets:model.predict([[6, 3]]), exactly as in item 67. - Using the word regression for a classifier.
LogisticRegressionis a classifier, despite its name. It predicts a category, not a number. If you need a number, you wantLinearRegressionfrom item 67. - Testing on three students and calling the model proven. Accuracy 1.0 on three rows is a demonstration. Real confidence needs more test data, and item 69 shows how to get it.
- Forgetting the threshold is a choice. The model calls pass above 0.5 and fail below it. That 0.5 is a default, not a law: moving it trades one kind of mistake for the other, and the right setting depends on which mistake costs more.
Frequently asked questions
What is the difference between classification and regression, in one line?
Classification predicts a category, regression predicts a number. Pass or fail is classification. Exam score is regression. The two tutorials in this pair use the same twelve students to show the difference with the same data.
Why is it called logistic regression if it is a classifier?
History. The method grew out of regression maths, and the name stuck. The model itself predicts a probability, which is then turned into a category at the 0.5 threshold. Judge it by what it outputs, a label, not by its name.
When should I use a decision tree instead of logistic regression?
Use logistic regression first: it is simple, its probabilities are readable, and it works well when the boundary between groups is roughly straight. Item 33 used a decision tree on iris flowers, where the boundaries curve. Reach for a tree when the boundary is not straight, or when you need rules a person can read aloud.
What does the confusion matrix tell me that accuracy does not?
It tells you which mistakes the model makes. Accuracy 0.75 hides the fact that zero of three failing students were caught. The matrix shows it plainly: the fail row has its count in the wrong column. Item 69 builds precision and recall on top of these four counts.
How many categories can a classifier handle?
As many as your labels have. Binary is two, multi-class is three or more, like the three iris species in item 33. The same fitting and testing discipline applies; only the matrix grows, one row and one column per category.
Follow the Python + AI/ML Beginner Roadmap
Learn Python from zero and take your first steps into AI and machine learning. Free, step by step, at your pace.
View the Roadmap