#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
def classify0(inX, dataSet, labels, k): #inX is input vector, dataSet is training set 用于分类的输入向量是inX,输入的训练样本集为dataSet,标签向量为labels,最后的参数k表示用于选择最近邻居的数目
dataSetSize = dataSet.shape[0] #返回行数
diffMat = tile(inX, (dataSetSize,1)) - dataSet #tile创建datasetsize维数组
sqDiffMat = diffMat ** 2
sqDistances = sqDiffMat.sum(axis=1)#axis=1表示按行相加
distance = sqDistances ** 0.5
sortedDistIndicies = distance.argsort()#数据按照从小到大的次序排序,argaort返回排序后元素在原对象中的下标
classCount = {} #建立label:label出现次数字典
for i in range(k):
voteIlabel = labels[sortedDistIndicies[i]]
classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1
sortedClassCount = sorted(classCount.iteritems(),
key = operator.itemgetter(1),reverse = True)
#将classCount字典分解成元组列表,然后使用程序第二行导入运算符模块的itemgetter方法,按照第二个元素的次序对元组进行排序
return sortedClassCount[0][0]
##k-近邻算法是基于实例的学习,使用算法时必须有接近实际数据的训练样本数据。
#k-近邻算法必须保存全部数据集,如果训练数据集很大,必须使用大量的存储控件。此外,由于必须对数据集中的每个数据计算距离值,实际使用时可能非常耗时。
#k-近邻算法的另一个缺陷是它无法给出任何数据的基础结构信息,因此我们也无法知晓平均实例样本和典型实例样本具有社么特征
def file2matrix(filename): #输入:文本文件名字符串;输出:训练样本矩阵和类标签向量
fr = open(filename)
arrayOlines = fr.readlines()
numberOfLines = len(arrayOlines) #得文件行数
returnMat = zeros((numberOfLines,3)) #创建以0填充的Numpy矩阵
classLabelVector = []
index = 0
for line in arrayOlines: #解析文件数据到列表
line = line.strip() #删除回车字符
listFromLine = line.split('\t')#用tab字符将上一步得到的整行数据分割成元素列表
returnMat[index,:] = listFromLine[0:3]
classLabelVector.append(int(listFromLine[-1]))#将列表最后一列存到里面
index += 1
return returnMat,classLabelVector
def autoNorm(dataSet): # 归一化特征值
minVals = dataSet.min(0) #每列的最小值,0表示列,1x3
maxVals = dataSet.max(0)
ranges = maxVals - minVals # 1x3
normDataSet = zeros(shape(dataSet))
m = dataSet.shape[0] #dataSet行数
normDataSet = dataSet - tile(minVals, (m,1)) #将最小值向量复制,与dataDet同维数
normDataSet = normDataSet/tile(ranges, (m,1)) #具体特征值相除。矩阵除法:linalg。solve(matA,matB)
return normDataSet, ranges, minVals
def datingClassTest():#测试分类器效果函数 自包含函数
hoRatio = 0.1
datingDataMat, datingLabels = file2matrix(r'/home/yang/Software/pycharm-community-2017.3.4/bin/桌面/PycharmProjects/untitled/k18/datingTestSet2.txt') #提取数据
normMat, ranges, minVals, = autoNorm(datingDataMat) #归一化特征值
m = normMat.shape[0] #计算测试向量和训练样本的数量
numTestVecs = int(m*hoRatio) #测试向量的数量 10%
errorCount = 0.0 #计数器
for i in range(numTestVecs):
classifierResult = classify0(normMat[i,:],normMat[numTestVecs:m,:],\
datingLabels[numTestVecs:m],3) #inX, dataSet, labels, k)
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))) #计算错误率
def classifyPerson():
resultList = ['not at all','in small doses','in large doses']
percentTats = float(raw_input("percentage of time spent playing video games?"))
ffMiles = float(raw_input("frequent flier miles earned per year?"))
iceCream = float(raw_input("liters of ice cream consumed per year?"))
datingDataMat, datingLabels = file2matrix(r'/home/yang/Software/pycharm-community-2017.3.4/bin/桌面/PycharmProjects/untitled/k18/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])
classifyPerson()
test:
percentage of time spent playing video games?10
frequent flier miles earned per year?500
liters of ice cream consumed per year?3
('you will probably like this person:', 'in small doses')