伪代码
(1)计算已知类别数据集中的点与当前点之间的距离
(2)按照距离递增次序排序
(3)选取与当前点距离最小的k个点
(4)确定前k个点坐在类别出现的频率
(5)返回前k个点出现频率最高的类别作为当前点的预测分类
# -*- coding: UTF-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
group, labels = createDataSet()
print group, '\n', labels
# (1, 1.1)定义为类A, (0, 0.1)定义为类B
def classify0(inX, dataSet, labels, k):
dataSetSize = dataSet.shape[0] #hape[0]就是读取矩阵第一维度的长度
diffMat = tile(inX, (dataSetSize, 1)) - dataSet
sqDiffMat = diffMat**2
sqDistances = sqDiffMat.sum(axis=1)
distances = sqDistances**0.5
sortedDistIndicies = distances.argsort()
classCount={}
print classCount
for i in range(k):
voteIlabel = labels[sortedDistIndicies[i]]
#返回voteIlabel的值,如果不存在,则返回0, 然后将票数增1
classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1
#把分类结果进行排序,然后返回得票数最多的分类结果
sortedClassCount = sorted(classCount.iteritems(), key=operator.itemgetter(1), reverse=True)
print sortedClassCount
return sortedClassCount[0][0]
result = classify0([0, 0], group, labels, 3)
print result
使用kNN近邻算法改进约会网站的配对效果
样本例子:
其中 1 代表不喜欢,2 代表魅力一般,3 代表极具魅力
40920 8.326976 0.953952 3
14488 7.153469 1.673904 2
26052 1.441871 0.805124 1
.................................
75136 13.147394 0.428964 1
38344 1.669788 0.134296 1
72993 10.141740 1.032955 1
35948 6.830792 1.213192 3
42666 13.276369 0.543880 3
数字差值最大的特征对计算结果的影响最大,也就是说,飞行里程数对计算结果的影响远远大于其他两个特征的影响。
在处理这种不同取值范围的特征值时,我们需要对数据进行归一化处理。将取值范围处理为 0 到 1 或者 -1 到 1 之间。下面的公式可以将任意取值范围的特征值转化为 0 到 1 区间内的值:
newValue=(oldValue-min)/(max-min)
其中 min 和 max 分别是数据集中某个特征的最小值和最大值。
def file2matrix(filename):
fr = open(filename)
numberOfLines = len(fr.readlines()) #get the number of lines in the file
returnMat = zeros((numberOfLines,3)) # 创建一个初始值为0,大小为 numberOfLines x 3 的数组
classLabelVector = [] #prepare labels return
fr = open(filename)
index = 0
for line in fr.readlines():
line = line.strip() # 去掉行首尾的空白字符,(包括'\n', '\r', '\t', ' ')
listFromLine = line.split('\t') # 分割每行数据,保存到一个列表中
returnMat[index,:] = listFromLine[0:3] # 将列表中的特征保存到reurnMat中
classLabelVector.append(int(listFromLine[-1])) # 保存分类标签
index += 1
return returnMat,classLabelVector
datingDataMat, datingLabels = file2matrix('datingTestSet.txt')
print datingDataMat
def autoNorm(dataSet):
minVals = dataSet.min(0) # minVals保存每列最小值
maxVals = dataSet.max(0) # maxVals保存每列最大值
ranges = maxVals - minVals # ranges保存每列的取值范围
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 datingClassTest():
hoRatio = 0.3 # 测试比例
datingDataMat,datingLabels = file2matrix('datingTestSet.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],50)
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
datingClassTest()