基于K-近邻算法的约会网站用户预测

基本步骤流程:

  1. 收集数据
  2. 数据归一化
  3. 使用KNN算法进行测试 

本例来自Peter Harrington编著的《机器学习实战》, 书中配套代码放在GitHub上《机器学习实战》

约会数据放在文本文件datingTestSet.txtz中,有需要的可以联系,每个样本数据占一行,总共有1000行。每个样本包括3个特征:

  • 每年飞行的旅程数
  • 玩游戏所耗时间百分比  
  • 每周消费的冰淇淋公升数

 分类结果有三类:

  • 1代表没有魅力
  • 2代表有一点魅力
  • 3代表十分有魅力

1.新建KNN.py文件

1.1将文本文件转换为数组:

import numpy as np
#文本文件转换为计算机认识的数据格式
def file2matrix(fileName):
    f = open(fileName)
    arrayLines = f.readlines()#读出所有行
    lenLines = len(arrayLines)#有多少行
    dataSet = np.zeros((lenLines,3))
    labels = []
    index = 0
    for line in arrayLines:
        line = line.strip()#去掉首尾字符,一般去掉首尾的空格换行等字符
        line = line.split('\t')#字符分割,这里以水平制表符‘\t’分割
        dataSet[index,:] = line[0:3]#字符切片
        labels.append(int(line[-1]))#将切片后的最后一片放到标签里
        index += 1
    return dataSet,labels

1.2数据归一化

#数据归一化
def normlize(dataSet):
    maxVal = dataSet.max(axis=0)#按行最大值
    minVal = dataSet.min(axis=0)#按行最小值
    ranges = maxVal - minVal
    row = dataSet.shape[0]#数据行数,即有多少个样本数据
    norm_dataSet = (dataSet - np.tile(minVal,(row,1)))/np.tile((ranges),(row,1))#归一化
    return norm_dataSet,ranges,minVal

1.3K-近邻算法预测

#K-nearst-neighbor
def classifier(inX,dataSet,labels,K):
    row = dataSet.shape[0]
    subtract = np.tile(inX,(row,1)) - dataSet
    square = subtract**2
    sqr_sum = np.sum(square,axis=1)
    sort_index = sqr_sum.argsort()
    classCount = {}
    for i in range(K):
        key = labels[sort_index[i]]
        classCount[key] = classCount.get(key,0)+1
        result = sorted(classCount.items(),key = lambda x:x[1],reverse=True)
        return result[0][0]

2.新建ipynb文件,导入数据

import numpy as np
import KNN
dataSet,labels = KNN.file2matrix('datingTestSet.txt')

 3.分析数据,使用matplotlib创建散点图

import matplotlib
import matplotlib.pyplot as plt
plt.subplot(1,1,1)
plt.scatter(dataSet[:,1],dataSet[:,2])#散点图使用矩阵的第二、三列数据
plt.show()

#为了区分不同的类别,在散点图上绘制尺寸不同、色彩不同的点
plt.subplot(1,1,1)
plt.scatter(dataSet[:,1],dataSet[:,2],15*np.array(labels),15*np.array(labels))
plt.show()

 4.数据归一化

#数据归一化
norm_dataSet,ranges,minVal = KNN.normlize(dataSet)

5.评估模型

#测试错误率
def test():
    count = 0
    row = norm_dataSet.shape[0]
    for i in range(100):
        inX = norm_dataSet[i,:]
        dataSet = norm_dataSet[100:,:]
        label = labels[100:]
        result = KNN.classifier(inX,dataSet,label,3)
        if(result != labels[i]):
            count += 1
    print("the error rate is: %.2f" %(count/100))  

test()

运行结果:the error rate is: 0.08

6.构建约会网站预测系统

#构建可用的约会网站系统
def classifyPerson():
    types = ['not at all','a little like','like very much']
    plane = float(input("frequent flier miles earned per year:"))
    games = float(input("percentage of time spend playing video games:"))
    icecream = float(input("liters of ice cream consumed per year:"))
    dataSet,labels = KNN.file2matrix('datingTestSet.txt')
    norm_dataSet,ranges,minVal = KNN.normlize(dataSet)
    inX = np.array([plane,games,icecream])
    result = KNN.classifier((inX-minVal)/ranges,norm_dataSet,labels,3)
    print("Like Degree:%s"%(types[result-1]))

猜你喜欢

转载自blog.csdn.net/qq_24946843/article/details/83859501