Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

K-Nearest Neighbors Algorithm

K-Nearest Neighbors Algorithm

The K-Nearest Neighbors algorithm (K-Nearest Neighbors, or KNN for short) is a simple and widely used algorithm for classification and regression.

K-Nearest Neighbors is a type of supervised learning. Its core idea is to compute the distance between the sample to be classified and each sample in the training set, find the K nearest samples, and then predict the class or value of the sample based on the classes or values of these K samples.

Basic Principles of KNN

The basic principle of the KNN algorithm can be summarized in the following steps:

  1. Calculate Distance: Calculate the distance between the sample to be classified and each sample in the training set. Common distance metrics include Euclidean distance, Manhattan distance, and others.
  2. Select the K Nearest Neighbors: Based on the calculated distances, select the K samples that are closest.
  3. Voting or Averaging: For classification problems, the class that appears most frequently among the K nearest neighbors is the class of the sample to be classified; for regression problems, the average of the values of the K nearest neighbors is the value of the sample.

Characteristics of KNN

Advantages and Disadvantages of KNN

Advantages

Disadvantages


Implementation Steps of the KNN Algorithm

1. Import the necessary libraries

First, we need to import some commonly used Python libraries, such as numpy for numerical computation,matplotlib for plotting,sklearn for loading datasets and evaluating models.

Example

import

numpy

as

np

import

matplotlib.

pyplot

as

plt

from

sklearn

import

datasets

from

sklearn.

model_selection

import

train_test_split

from

sklearn.

neighbors

import

KNeighborsClassifier

from

sklearn.

metrics

import

accuracy_score

2. Load the Dataset

We use sklearn The load_iris The function loads the classic Iris dataset. This dataset contains 150 samples, each with 4 features, and the goal is to classify the samples into 3 categories.

Example

Load the Iris dataset

iris

=

datasets.

load_iris

(

)

X

=

iris.

data

[

:

,

:

2

]

 

Take only the first two features for easier visualization

y

=

iris.

target

3. Data Preprocessing

Before applying the KNN algorithm, the data usually needs to be standardized to ensure that each feature contributes equally to the distance calculation.

Example

Split the dataset into training and test sets

X_train

,

X_test

,

y_train

,

y_test

=

train_test_split

(

X

,

y

,

test_size

=

0.3

,

random_state

=

42

)

4. Train the KNN Model

Next, we use sklearn The KNeighborsClassifier to train the KNN model. Here we choose K=3, that is, 3 nearest neighbors.

Example

Create the KNN model and set K to 3

knn

=

KNeighborsClassifier

(

n_neighbors

=

3

)

Train the model

knn.

fit

(

X_train

,

y_train

)

5. Prediction and Evaluation

Use the trained model to make predictions on the test set and calculate the model's accuracy.

Example

Make predictions on the test set

y_pred

=

knn.

predict

(

X_test

)

Compute accuracy

accuracy

=

accuracy_score

(

y_test

,

y_pred

)

print

(

f

"KNN model accuracy: {accuracy:.4f}"

)

The output is as follows:

KNN模型的准确率: 0.7556

6. Visualize the KNN Classification Results

To understand the classification effect of KNN more intuitively, we can plot the data points as well as the decision boundary.

Here we use the first two features of the dataset as input features.

Example

import

numpy

as

np

import

matplotlib.

pyplot

as

plt

from

sklearn

import

datasets

from

sklearn.

model_selection

import

train_test_split

from

sklearn.

neighbors

import

KNeighborsClassifier

from

sklearn.

metrics

import

accuracy_score

Load the Iris dataset

iris

=

datasets.

load_iris

(

)

X

=

iris.

data

[

:

,

:

2

]

 

Take only the first two features for easier visualization

y

=

iris.

target

Split the dataset into training and test sets

X_train

,

X_test

,

y_train

,

y_test

=

train_test_split

(

X

,

y

,

test_size

=

0.3

,

random_state

=

42

)

Create the KNN model and set K to 3

knn

=

KNeighborsClassifier

(

n_neighbors

=

3

)

Train the model

knn.

fit

