1、kNN 算法
算法说明:
set<X1,X2……Xn> 为已知类别数据集,预测 点Xt 的类别:
(1)计算中的set中每一个点与Xt的距离
(2)按距离增序排列
(3)选择距离最小的前k个点
(4)确定前k个点所在的类别的出现频率
(5)返回频率最高的类别作为测试的结果
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
def classify0(inX , dataSet ,labels,k):
dataSetSize = dataSet.shape[0] #行数
diffMat = tile(inX,(dataSetSize,1)) - dataSet # tile(inX,(dataSetSize,1)) 生成 dataSetSize 行 1 列的 元素为 inX的 数组
sqDiffMat = diffMat ** 2 # ** 为 ^
sqDistances = sqDiffMat.sum(axis=1) # axis=0是按列求和 axis=1 是按行求和
distance = sqDistances ** 0.5
sortedDisInd = distance.argsort()# argsort,属于numpy中的函数 返回排序后元素在原对象中的下标
classCount = {}
for i in range(k):
votelabel = labels[sortedDisInd[i]]
classCount[votelabel] = classCount.get(votelabel,0) + 1 #dict.get(key, default=None) key:key在字典中查找。 default:在key不存在的情况下返回值None。
sortedClassCount = sorted(classCount.iteritems(),key = operator.itemgetter(1),reverse =True)
'''
要通过student的第三个域排序,可以这么写:
sorted(students, key=operator.itemgetter(2))
sorted函数也可以进行多级排序,例如要根据第二个域和第三个域进行排序,可以这么写:
sorted(students, key=operator.itemgetter(1,2))
即先跟句第二个域排序,再根据第三个域排序。
'''
return sortedClassCount[0][0]
2、加载数据
下载地址:http://pan.baidu.com/s/1c0NeKCg
数据格式:[fre flier miles earned per year]'\t'[per of time spent playing video games]'\t'[liters of ice cream consumed per year]'\t'[1,means do not at all/2,means small do/3,means large do]
#加载数据
def file2matrix(filename):
fr = open(filename)
arrayOLines = fr.readlines() #注意需要加s
numberOfLines = len(arrayOLines)
returnMat = zeros((numberOfLines,3))
classLabelVector = []
index = 0
for line in arrayOLines:
line = line.strip()
listFormLine = line.split('\t')
for x in range(0,3):
returnMat[index,x] = float(listFormLine[x])
classLabelVector.append(int(listFormLine[-1])) # -1 为最后一个元素
index += 1
return returnMat,classLabelVector
3、散点图
import matplotlib
import matplotlib.pyplot as plt
datingDataMat,datingLabels = kNN.file2matrix('datingTestSet.txt')
fig = plt.figure() #figure创建一个绘图对象
ax = fig.add_subplot(111)# 若参数为349,意思是:将画布分割成3行4列,图像画在从左到右从上到下的第9块, '''
matplotlib.pyplot.scatter(x, y, s=20, c='b', marker='o', cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, verts=None, hold=None,**kwargs)
其中,xy是点的坐标,s点的大小
maker是形状可以maker=(5,1)5表示形状是5边型,1表示是星型(0表示多边形,2放射型,3圆形)
alpha表示透明度;facecolor=‘none’表示不填充。
''' ax.scatter(datingDataMat[:,1],datingDataMat[:,2],15.0*array(datingLabels),marker=(5,1),alpha=0.5)
plt.show()
4、归一化特征值
由于特征值的大小不同,所以就会对结果的影响程度不同。这就需要我们归一化特征值,把每个特征值的大小固定在[0,1]:
range = MaxVal - MinVal
normVal = rawVal / (MaxVal - MinVal)
#归一化特征值
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
5.分类器测试
用10%的数据作为输入来测试,另外90%作为已知集合
def datingClassTest():
hoRatio = 0.10
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],3)
print "back %d ,real %d" % (classifierResult,datingLabels[i])
if(classifierResult != datingLabels[i]):
errorCount += 1.0
print "range is %f" % (errorCount / float(numTestVecs))
6、约会网站测试
#约会网站测试函数
def classifyPerson():
resultList = ['not at all','in small doses','in large dose']
percentTats = float(raw_input("per of time spent playing video games?"))
ffMiles = float(raw_input("fre flier miles earned per year?"))
iceCream = float(raw_input("liters of ice cream consumed per year?"))
datingDataMat,datingLabels = file2matrix('datingTestSet.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 :",
print resultList[classifierResult-1]