Python机器学习之底层实现KNN


Posted in Python onJune 20, 2021

一、导入数据

借助python自带的pandas库导入数据,很简单。用的数据是下载到本地的红酒集。

代码如下(示例):

import pandas as pd
def read_xlsx(csv_path):
    data = pd.read_csv(csv_path)
    print(data)
    return data

二、归一化

KNN算法中将用到距离,因此归一化是一个重要步骤,可以消除数据的量纲。我用了归一化,消除量纲也可以用标准化,但是作为新手,我觉得归一化比较简单。

其中最大最小值的计算用到了python中的numpy库,pandas导入的数据是DateFrame形式的,np.array()用来将DateFrame形式转化为可以用numpy计算的ndarray形式。

代码如下(示例):

import numpy as np
def MinMaxScaler(data):
    col = data.shape[1]
    for i in range(0, col-1):
        arr = data.iloc[:, i]
        arr = np.array(arr) #将DataFrame形式转化为ndarray形式,方便后续用numpy计算
        min = np.min(arr)
        max = np.max(arr)
        arr = (arr-min)/(max-min)
        data.iloc[:, i] = arr
    return data

三、分训练集和测试集

先将数据值和标签值分别用x和y划分开,设置随机数种子random_state,若不设置,则每次运行的结果会不相同。test_size表示测试集比例。

def train_test_split(data, test_size=0.2, random_state=None):
    col = data.shape[1]
    x = data.iloc[:, 0:col-1]
    y = data.iloc[:, -1]
    x = np.array(x)
    y = np.array(y)
    # 设置随机种子,当随机种子非空时,将锁定随机数
    if random_state:
        np.random.seed(random_state)
        # 将样本集的索引值进行随机打乱
        # permutation随机生成0-len(data)随机序列
    shuffle_indexs = np.random.permutation(len(x))
    # 提取位于样本集中20%的那个索引值
    test_size = int(len(x) * test_size)
    # 将随机打乱的20%的索引值赋值给测试索引
    test_indexs = shuffle_indexs[:test_size]
    # 将随机打乱的80%的索引值赋值给训练索引
    train_indexs = shuffle_indexs[test_size:]
    # 根据索引提取训练集和测试集
    x_train = x[train_indexs]
    y_train = y[train_indexs]
    x_test = x[test_indexs]
    y_test = y[test_indexs]
    # 将切分好的数据集返回出去
    # print(y_train)
    return x_train, x_test, y_train, y_test

四、计算距离

此处用到欧氏距离,pow()函数用来计算幂次方。length指属性值数量,在计算最近邻时用到。

def CountDistance(train,test,length):
    distance = 0
    for x in range(length):
        distance += pow(test[x] - train[x], 2)**0.5
    return distance

五、选择最近邻

计算测试集中的一条数据和训练集中的每一条数据的距离,选择距离最近的k个,以少数服从多数原则得出标签值。其中argsort返回的是数值从小到大的索引值,为了找到对应的标签值。

tip:用numpy计算众数的方法

import numpy as np
#bincount():统计非负整数的个数,不能统计浮点数
counts = np.bincount(nums)
#返回众数
np.argmax(counts)

少数服从多数原则,计算众数,返回标签值。

def getNeighbor(x_train,test,y_train,k):
    distance = []
    #测试集的维度
    length = x_train.shape[1]
    #测试集合所有训练集的距离
    for x in range(x_train.shape[0]):
        dist = CountDistance(test, x_train[x], length)
        distance.append(dist)
    distance = np.array(distance)
    #排序
    distanceSort = distance.argsort()
    # distance.sort(key= operator.itemgetter(1))
    # print(len(distance))
    # print(distanceSort[0])
    neighbors =[]
    for x in range(k):
        labels = y_train[distanceSort[x]]
        neighbors.append(labels)
        # print(labels)
    counts = np.bincount(neighbors)
    label = np.argmax(counts)
    # print(label)
    return label

调用函数时:

getNeighbor(x_train,x_test[0],y_train,3)

六、计算准确率

用以上KNN算法预测测试集中每一条数据的标签值,存入result数组,将预测结果与真实值比较,计算预测正确的个数与总体个数的比值,即为准确率。

def getAccuracy(x_test,x_train,y_train,y_test):
    result = []
    k = 3
    # arr_label = getNeighbor(x_train, x_test[0], y_train, k)
    for x in range(len(x_test)):
        arr_label = getNeighbor(x_train, x_test[x], y_train, k)
        result.append(arr_label)
    correct = 0
    for x in range(len(y_test)):
        if result[x] == y_test[x]:
           correct += 1
    # print(correct)
    accuracy = (correct / float(len(y_test))) * 100.0
    print("Accuracy:", accuracy, "%")
    return accuracy

