机器学习---实验(1)--k近邻

k-近邻算法概述

简单地算,k-近邻算法采用测量不同特征值之间的距离方法进行分类
优点: 精度高,对异常值不敏感,无数据输入假定。
缺点:计算复杂度高,空间复杂度高。
使用数据范围:数值型和标称型

k-近邻算法的工作原理

存在一个样本集,并且样本集中的每个数据都存在标签,即我们知道样本集中的每一个数据与所属分类的对应关系。输入没有标签的新数据后,将新数据的每个特征与样本集中数据对应的特征进行比较,然后算法提取样本集中特征最相似的分类标签。

k-近邻算法的一般流程

1.搜集数据:可以使用任何方法
2.准备数据:距离计算所需要的数值,最好是结构化的数据格式
3.分析数据:可以使用任何方法
4.训练算法:此步骤不适用于k-近邻算法
5.测试算法:计算错误率
6.使用算法:首先需要输入样本数据和结构化的输出结果,然后运行k-近邻算法判定输入数据分别属于哪个分类,最后应用对计算出的分类执行后续的处理

k-近邻算法伪代码及代码

伪代码:
1.计算已知类别数据集中的点与当前点之间的距离
2.按照距离递增次序排序
3.选取与当前点距离最小的k个点
4.确定前k个点所在类别的出现频率
5.返回前k个点出现频率最高的类别作为当前点的预测分类
使用python导入数据:

from numpy import *
import operator

def createDataSet():
    group = array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])
    labels=['A','A','B','B']
    return group,labels

k-近邻算法

def classify(inX,dataSet,labels,k):
    #计算距离
    dataSetSize=dataSet.shape[0]
    diffMat=tile(inX,(dataSetSize,1))-dataSet
    sqDiffMat=diffMat**2
    sqDistances=sqDiffMat.sum(axis=1)
    distances=sqDistances**0.5
    sortedDistIndicies=distances.argsort()#argsort()函数是将x中的元素从小到大排列,提取其对应的index(索引号)
    classCount={}
    #选择距离最小的k个点
    for i in range(k):
        voteIlabel = labels[sortedDistIndicies[i]]
        classCount[voteIlabel]=classCount.get(voteIlabel,0)+1#统计列表中每个元素出现次数
    #排序
    sortedClassCount = sorted(classCount.items(),
    key=operator.itemgetter(1),reverse=True)
    return sortedClassCount[0][0]

计算两个向量点xA和xB之间的距离
在这里插入图片描述
运行测试:

if __name__=='__main__':
    group,labels=createDataSet()
    print(classify([0,0],group,labels,3))

使用k-近邻算法预测奖学金等级

数据格式:卷面成绩 班级排名 综测分 奖学金等级(集美大学20智科学习成绩)
共计117条
在这里插入图片描述
数据分布散点图展示:
在这里插入图片描述

从文本中解析数据

def file2matrix(filename):
    fr=open(filename,'r')
    arrayOLines=fr.readlines()
    random.shuffle(arrayOLines)#由于原始数据规则,这里打乱它
    numberOfLines=len(arrayOLines)
    returnMat=zeros((numberOfLines,3))
    classLabelVector=[]
    index=0
    for line in arrayOLines:
        line=line.strip()
        listFromLine=line.split(' ')
        returnMat[index,:]=listFromLine[0:3]
        classLabelVector.append(listFromLine[-1])
        index+=1
    return returnMat,classLabelVector

平衡各特征的数值差值,设置归一化函数
采用:newvalue=(oldValue-min)/(max-min)

#归一化特征
def autoNorm(dataset):
    minVals=dataset.min(0)#参数0使得函数可以从列中选取最小值
    maxVals=dataset.max(0)
    ranges=maxVals-minVals
    normDataSet=zeros(shape(dataset))
    m=dataset.shape[0]
    normDataSet=dataset-tile(minVals,(m,1))
    normDataSet=normDataSet/tile(ranges,(m,1))
    return normDataSet,ranges,minVals

导入库修改:

from numpy import *
import operator
import matplotlib
import matplotlib.pyplot as plt
from pylab import mpl
# 设置显示中文字体
mpl.rcParams["font.sans-serif"] = ["SimHei"]
# 设置正常显示符号
mpl.rcParams["axes.unicode_minus"] = False

测试代码,修改主函数,取数据中90%作为:

if __name__=='__main__':
   datingDataMat,datingLabels=file2matrix('./ch1/grade.txt')
   normMat,ranges,minVals=autoNorm(datingDataMat)
   fig=plt.figure()
   ax=fig.add_subplot(111,projection='3d')
   dir={0:'black',1:'red',2:'green',3:'blue'}
   ax.set_xlabel('成绩')
   ax.set_ylabel('班级排名')
   ax.set_zlabel('综测分')
   index=0
   for x,y,z in normMat:
    ax.scatter(x,y,z,c=dir[int(datingLabels[index])])
    index=index+1
   
   plt.show()
   hoRatio=0.10
   m=normMat.shape[0]
   numTestVecs=int(m*hoRatio)#取出0.1
   errorCount=0.0
   for i in range(numTestVecs):
     classifierResult=classify(normMat[i,:],normMat[numTestVecs:m,:],
     datingLabels[numTestVecs:m],3)
     print(f"The classifier came back with {classifierResult}, the real answer is {datingLabels[i]}")
     if(classifierResult!=datingLabels[i]):
        errorCount+=1.0
   print(f"the total error rate is:{errorCount/float(numTestVecs)}")

运行结果展示
此时k的值为3:错误率0.272
在这里插入图片描述
此时k的值为2*:错误率:0.454
在这里插入图片描述
此时k的值为2*:错误率:0.181
在这里插入图片描述

实验结果分析:
由于拥有高等级奖学金的数据过少,在划分数据集的时候,测试集中有这些高奖学金的时候,误差会偏高。相对的,如果测试集中低奖学金等级的数据集较多时,错误率会低很多。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值