概述
k-近邻算法采用测量不同特征值之间的距离方法进行分类。
一般流程
- 收集数据
- 准备数据
- 分析数据
- 训练算法 %此步骤不适用k-近邻算法
- 测试算法
- 使用算法
导入数据集
from numpy import * #导入科学计算包
import operator #导入运算符模块
def createDataSet():
group=array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])
lables=['A','A','B','B']
return group,lables
准备数据:从文本中解析数据
def file2mattrix(filename):
#打开文件并得到文件行数
fr=open(filename)
arrayOLines=fr.readlines()
numberOfLines=len(arrayOLines)
#创建返回的numPy矩阵
##创建m行n列的零矩阵,存数据矩阵
returnMat=zeros((numberOfLines,3))
classLableVector=[]#创建类标签
index=0
#解析文件数据到列表
for line in arrayOLines:
#去除行的尾部的换行符
line=line.strip()
#将一行数据按空进行分割
listFromLine=line.split('\t')
#将前三列数据存入将要返回的数据矩阵的对应行的前三列
returnMat[index,:]=listFromLine[:3]
#最后一列为数据的分类标签
classLableVector.append(int(listFromLine[-1]))
index+=1
return returnMat,classLableVector
数据分析:使用Matplotlib绘制散点图
需要导入两个库
import matplotlib
import matplotlib.pyplot as plt
用上述函数从文本中导入数据
datingDataMat,datingLables=file2mattrix("datingTestSet.txt")
绘制散点图
fig=plt.figure()
ax=fig.add_subplot(111)#画布分割
#x轴为数据矩阵第一列,Y轴为数据矩阵第二列
ax.scatter(datingDataMat[:,1],datingDataMat[:,2])
plt.show()
绘制的散点图如下图所示:
准备数据:归一化数值
归一化数值一般就是将数据变换到0到1或者-1到1的范围内,下面公式能将任意取值范围的数值归一化到0到1范围内:
newValue=(oldValue-min)/(max-min)
其中max和min分别为数据集中最大特征值和最小特征值
def autoNorm(dataSet):
#取列的最大值最小值(参数0表示从列取而不是行)
minVals=dataSet.min(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
分析数据:
def classify0(inX,dataSet,lables,k):
# shape[0]获取行 shape[1] 获取列
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()
classCount={}
for i in range(k):
# 获取类别
voteIlabel=labels[sortedDistIndicies[i]]
#字典的get方法,查找classCount中是否包含voteIlabel,是则返回该值,不是则返回defValue,这里是0
# 其实这也就是计算K临近点中出现的类别的频率,以次数体现
classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1
# 对字典中的类别出现次数进行排序,classCount中存储的事 key-value,其中key就是label,value就是出现的次数
# 所以key=operator.itemgetter(1)选中的事value,也就是对次数进行排序
sortedClassCount = sorted(classCount.iteritems(),key=operator.itemgetter(1),reverse=True)
#sortedClassCount[0][0]也就是排序后的次数最大的那个label
return sortedClassCount[0][0]
测试算法:作为完整程序验证分类器
def datingClassTest():
hoRatio=0.10
datingDataMat,datingLables=file2matix('')
normMat,ranges,minVals=autoNorm(datingDataMat)
m=normMat.shape[0]
numTestVecs=int(m*hoRatio)
errorCount=0.0
for i in range(numTestVecs):
classifierResult=classify0(normMat[i,:],normMat[numTestVecs:m,:],\
,datingLables[numTestVecs:m],3)
print('The classfier came back with: %d, The real answer is: %d'%(classifierResult, datingLables[i]))
if(classifierResult!=datingLables[i]):
errorCount+=1.0
print('The total error rate is: %f'%(errorCount/float(numTestVecs)))
使用算法:构建完整可用系统
def classfyPerson():
resultList=['not at all','in small doses','in large doses']
percentTats=float(input('percentage of time spent playing vedio games?'))
ffMiles=float(input('frequent flier miles earned per year?'))
iceCream=float(input('liters of ice cream consumed per year?'))
datingDataMat,datingLables=file2mattrix('')
normMat,ranges,minVals=autoNorm(datingDataMat)
inArr=array([ffMiles,percentTats,iceCream])
classifierResult=classify0((inArr-minVals)/ranges,normMat,datingLables,3)
print('You will probably like this person: ', resultList[classifierResult-1])