python实现KNN算法改进约会网站的配对效果

1.knn算法概述
knn算法又称为k近邻分类(k-nearest neighbor classification)算法,核心思想:给定测试样本,基于某种距离度量找出训练集中与其最靠近的k个训练样本,然后基于这k个相邻点的信息进行预测。
通常,在分类任务中可使用"投票法",即将这k个样本中出现最多的类别标记作为预测结果;在回归任务中可使用“平均法”,即将这k个样本的实际值输入标记的平均值作为预测结果;还可以基于距离远近进行加权平均或者加权投票,距离越近的样本权重越大。

2.准备数据:从文本文件中解析数据

 数据主要包含三种特征,

其中第一列代表的是:每年获得的飞行常客里程数

第二列代表的是:玩视频游戏所耗时间百分比

第三列代表的是:每周消费的冰淇淋公升数

第四列代表的是:1-不喜欢、2-有点喜欢、3-非常喜欢

 将文本记录到转换NumPy的解析程序

def file2matrix(filename):
    fr = open(filename)
    numberOfLines = len(fr.readlines())       
    returnMat = zeros((numberOfLines,3))        
    classLabelVector = []                       
    fr = open(filename)
    index = 0
    for line in fr.readlines():
        line = line.strip()
        listFromLine = line.split('\t')
        returnMat[index,:] = listFromLine[0:3]
        classLabelVector.append(int(listFromLine[-1]))
        index += 1
    return returnMat,classLabelVector

3.分析数据:使用Matplotlib创建散点图

在python命令环境中,输入下列命令

import matplotlib
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(datingDataMat[:,1], datingDataMat[:,2])
plt.show()

输出效果图如图所示

 横坐标表示“玩视频游戏所耗时间百分比”

纵坐标表示“每周消费的冰淇凌公升数”

4.准备数据:归一化数值

归一化特征值

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))   #element wise divide
    return normDataSet, ranges, minVals


5.测试算法:作为完整程序验证分类器

分类器针对约会网站的测试代码

def datingClassTest():
    hoRatio = 0.50      #hold out 10%
    datingDataMat,datingLabels = file2matrix('datingTestSet2.txt')       #load data setfrom file
    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))
    print errorCount

6.使用算法:构建完整可用系统

约会网站预测函数

def classifyperson():
    resultList=['not at all','in small doses','in large doses']
    percentTats=float(input("percentage of tiome spent playing video games?"))
    ffMiles=float(input("frequent flier miles earned per year?"))
    iceCream=float(input("liters of ice cream consumed per year?"))
    datingDatMat,datingLabels=files2matrix('datingTestSet2.txt')
    normMat,ranges,minVals=autoNorm(datingDatMat)
    inArr=np.array([ffMiles,percentTats,iceCream])
    classifierResult=calssify0((inArr-minVals)/ranges,normMat,datingLabels,3)
    print("You will probably like this person:",resultList[classifierResult-1])

实现结果

classifyperson()
out:
percentage of tiome spent playing video games?100

frequent flier miles earned per year?90

liters of ice cream consumed per year?10
You will probably like this person: in large doses

注:以上代码均来自《机器学习实战》

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值