学习目标
- 什么是k-NN
- k-NN如何工作的
步骤讲解
k-NN
k邻近法(k-NN)是最简单的分类算法,也可以用于回归计算。
原理
对给定对象进行分类时,需要满足三个关键条件:
-
一组已经标记的对象
-
对象间的距离
-
最近对象统计数阈值k
首先计算所有已标记对象与待标记对象的距离,并记录最近的k个对象,待标记对象与k个对象中计数最多的分为同一类。
源代码
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Importing the dataset
dataset = pd.read_csv("Social_Network_Ads.csv")
x = dataset.iloc[:, [2, 3]].values
y = dataset.iloc[:, 4].values
# Splitting the dataset into The training set and Test set
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.25, random_state = 0)
# Feature scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
x_train = sc.fit_transform(x_train)
x_test = sc.transform(x_test)
# Using k-NN classifier
from sklearn.neighbors import KNeighborsClassifier
classifier = KNeighborsClassifier(n_neighbors=5, metric='minkowski', p=2)
classifier.fit(x_train, y_train)
# Prediction
y_pred = classifier.predict(x_test)
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)