k近邻算法

本文详细介绍了k近邻算法,包括Matplotlib的使用、数据预处理中的归一化操作,以及KNN算法在手写数字识别中的应用。通过实例展示了如何利用numpy进行数据处理,并探讨了KNN的工作机制,指出其属于懒惰学习类别。同时,文章提供了错误率测试,以评估模型性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

k近邻算法

@(机器学习实战)
书中配套代码放在GitHub上《机器学习实战》


看到k-近邻算法代码时,一个函数不太懂:

    import numpy as np
    np.tile(A,reps)

这个函数是将数组A重复reps次,reps可以是个整数、数组等。
例:

import numpy as np
a=np.array([0,1,2])
np.tile(a,2)//在列方向将数组a重复2次
>>>array([0,1,2,0,1,2])
np.tile(a,(2,3))//在行方向重复2次,列方向重复3次
>>>array([0,1,2,0,1,2],[0,1,2,0,1,2])

numpy中的sum函数。

import numpy as np
a=np.array([[0,1,2],[2,1,3]])
np.sum(a)//输出9,是将数组a全部元素求和
np.sum(a,axis=0)//输出array([2,2,5])是将数组a按列求和
np.sum(a,axis=1)//输出array([2,2,5]),是将数组按行求和
sum中没有axis表示全部相加,axis=0表示按列相加,axis=1表示按行相加。

numpy中的argsort函数。
函数返回数组值从小到大所对应的索引值,函数不影响原数组

    import numpy as np
    x=np.array([3,1,2])
    np.argsort(x)//返回array([1,2,0])
    x=np.array([[3,1,2],[4,0,1]])
    np.argsort(x,axis=0)//按列排序,返回arr([[0,1,1],[1,0,0]])
    np.argsort(x,axis=1)//按行排序,返回array([[1,2,0],[1,2,0]])

dict.get(key)和dict[key],Python中尽量使用dict.get(key)
因为:

    dictionary.get("bogus",default_value)//在dictionary中没有键key-"bogus"时,会返回default_value,如果省略,默认返回None,而如果使用
    dictionary["bogus"]//会引发KeyError

numpy.zeros(shape,dtype=float)用来创建一个全0数组:

    numpy.zeros(5)//array([0.,0.,0.,0.,0.])
    numpy.zeros((1,3))
    //array([[0.,0.,0.],[0.,0.,0.],[0.,0.,0.]])
    numpy.zeros(3,dtype=int)//array([0,0,0])

Determine the type of an object from stackoverflow
python查看一个变量或对象的类型,使用內建函数type()

    type(variable_name)
    type(object_name)
    type({})//<type 'dict'>
    type([])//<type 'list'>

type()函数在查看对象类型时会出现错误情况:

    class Test1(object):
        pass
    calss Test2(Test1):
        pass
    a=Test1()
    b=Test2()
    type(a) is Test1 //True
    type(b) is Test2 //True
    type(b) is Test1 //False,这里对象b其实也是Test1类型,但使用type()并不能看得出。

所以推荐使用isinstance(object,type)

    isinstance(b,Tets1)//True
    isinstance(b,Test2)//True
    isinstance(a,Tets1)//True
    isinstance(a,Test2)//False

用python做数据处理时,常常需要从txt、csv文件导入数据,一般的流程为:

     fr=open(filename)
     for line in fr.readlines():
         line = line.strip()
         listFromLine = line.split('\t')
         returnMat[index,:] = listFromLine[0:3]
         classLabelVector.append(int(listFromLine[-1]))
         index += 1
     return returnMat,classLabelVector//返回数据集sample和对应的label

经常会用到.strip()和.split()
.strip()可以去除首尾的空白字符,
split()可以去除空白字符,如空格字符,制表符等。split()返回的就是列表类型数据。


使用Matplotlib
    import matplotlib
    import matplotlib.pyplot as plt
    fig=plt.figure()//创建空白图像
    ax=fig.add_subplot(111)//增加子图参数,111表示1*1网格,第1子图
    ax.scatter(datingDataMat[:,1],datingDataMat[:,
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值