MACHINE LEARNING • LESSON 10

Understand the Python Code

We already built a KNN model. Now let's understand what every important line of the Python code does and how all the lines work together to make a prediction.

THE BIG PICTURE

Don't memorize the code. Understand what each part is responsible for.

The KNN program has a simple flow: create the data, create the labels, choose K, create the model, train it, give it new data, and make a prediction.

01

The Complete Code

First, let's look at the complete program before breaking it into individual parts.

from sklearn.neighbors import KNeighborsClassifier

# Training features
X = [
    [2, 60],
    [3, 65],
    [4, 70],
    [5, 80],
    [6, 85],
    [7, 90]
]

# Training labels
y = [
    "Fail",
    "Fail",
    "Fail",
    "Pass",
    "Pass",
    "Pass"
]

# Create the KNN model
model = KNeighborsClassifier(n_neighbors=3)

# Train the model
model.fit(X, y)

# New student
new_student = [[5, 82]]

# Make prediction
prediction = model.predict(new_student)

print(prediction)
['Pass']
02

Line 1 — Import KNN

from sklearn.neighbors import KNeighborsClassifier

This line imports the KNN classification algorithm from scikit-learn.

Without this import, Python would not know what KNeighborsClassifier means.

Think of it like this:

We are telling Python: "Bring me the KNN classifier so I can use it."

03

Lines 3–10 — Create X

X = [
    [2, 60],
    [3, 65],
    [4, 70],
    [5, 80],
    [6, 85],
    [7, 90]
]

X contains the input features used by KNN.

Each inner list represents one student. The first value is study hours and the second value is attendance.

ROW STUDY HOURS ATTENDANCE
1 2 60%
2 3 65%
3 4 70%
4 5 80%
5 6 85%
6 7 90%
X = the information KNN uses to compare students.
04

Lines 13–20 — Create y

y = [
    "Fail",
    "Fail",
    "Fail",
    "Pass",
    "Pass",
    "Pass"
]

y contains the correct labels for the training examples.

The positions of X and y correspond to each other.

X [2, 60]
y Fail
X [5, 80]
y Pass
X tells the model what the example looks like. y tells the model which class that example belongs to.
05

Line 23 — Create the Model

model = KNeighborsClassifier(n_neighbors=3)

This creates a KNN classifier and stores it in a variable called model.

The important part is:

n_neighbors 3

K = 3

This means KNN will look at the 3 nearest training examples when making a prediction.

Important:

Creating the model does not make a prediction yet. We are only configuring the KNN algorithm.

06

Line 26 — Train the Model

model.fit(X, y)

fit() gives the model the training features and their known labels.

X Features

Study hours + attendance

+
y Labels

Pass + Fail

fit() Model prepared

Ready to classify new data.

A common beginner mistake is thinking that fit() means KNN creates a mathematical equation like linear regression.

KNN is different. It keeps the training examples available so it can compare a new point with them.

07

Line 29 — Create New Data

new_student = [[5, 82]]

This is a new student whose result is unknown.

NEW STUDENT [5, 82]

5 study hours and 82% attendance.

Notice the double brackets:

[[5, 82]]

The outer list represents the collection of data points, while the inner list represents one data point with two features.

08

Line 32 — Make the Prediction

prediction = model.predict(new_student)

This asks the trained KNN model to classify the new student.

Behind the scenes, KNN conceptually does this:

NEW DATA [5, 82]
DISTANCE Compare points
K = 3 Find 3 closest
VOTE Count labels
RESULT Pass
09

Line 34 — Print the Result

print(prediction)

This simply displays whatever prediction was returned by the model.

['Pass']

The result is inside a list because predict() can predict multiple data points at the same time.

10

Why Is predict() So Important?

The entire purpose of building the model is eventually to use it on data it has not been given a label for.

KNOWN DATA X + y

Training examples with known answers.

KNN MODEL model

Uses nearby examples.

UNKNOWN DATA [5, 82]

No label yet.

ANSWER Pass

Predicted class.

11

One Complete Example

Let's trace one prediction from beginning to end.

TRAINING EXAMPLE [5, 80]

Label: Pass

TRAINING EXAMPLE [6, 85]

Label: Pass

TRAINING EXAMPLE [4, 70]

Label: Fail

Now we give KNN:

NEW DATA [5, 82]

Suppose these three are the nearest neighbors. Their labels are:

VOTE 1 Pass
VOTE 2 Pass
VOTE 3 Fail
MAJORITY VOTE Pass

2 Pass votes beat 1 Fail vote.

12

The Code in Plain English

If the Python code feels confusing, translate it into normal language:

1. Bring the KNN classifier.
2. Give it the training features.
3. Give it the correct labels.
4. Tell it to use 3 neighbors.
5. Train the model with the known examples.
6. Give it a new student.
7. Ask KNN to predict the student's class.
8. Display the prediction.
13

What You Should Remember

X Input features
y Correct labels
K Number of neighbors
fit() Provide training data
predict() Predict new data
REMEMBER THIS

KNN Python code is just the KNN process written in Python.

You prepare X and y, choose K, create the model, call fit(), provide new data, and call predict(). The library handles the distance calculations and neighbor voting for you.

X + y KNN fit() New Data predict() Result
QUICK CHECK

Check Your Understanding

What does X contain? The input features used to describe the training examples.
What does y contain? The known class labels for those training examples.
What does n_neighbors=3 mean? KNN uses the 3 nearest neighbors when making a classification.
What does fit(X, y) do? It gives KNN the training examples and their labels.
What does predict() do? It uses the trained KNN model to classify new data.
If the nearest 3 neighbors are Pass, Pass, Fail, what happens? Pass wins the majority vote, so the prediction is Pass.
LESSON 10 COMPLETE

You Now Understand KNN

You have learned what KNN is, how it chooses neighbors, how distance works, how K affects the prediction, how classification works, and how to build and understand a KNN model in Python.