总结

KNN算是机器学习中最简单的算法,实现起来相对简单,但对于我这样的新手,还是花费了大半天时间才整出来。

在github上传了项目:https://github.com/chenyi369/KNN

到此这篇关于Python机器学习之底层实现KNN的文章就介绍到这了,更多相关Python底层实现KNN内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
Python之文字转图片方法
May 10 Python
对pandas中iloc,loc取数据差别及按条件取值的方法详解
Nov 06 Python
对pandas通过索引提取dataframe的行方法详解
Feb 01 Python
Python 函数返回值的示例代码
Mar 11 Python
python3+PyQt5 使用三种不同的简便项窗口部件显示数据的方法
Jun 17 Python
Django获取应用下的所有models的例子
Aug 30 Python
Python大数据之使用lxml库解析html网页文件示例
Nov 16 Python
python getopt模块使用实例解析
Dec 18 Python
jupyter实现重新加载模块
Apr 16 Python
Python Pillow(PIL)库的用法详解
Sep 19 Python
深入浅析python3 依赖倒置原则(示例代码)
Jul 09 Python
python playwright 自动等待和断言详解
Nov 27 Python
利用python进行数据加载
Jun 20 #Python
Python编解码问题及文本文件处理方法详解
浅谈Python协程asyncio
Jun 20 #Python
Python3接口性能测试实例代码
Jun 20 #Python
使用Djongo模块在Django中使用MongoDB数据库
python自动计算图像数据集的RGB均值
详解如何用Python实现感知器算法
You might like
第十四节--命名空间
2006/11/16 PHP
PHP 文件上传功能实现代码
2009/06/24 PHP
PHP 冒泡排序算法的实现代码
2010/08/08 PHP
eclipse php wamp配置教程
2016/06/30 PHP
10个实用的脚本代码工具
2010/05/04 Javascript
原生Js实现按的数据源均分时间点幻灯片效果(已封装)
2010/12/28 Javascript
json+jQuery实现的无限级树形菜单效果代码
2015/08/27 Javascript
jQuery多级手风琴菜单实例讲解
2015/10/22 Javascript
基于JS实现textarea中获取动态剩余字数的方法
2016/05/25 Javascript
json对象与数组以及转换成js对象的简单实现方法
2016/06/24 Javascript
AngularJS定时器的使用与移除操作方法【interval与timeout】
2016/12/14 Javascript
Angularjs实现下拉框联动的示例代码
2017/08/22 Javascript
详解Node全局变量global模块
2017/09/28 Javascript
详解vue2.0 不同屏幕适配及px与rem转换问题
2018/02/23 Javascript
vue2.0使用swiper组件实现轮播的示例代码
2018/03/03 Javascript
详解vue中使用protobuf踩坑记
2019/05/07 Javascript
js实现无限层级树形数据结构(创新算法)
2020/02/27 Javascript
Vue SSR 即时编译技术的实现
2020/05/06 Javascript
[01:33]DOTA2上海特级锦标赛 LIQUID战队完整宣传片
2016/03/16 DOTA
Python编程中归并排序算法的实现步骤详解
2016/05/04 Python
用yum安装MySQLdb模块的步骤方法
2016/12/15 Python
PyQt5每天必学之QSplitter实现窗口分隔
2018/04/19 Python
python模拟登陆,用session维持回话的实例
2018/12/27 Python
python实现将列表中各个值快速赋值给多个变量
2020/04/02 Python
在Python3.74+PyCharm2020.1 x64中安装使用Kivy的详细教程
2020/08/07 Python
详解Python 中的容器 collections
2020/08/17 Python
意大利婴儿产品网上商店:Mukako
2018/10/14 全球购物
Clos19英国:高档香槟、葡萄酒和烈酒在线购物平台
2020/07/10 全球购物
幼师专业求职推荐信
2013/11/08 职场文书
安全员岗位职责
2013/11/11 职场文书
会计应聘求职信范文
2013/12/17 职场文书
公司活动方案范文
2014/03/06 职场文书
竞选生活委员演讲稿
2014/04/28 职场文书
学前班评语大全
2014/05/04 职场文书
租赁协议书
2015/01/27 职场文书
go:垃圾回收GC触发条件详解
2021/04/24 Golang