1.knn算法概述
knn算法又称为k近邻分类(k-nearest neighbor classification)算法,核心思想:给定测试样本,基于某种距离度量找出训练集中与其最靠近的k个训练样本,然后基于这k个相邻点的信息进行预测。
通常,在分类任务中可使用"投票法",即将这k个样本中出现最多的类别标记作为预测结果;在回归任务中可使用“平均法”,即将这k个样本的实际值输入标记的平均值作为预测结果;还可以基于距离远近进行加权平均或者加权投票,距离越近的样本权重越大。
2.准备数据:从文本文件中解析数据
数据主要包含三种特征,
其中第一列代表的是:每年获得的飞行常客里程数
第二列代表的是:玩视频游戏所耗时间百分比
第三列代表的是:每周消费的冰淇淋公升数
第四列代表的是:1-不喜欢、2-有点喜欢、3-非常喜欢
将文本记录到转换NumPy的解析程序
def file2matrix(filename):
fr = open(filename)
numberOfLines = len(fr.readlines())
returnMat = zeros((numberOfLines,3))
classLabelVector = []
fr = open(filename)
index = 0
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
3.分析数据:使用Matplotlib创建散点图
在python命令环境中,输入下列命令
import matplotlib
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(datingDataMat[:,1], datingDataMat[:,2])
plt.show()
输出效果图如图所示
横坐标表示“玩视频游戏所耗时间百分比”
纵坐标表示“每周消费的冰淇凌公升数”
4.准备数据:归一化数值
归一化特征值
def autoNorm(dataSet):
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)) #element wise divide
return normDataSet, ranges, minVals
5.测试算法:作为完整程序验证分类器
分类器针对约会网站的测试代码
def datingClassTest():
hoRatio = 0.50 #hold out 10%
datingDataMat,datingLabels = file2matrix('datingTestSet2.txt') #load data setfrom file
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,:],datingLabels[numTestVecs:m],3)
print "the classifier came back with: %d, the real answer is: %d" % (classifierResult, datingLabels[i])
if (classifierResult != datingLabels[i]): errorCount += 1.0
print "the total error rate is: %f" % (errorCount/float(numTestVecs))
print errorCount
6.使用算法:构建完整可用系统
约会网站预测函数
def classifyperson():
resultList=['not at all','in small doses','in large doses']
percentTats=float(input("percentage of tiome spent playing video games?"))
ffMiles=float(input("frequent flier miles earned per year?"))
iceCream=float(input("liters of ice cream consumed per year?"))
datingDatMat,datingLabels=files2matrix('datingTestSet2.txt')
normMat,ranges,minVals=autoNorm(datingDatMat)
inArr=np.array([ffMiles,percentTats,iceCream])
classifierResult=calssify0((inArr-minVals)/ranges,normMat,datingLabels,3)
print("You will probably like this person:",resultList[classifierResult-1])
实现结果
classifyperson()
out:
percentage of tiome spent playing video games?100
frequent flier miles earned per year?90
liters of ice cream consumed per year?10
You will probably like this person: in large doses
注:以上代码均来自《机器学习实战》