(

X_train

,

y_train

)

Make predictions on the test set

y_pred

=

knn.

predict

(

X_test

)

Compute accuracy

accuracy

=

accuracy_score

(

y_test

,

y_pred

)

print

(

f

"KNN model accuracy: {accuracy:.4f}"

)

Plot the decision boundary and data points

h

=

.02

 

Grid step size

x_min

,

x_max

=

X

[

:

,

0

]

.

min

(

)

1

,

X

[

:

,

0

]

.

max

(

)

1

y_min

,

y_max

=

X

[

:

,

1

]

.

min

(

)

1

,

X

[

:

,

1

]

.

max

(

)

1

Create a 2D grid representing different sample spaces

xx

,

yy

=

np.

meshgrid

(

np.

arange

(

x_min

,

x_max

,

h

)

,

                     np.

arange

(

y_min

,

y_max

,

h

)

)

Use the KNN model to predict the class of each point in the grid

Z

=

knn.

predict

(

np.

c_

[

xx.

ravel

(

)

,

yy.

ravel

(

)

]

)

Z

=

Z.

reshape

(

xx.

shape

)

Plot the decision boundary

plt.

contourf

(

xx

,

yy

,

Z

,

alpha

=

0.8

)

Plot the training data points

plt.

scatter

(

X

[

:

,

0

]

,

X

[

:

,

1

]

,

c

=

y

,

edgecolors

=

'k'

,

marker

=

'o'

,

s

=

50

)

plt.

title

(

"KNN Demo"

)

plt.

xlabel

(

"Feature 1"

)

plt.

ylabel

(

"Feature 2"

)

plt.

show

(

)

The display is shown as follows:

7. Adjust the K Value

The choice of K has an important impact on model performance.

Typically, we select the best K value through cross-validation or visualization methods.

Example

Try different K values and plot the change in accuracy

k_range

=

range

(

1

,

21

)

accuracies

=

[

]

for

k

in

k_range:

    knn

=

KNeighborsClassifier

(

n_neighbors

=

k

)

    knn.

fit

(

X_train

,

y_train

)

    y_pred

=

knn.

predict

(

X_test

)

    accuracy

=

accuracy_score

(

y_test

,

y_pred

)

    accuracies.

append

(

accuracy

)

Plot the relationship between K and accuracy

plt.

plot

(

k_range

,

accuracies

,

marker

=

'o'

)

plt.

title

(

"Relationship between K and accuracy"

)

plt.

xlabel

(

"K value"

)

plt.

ylabel

(

"Accuracy"

)

plt.

show

(

)

8. Using KNN for Regression Tasks

KNN can also be used for regression tasks (KNN Regression).

In regression tasks, KNN predicts the output by averaging the target values of the K nearest neighbors.

Example

import

numpy

as

np

import

matplotlib.

pyplot

as

plt

from

sklearn.

model_selection

import

train_test_split

from

sklearn.

neighbors

import

KNeighborsRegressor

Generate sample data

X

=

np.

random

.

rand

(

100

,

1

)

10

y

=

np.

sin

(

X

)

.

ravel

(

)

0.1

random

.

randn

(

100

)

Split into training and test sets

X_train

,

X_test

,

y_train

,

y_test

=

train_test_split

(

X

,

y

,

test_size

=

0.3

,

random_state

=

42

)

Create the KNN regression model

knn_reg

=

KNeighborsRegressor

(

n_neighbors

=

5

)

Train the model

knn_reg.

fit

(

X_train

,

y_train

)

Make predictions on the test set

y_pred

=

knn_reg.

predict

(

X_test

)

Visualize the regression results

plt.

scatter

(

X_test

,

y_test

,

color

=

'red'

,

label

=

'True Values'

)

plt.

scatter

(

X_test

,

y_pred

,

color

=

'blue'

,

label

=

'Predicted Values'

)

plt.

title

(

"KNN Regression"

)

plt.

xlabel

(

"Feature"

)

plt.

ylabel

(

"Target"

)

plt.

legend

(

)

plt.

show

(

)

Red represents the true values, blue represents the predicted values: