使用K-近邻算法改进约会网站的配对效果
我的朋友海伦一直使用在线约会网站寻找适合自己 约会对 。尽管约会网站会推荐不同的人选 但她 没有从中找到喜欢的人。经过一番总结 她发现曾交往过三种类型的人
□不 喜欢的人
□ 魅力一 般的人
□ 极具魅力的人
尽管发现了上 述规律,但海伦依然无法将约会网站推荐的 匹配对象归入 恰当的分类 。
她觉得可以在周一到周五约会那些魅力一般的人,而周末 更喜欢 那些极具魅力的人为伴。海伦希望我们的分 软件可以更好 帮助她将匹配对象分到确切的分类中。此外 伦还收集了一些约会网站未曾记录的数据信息 她认为这些数据更 匹配对 归类。每个样本数据占据 行 总共 1000行。
海伦的样本主要包含以 3种特征:
□ 每年 得的飞行常客 程数
□ 玩视频游戏所耗时间百分比
□ 每周消费的冰淇淋公 数
代码:
from numpy import *
import numpy as np
import operator
from os import listdir
import pandas as pd
def createDataSet():
# txt转化为数组
# labels = ['A','A','B','B']
group = np.loadtxt('Test.txt',usecols=(0,1,2)) #使用哪列
# group = array([[0,10],[0,8],[10,0],[7,0]])
file = pd.read_csv('Test.csv',header=None)
labels = list(file.iloc[:,3])
# 相当于有col的这样
# file = pd.read_csv('TestCOL.csv')
# labels = list(file['Tables'])
return group, labels
def classify0(inX, dataSet, labels, k):
dataSetSize = dataSet.shape[0]
diffMat = tile(inX, (dataSetSize,1)) - dataSet
sqDiffMat = diffMat**2
sqDistances = sqDiffMat.sum(axis=1)
distances = sqDistances**0.5
sortedDistIndicies = distances.argsort()
classCount={}
for i in range(k):
voteIlabel = labels[sortedDistIndicies[i]]
classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1
sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)
# print(sortedClassCount)
return sortedClassCount[0][0],sortedClassCount[0][1]
def Test_k():
# 测试
group_test = np.loadtxt('Test.txt',usecols=(0,1,2))
import random
for k in range(2,20):#取20组数据进行测试
max_j=0
for i in range(30):
num = random.randrange(1000)
list_test = group_test[num,:]
one,two = classify0(list_test,group,labels,k)
if two/k >= 0.90:
max_j=max_j+1
print('k=',k,' 准确率:',max_j/30)