ML Day11K近邻法

机器学习100天,每天进步一点点。跟着GitHub开始学习!

英文项目地址https://github.com/Avik-Jain/100-Days-Of-ML-Code

中文项目地址https://github.com/MLEveryday/100-Days-Of-ML-Code


K近邻算法是一种简单但也最常用的分类算法。对未标记的对象进行分类时,首先计算出该对象对标记的对象之间的距离,确定k近邻点,然后使用周边数量最多的最近邻点的类标签来确定该对象的类标签。

对于实际中输入的变量,最常用的距离度量是欧式距离。欧式距离的计算为一个新点和一个现有点在所有输入属性上的差的平方之和的平方根。

K的取值:K值小意味着噪声会对结果产生较大的影响,而K值大则会使计算成本变高。根据实际来选择K值。

K近邻算法的步骤为:

1 数据预处理

导入相关库、导入数据集、将数据划分为训练集和测试集、特征缩放

2 使用K-NN对训练集数据进行训练

3 对测试集进行预测

4 生成混淆矩阵

代码:

# Importing the libraries
import numpy as np  #包含数学计算函数
import matplotlib.pyplot as plt
import pandas as pd  #用于导入和管理数据集

# Importing the dataset
dataset = pd.read_csv('../datasets/Social_Network_Ads.csv')
X = dataset.iloc[:, [2, 3]].values  #iloc是取矩阵的某行某列
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)

# Fitting K-NN to the Training set
from sklearn.neighbors import KNeighborsClassifier
classifier = KNeighborsClassifier(n_neighbors = 5, metric = 'minkowski', p = 2)
classifier.fit(X_train, y_train)

# Predicting the Test set results
y_pred = classifier.predict(X_test)

# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
cm = confusion_matrix(y_test, y_pred)  #生成混淆矩阵
print(cm)
print(classification_report(y_test, y_pred))  #在报告中显示每个类的精确度,召回率,F1值等信息。

结果:

猜你喜欢

转载自blog.csdn.net/weixin_40277254/article/details/86294819
ML