S
将海伦的约会对象分个类为三种类型的人:
- 不喜欢的人
- 魅力一般的人
- 极具魅力的人
海伦手机的样本(datingTestSet2.txt)主要包含以下3种特征
- 每年获得的飞行常客里程数
- 玩视频游戏所耗时间百分比
- 每周消费的冰淇淋公升数
T
使用K-近邻算法将匹配对象分到确切的分类中
A
1.收集数据
2.准备数据:使用python解析文本文件
3.分析数据:使用Matplotlib画图
4.训练算法:不适合KNN
5.测试算法:将海伦提供的部分数据作为测试样本(测试样本是已经完成分类的数据)
6.使用算法
- KNN.py
import numpy as np
import operator
from distlib.compat import raw_input
def createDataSet():
group = np.array([[1.0, 1.1], [1.0, 1.0], [0, 0], [0, 0.1]])
labels = ['A', 'A', 'B', 'B']
return group, labels
# 程序清单2-1: K-近邻算法
"""
step1.计算已知类别数据集中的点与当前点之间的距离
step2.按照距离递增次序排序
step3.选取与当前距离最小的K个点
step4.确定前K个点所在类别的出现频率
step5.返回前K个点出现频率最高的类别作为当前点的预测分类
inx:分类的输入向量
dataSet:训练样本集
labels:标签向量
K:选择最近邻居的数目
"""
def classify0(inx, dataSet, labels, k): #原始KNN分类器函数
"""计算欧式距离"""
dataSetSize = dataSet.shape[0] # shape(0):读取矩阵第一维度的长度
difMat = np.tile(inx, (dataSetSize, 1)) - dataSet # title()
sqDiffMax = difMat ** 2
sqDistances = sqDiffMax.sum(axis=1) # sum(axis=1):将矩阵的每一行相加
distances = sqDistances ** 0.5
"""从小到达排序"""
sortedDistIndices = distances.argsort() # argsort():数值从小到大的索引值
"""确定前K个距离最小元素所在的主要分类"""
classCount = {}
for i in range(k):
voteIlabel = labels[sortedDistIndices[i]]
classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1 # classCount.get(voteIlabel,0)返回字典中votrIlabel元素对应的值
sortedClassCount = sorted(classCount.items(),
key=operator.itemgetter(1), reverse=True) # operator.itrmgettrt(1):获取对象指定区域中的值
return sortedClassCount[0][0]
# 程序清单2-2: 将文本记录准换位NumPy的解析程序
"""
函数的输入为文件名字符串,输出为训练样本矩阵和类标签向量
"""
def file2matrix(filename):
fr = open(filename) # 打开i一个文件
arrayOLines = fr.readlines() # 读取文件的行数
numberOfLines = len(arrayOLines) # len:计算对象的长度
returnMat = np.zeros((numberOfLines, 3)) # 创建一个numberOfLines行3列的0填充的数组
classLabelVector = []
index = 0
for line in arrayOLines: # 循环处理文件中的每行数据
line = line.strip() # strip():截取掉所有的回车字符
listFromLine = line.split('\t') # split('\t'):使用'\t'将整行数据分割成一个元素列表
returnMat[index, :] = listFromLine[0:3] # 选取前三个元素
classLabelVector.append(int(listFromLine[-1])) # 将最后一列存储到向量classLabrlVextor
index += 1
return returnMat, classLabelVector
#程序清单2-3 归一化特征值
"""
归一化公式: newValue = (oldValue-min)/(max-min)
"""
def autoNorm(dataSet):
minVals = dataSet.min(0) #从列中选取最小值
maxVals = dataSet.max(0)
ranges = maxVals - minVals #函数计算可能选取的取值范围
normDataSet = np.zeros(np.shape(dataSet)) #创建新的返回矩阵
m = dataSet.shape[0]
normDataSet = dataSet - np.tile(minVals, (m,1)) #minVal和ranges都为1*3 而特征矩阵为1000*3
normDataSet = normDataSet/np.tile(ranges,(m,1)) #title()将变量内容赋值成输入矩阵同样大小的矩阵
return normDataSet, ranges, minVals
#程序清单 2-4 分类器针对约会网站的测试代码
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 ) #将测试数据和巡礼那样本数据输入到KNN分类器classify0函数
print ("the classifier came back with: %d, thr real answer is: %d"%(classifierResult,datingLabels[i]))
if (classifierResult != datingLabels[i]): errorCount += 1.0 #计算错误列表并输出结果
print ("the total erroe rate is: %f"%(errorCount/float(numTestVecs)))
#程序清单2-5 约会网站预测函数
def classifyPerson():
resultList = ['not at all','in small doses','in large doses'] #结果类型
percentTats = float(raw_input("percentage of time spent playing video games?")) #raw_input:允许用户输入文本行命令并返回用户所输入的命令
ffMiles = float(raw_input("frequent flier miles earned per year?"))
iceCream = float(raw_input("liters of ice cream consumed per year?"))
datingDataMat, datingLabels = file2matrix('datingTestSet2.txt') #读取文件数据
normMat, ranges, minVals = autoNorm(datingDataMat) #归一化
inArr = np.array([ffMiles, percentTats, iceCream]) #创建数组
classifierResult = classify0((inArr-minVals)/ranges,normMat,datingLabels,3) #使用原始KNN分类器
print("You will probably like this person:",resultList[classifierResult -1]) #输入结果
- text_KNN.py
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from importlib import reload
import KNN
#2.1.1
group ,labels = KNN.createDataSet()
print(group)
print(labels)
#2.1.2
print(KNN.classify0([0,0], group, labels, 3))
"""
2.2 示例:使用K-近邻算法改进约会网站
"""
#2.2.1 准备数据:从文本文件中解析数据
reload(KNN) #重新加载
datingDataMat, datingLabels = KNN.file2matrix('datingTestSet2.txt')
print(datingDataMat)
print(datingLabels)
#2.2.2 分析数据:使用Matplotlib创建散点图
"""
使用Matplotlib分析数据
"""
# import matplotlib
# import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(2,2,1)
ax.scatter(datingDataMat[:,1],datingDataMat[:,2],
15.0*np.array(datingLabels),15.0*np.array(datingLabels))#使用第2列和第3列数据
ax = fig.add_subplot(2,2,2)
ax.scatter(datingDataMat[:,0],datingDataMat[:,1],
15.0*np.array(datingLabels),15.0*np.array(datingLabels))#使用第1列和第2列数据
plt.show()
#2.2.3 准备数据:归一化数值
reload(KNN)
normMat, ranges, minVals = KNN.autoNorm(datingDataMat)
print (normMat)
print (ranges)
print (minVals)
#2.2.4 测试算法: 作为完成程序验证分类器
reload(KNN)
KNN.datingClassTest()
#2.2.5 使用算法:构建完整可用系统
KNN.classifyPerson()
[[1. 1.1]
[1. 1. ]
[0. 0. ]
[0. 0.1]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 3, 1, 2, 3, 1, 2, 2, 2, 2, 3, 2, 3, 3, 1, 2, 1, 2, 3, 1, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2, 2, 2, 2, 2, 1, 3, 3, 3]
[[0.44832535 0.39805139 0.56233353]
[0.15873259 0.34195467 0.98724416]
[0.28542943 0.06892523 0.47449629]
...
[0.29115949 0.50910294 0.51079493]
[0.52711097 0.43665451 0.4290048 ]
[0.47940793 0.3768091 0.78571804]]
[9.1273000e+04 2.0919349e+01 1.6943610e+00]
[0. 0. 0.001156]
the classifier came back with: 3, thr real answer is: 3
the classifier came back with: 2, thr real answer is: 2
the classifier came back with: 1, thr real answer is: 1
the classifier came back with: 1, thr real answer is: 1
the classifier came back with: 1, thr real answer is: 1
the classifier came back with: 1, thr real answer is: 1
the classifier came back with: 3, thr real answer is: 3
the classifier came back with: 3, thr real answer is: 3
the classifier came back with: 1, thr real answer is: 1
the classifier came back with: 3, thr real answer is: 3
the classifier came back with: 1, thr real answer is: 1
the classifier came back with: 1, thr real answer is: 1
the classifier came back with: 2, thr real answer is: 2
the classifier came back with: 1, thr real answer is: 1
the classifier came back with: 1, thr real answer is: 1
the classifier came back with: 1, thr real answer is: 1
the classifier came back with: 1, thr real answer is: 1
the classifier came back with: 1, thr real answer is: 1
the classifier came back with: 2, thr real answer is: 2
the classifier came back with: 3, thr real answer is: 3
the classifier came back with: 2, thr real answer is: 2
the classifier came back with: 1, thr real answer is: 1
the classifier came back with: 3, thr real answer is: 2
the classifier came back with: 3, thr real answer is: 3
the classifier came back with: 2, thr real answer is: 2
the classifier came back with: 3, thr real answer is: 3
the classifier came back with: 2, thr real answer is: 2
the classifier came back with: 3, thr real answer is: 3
the classifier came back with: 2, thr real answer is: 2
the classifier came back with: 1, thr real answer is: 1
the classifier came back with: 3, thr real answer is: 3
the classifier came back with: 1, thr real answer is: 1
the classifier came back with: 3, thr real answer is: 3
the classifier came back with: 1, thr real answer is: 1
the classifier came back with: 2, thr real answer is: 2
the classifier came back with: 1, thr real answer is: 1
the classifier came back with: 1, thr real answer is: 1
the classifier came back with: 2, thr real answer is: 2
the classifier came back with: 3, thr real answer is: 3
the classifier came back with: 3, thr real answer is: 3
the classifier came back with: 1, thr real answer is: 1
the classifier came back with: 2, thr real answer is: 2
the classifier came back with: 3, thr real answer is: 3
the classifier came back with: 3, thr real answer is: 3
the classifier came back with: 3, thr real answer is: 3
the classifier came back with: 1, thr real answer is: 1
the classifier came back with: 1, thr real answer is: 1
the classifier came back with: 1, thr real answer is: 1
the classifier came back with: 1, thr real answer is: 1
the classifier came back with: 2, thr real answer is: 2
the classifier came back with: 2, thr real answer is: 2
the classifier came back with: 1, thr real answer is: 1
the classifier came back with: 3, thr real answer is: 3
the classifier came back with: 2, thr real answer is: 2
the classifier came back with: 2, thr real answer is: 2
the classifier came back with: 2, thr real answer is: 2
the classifier came back with: 2, thr real answer is: 2
the classifier came back with: 3, thr real answer is: 3
the classifier came back with: 1, thr real answer is: 1
the classifier came back with: 2, thr real answer is: 2
the classifier came back with: 1, thr real answer is: 1
the classifier came back with: 2, thr real answer is: 2
the classifier came back with: 2, thr real answer is: 2
the classifier came back with: 2, thr real answer is: 2
the classifier came back with: 2, thr real answer is: 2
the classifier came back with: 2, thr real answer is: 2
the classifier came back with: 3, thr real answer is: 3
the classifier came back with: 2, thr real answer is: 2
the classifier came back with: 3, thr real answer is: 3
the classifier came back with: 1, thr real answer is: 1
the classifier came back with: 2, thr real answer is: 2
the classifier came back with: 3, thr real answer is: 3
the classifier came back with: 2, thr real answer is: 2
the classifier came back with: 2, thr real answer is: 2
the classifier came back with: 3, thr real answer is: 1
the classifier came back with: 3, thr real answer is: 3
the classifier came back with: 1, thr real answer is: 1
the classifier came back with: 1, thr real answer is: 1
the classifier came back with: 3, thr real answer is: 3
the classifier came back with: 3, thr real answer is: 3
the classifier came back with: 1, thr real answer is: 1
the classifier came back with: 2, thr real answer is: 2
the classifier came back with: 3, thr real answer is: 3
the classifier came back with: 3, thr real answer is: 1
the classifier came back with: 3, thr real answer is: 3
the classifier came back with: 1, thr real answer is: 1
the classifier came back with: 2, thr real answer is: 2
the classifier came back with: 2, thr real answer is: 2
the classifier came back with: 1, thr real answer is: 1
the classifier came back with: 1, thr real answer is: 1
the classifier came back with: 3, thr real answer is: 3
the classifier came back with: 2, thr real answer is: 3
the classifier came back with: 1, thr real answer is: 1
the classifier came back with: 2, thr real answer is: 2
the classifier came back with: 1, thr real answer is: 1
the classifier came back with: 3, thr real answer is: 3
the classifier came back with: 3, thr real answer is: 3
the classifier came back with: 2, thr real answer is: 2
the classifier came back with: 1, thr real answer is: 1
the classifier came back with: 3, thr real answer is: 1
the total erroe rate is: 0.050000
percentage of time spent playing video games?10
frequent flier miles earned per year?10000
liters of ice cream consumed per year?0.5
You will probably like this person: in small doses