机器学习-K近邻算法

一. 算法原理

先确定K值, 再计算距离,最后挑选K个最近的邻居进行投票
KNN 算法原理简单,不需要训练,属于监督学习算法,常用来解决分类问题

二. 鸢尾花数据集介绍

鸢尾花数据集
鸢尾花Iris Dataset数据集是机器学习领域经典数据集,鸢尾花数据集包含了150条鸢尾花信息,每50条取自三个鸢尾花中之一:Versicolour、Setosa和Virginica
在这里插入图片描述
每个花的特征用如下属性描述:
在这里插入图片描述

from sklearn.datasets import load_iris
# 1. 准备数据集
iris = load_iris()
iris.data

在这里插入图片描述

iris.target
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])
print(iris.DESCR)

Iris plants dataset

Data Set Characteristics:

:Number of Instances: 150 (50 in each of three classes)
:Number of Attributes: 4 numeric, predictive attributes and the class
:Attribute Information:
    - sepal length in cm
    - sepal width in cm
    - petal length in cm
    - petal width in cm
    - class:
            - Iris-Setosa
            - Iris-Versicolour
            - Iris-Virginica
            
:Summary Statistics:

============== ==== ==== ======= ===== ====================
                Min  Max   Mean    SD   Class Correlation
============== ==== ==== ======= ===== ====================
sepal length:   4.3  7.9   5.84   0.83    0.7826
sepal width:    2.0  4.4   3.05   0.43   -0.4194
petal length:   1.0  6.9   3.76   1.76    0.9490  (high!)
petal width:    0.1  2.5   1.20   0.76    0.9565  (high!)
============== ==== ==== ======= ===== ====================

:Missing Attribute Values: None
:Class Distribution: 33.3% for each of 3 classes.
:Creator: R.A. Fisher
:Donor: Michael Marshall (MARSHALL%PLU@io.arc.nasa.gov)
:Date: July, 1988

三. 鸢尾花KNN

from sklearn.datasets import load_iris
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier

if __name__ == '__main__':
    # 1. 加载数据集  
    iris = load_iris() #通过iris.data 获取数据集中的特征值  iris.target获取目标值

    # 2. 数据标准化
    transformer = StandardScaler()
    x_ = transformer.fit_transform(iris.data) # iris.data 数据的特征值

    # 3. 模型训练
    estimator = KNeighborsClassifier(n_neighbors=3) # n_neighbors 邻居的数量,也就是Knn中的K值
    estimator.fit(x_, iris.target) # 调用fit方法 传入特征和目标进行模型训练

    # 4. 利用模型预测
    result = estimator.predict(x_) 
    print(result)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2,
       2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       2, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])

四. k值的选择

KNN算法的关键是,是K值的选择,下图中K=3,属于红色三角形,K=5属于蓝色的正方形。这个时候就是K选择困难的时候。
在这里插入图片描述
KNN 算法中K值过大、过小都不好, 一般会取一个较小的值
采用交叉验证法(把训练数据再分成:训练集和验证集)来选择最优的K值。

#加载数据集
x,y = load_iris(return_X_y=True)
#数据标准化
scaler = StandardScaler()
x_scaled = scaler.fit_transform(x)
#划分数据集
x_train,x_test,y_train,y_test = train_test_split(x_scaled,y,test_size=0.2,random_state=0)
#创建网络搜索对象
knn = KNeighborsClassifier()
param_grid = {'n_neighbors':[1, 3, 5, 7]}
estimator = GridSearchCV(knn, param_grid, cv=5)
#训练模型
estimator.fit(x_train,y_train)
#输出最优参数
#打印最优参数(验证集)
print('最优参数组合:', estimator.best_params_, '最好得分:', estimator.best_score_)

#测试集评估模型(测试集)
print('测试集准确率:', estimator.score(x_test, y_test))
最优参数组合: {'n_neighbors': 7} 最好得分: 0.9416666666666667
测试集准确率: 1.0

五. 手写数字数据介绍

数据文件手写数字识别.csv包含从 0 到 9 的手绘数字的灰度图像。
● 每个图像高 28 像素,宽28 像素,共784个像素。
● 每个像素取值范围[0,255],取值越大意味着该像素颜色越深
● 数据集共785列。第一列为 “标签”,为该图片对应的手写数字。其余784列为该图像的像素值
● 训练集中的特征名称均有pixel前缀,后面的数字([0,783])代表了像素的序号。

import pandas as pd

data = pd.read_csv('data/手写数字识别.csv')
data.head()

在这里插入图片描述

data.shape

(42000, 785)

二. 手写数字识别KNN

import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
import joblib
from collections import Counter


def show_digit(idx):
      # 加载数据
    data = pd.read_csv('data/手写数字识别.csv')
    if idx < 0 or idx > len(data) - 1:
        return
    x = data.iloc[:, 1:]
    y = data.iloc[:,0]
    print('当前数字的标签为:',y[idx])
    
    # data 修改为 ndarray 类型
    data_ = x.iloc[idx].values
    # 将数据形状修改为 28*28
    data_ = data_.reshape(28, 28)
    # 关闭坐标轴标签
    plt.axis('off')
    # 显示图像
    plt.imshow(data_)
    plt.show()
    

def train_model():

    # 1. 加载手写数字数据集
    data = pd.read_csv('data/手写数字识别.csv')
    x = data.iloc[:, 1:] / 255
    y = data.iloc[:, 0]
    
    # 2. 打印数据基本信息
    print('数据基本信息:', x.shape)
    print('类别数据比例:', Counter(y))

    # 3. 分割数据集
    split_data = train_test_split(x, y, test_size=0.2, stratify=y, random_state=0)
    x_train, x_test, y_train, y_test = split_data

    # 4. 模型训练
    estimator = KNeighborsClassifier(n_neighbors=3)
    estimator.fit(x_train, y_train)

    # 5. 模型评估
    acc = estimator.score(x_test, y_test)
    print('测试集准确率: %.2f' % acc)

    # 6. 模型保存
    joblib.dump(estimator, 'model/knn.pth')


def test_model():
    # 读取图片数据
    import matplotlib.pyplot as plt
    import joblib
    img = plt.imread('temp/demo.png')
    plt.imshow(img)
    # 加载模型
    knn = joblib.load('model/knn.pth')
    y_pred = knn.predict(img.reshape(1, -1))
    print('您绘制的数字是:', y_pred)
# 显示部分数字
show_digit(1)

当前数字的标签为: 0
在这里插入图片描述

# 训练模型
train_model()
数据基本信息: (42000, 784)
类别数据比例: Counter({1: 4684, 7: 4401, 3: 4351, 9: 4188, 2: 4177, 6: 4137, 0: 4132, 4: 4072, 8: 4063, 5: 3795})
测试集准确率: 0.97
# 测试模型
test_model()

您绘制的数字是: [1]
在这里插入图片描述
啊偶,预测错了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值