使用kNN算法进行分类的原理是:从训练集中选出离待分类点最近的$k$个点,在这$k$个点中所占比重最大的分类即为该点所在的分类。通常$k$不超过$20$
kNN算法步骤:
- 计算数据集中的点与待分类点之间的距离
- 按照距离升序排序
- 选出距离最小的$k$个点
- 计算这$k$个点所在类别出现的频率(次数)
- 返回出现频率最高的点的类别
代码的实现:
首先导入numpy
模块和operator
模块,建立一个数据集
1 2 3 4 5 6 7 8
| 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
|
kNN算法的核心代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
def classify0(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() classCound = {} for i in range(k): voteIlabel = labels[sortedDistIndicies[i]] classCound[voteIlabel] = classCound.get(voteIlabel, 0) + 1 sortedClassCount = sorted(classCound.items(), key=operator.itemgetter(1), reverse=True) return sortedClassCount[0][0]
|
使用K-近邻算法改进约会网站的配对效果
数据集的处理
首先我们需要处理数据集,将其转换成训练样本矩阵和类标签向量
约会网站的数据集对应的文件名是datingTestSet2.txt
,每列对应的标签分别是:每年获得的飞行常客里程数;玩视频游戏所耗时间百分比;每周消费的冰淇淋公升数;属于哪一类型的人
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| def file2matrix(filename): fr = open(filename) arrar0Lines = fr.readlines() number0fLines = len(arrar0Lines) retrunMat = zeros((number0fLines, 3)) classLabelVector = [] index = 0 for line in arrar0Lines: line = line.strip() listFromLine = line.split('\t') retrunMat[index, :] = listFromLine[0:3] classLabelVector.append(int(listFromLine[-1])) index += 1 return retrunMat, classLabelVector
|
使用Matplotlib创建散点图
在命令行环境中,输入:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| import kNN from numpy import * import matplotlib import matplotlib.pyplot as plt datingDataMat,datingLabels=kNN.file2matrix('datingTestSet2.txt')
fig=plt.figure()
ax=fig.add_subplot(111)
ax.scatter(datingDataMat[:,1],datingDataMat[:,2],15.0*array(datingLabels),15.0*array(datingLabels)) plt.show()
|
此时,可以得到数据集的散点图:(横坐标是玩视频游戏所耗时间百分比
,纵坐标是每周消费的冰淇淋公升数
)
归一化数据
可以看出,在计算点的距离时,里程数对于距离的影响特别大,为了减小这个影响,需要将所有的数据范围处理到$0$到$1$或$-1$到$1$之间,利用下面的公式,可以实现将特征值转化为$[0,1]$区间内的值:
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| 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)) return normDataSet, ranges, minVals
|
分类器针对约会网站的测试代码
使用数据集中的$10\%$的数据作为测试数据,剩余的$90\%$作为数据集
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
def datingClassTest(): hoRatio = 0.10 datingDataMat, datingLabels = file2matrix('datingTestSet2.txt') 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)))
|
约会网站预测函数
1 2 3 4 5 6 7 8 9 10
| def classifyPerson(): resultList = ['not at all', 'in small doses', 'in large doses'] percentTats = float(input("percentage of time spent palying video games?")) ffMiles = float(input("fregunt flier miles earned per year?")) iceCream = float(input("liters of ice cream consumed per year?")) datingDataMat, datingLabels = file2matrix('datingTestSet2.txt') normMat, ranges, minVals = autoNorm(datingDataMat) inArr = array([ffMiles, percentTats, iceCream]) classifierResult = classify0((inArr - minVals) / ranges, normMat, datingLabels, 3) print("You will probably like this person: ", resultList[classifierResult - 1])
|