k近邻算法python实现 -- 《机器学习实战》



 1 ‘‘‘
 2 Created on Nov 06, 2017
 3 kNN: k Nearest Neighbors
 4
 5 Input:      inX: vector to compare to existing dataset (1xN)
 6             dataSet: size m data set of known vectors (NxM)
 7             labels: data set labels (1xM vector)
 8             k: number of neighbors to use for comparison (should be an odd number)
 9
10 Output:     the most popular class label
11
12 @author: Liu Chuanfeng
13 ‘‘‘
14 import operator
15 import numpy as np
16 import matplotlib.pyplot as plt
17
18 def classify0(inX, dataSet, labels, k):
19     dataSetSize = dataSet.shape[0]
20     diffMat = np.tile(inX, (dataSetSize,1)) - dataSet
21     sqDiffMat = diffMat ** 2
22     sqDistances = sqDiffMat.sum(axis=1)
23     distances = sqDistances ** 0.5
24     sortedDistIndicies = distances.argsort()
25     classCount = {}
26     for i in range(k):
27         voteIlabel = labels[sortedDistIndicies[i]]
28         classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1
29     sortedClassCount = sorted(classCount.items(), key = operator.itemgetter(1), reverse = True)
30     return sortedClassCount[0][0]
31
32 def file2matrix(filename):
33     fr = open(filename)
34     arrayLines = fr.readlines()
35     numberOfLines = len(arrayLines)
36     returnMat = np.zeros((numberOfLines, 3))
37     classLabelVector = []
38     index = 0
39     for line in arrayLines:
40         line = line.strip()
41         listFromLine = line.split(‘\t‘)
42         returnMat[index,:] = listFromLine[0:3]
43         classLabelVector.append(int(listFromLine[-1]))
44         index += 1
45     return returnMat, classLabelVector
46
47 def autoNorm(dataSet):
48     maxVals = dataSet.max(0)
49     minVals = dataSet.min(0)
50     ranges = maxVals -  minVals
51     m = dataSet.shape[0]
52     normDataSet = (dataSet - np.tile(minVals, (m, 1))) / np.tile(ranges, (m, 1))
53     return normDataSet, ranges, minVals
54
55 def datingClassTest():
56     hoRatio = 0.10
57     datingDataMat, datingLabels = file2matrix(‘datingTestSet2.txt‘)
58     normMat, ranges, minVals = autoNorm(datingDataMat)
59     m = normMat.shape[0]
60     numTestVecs = int(m * hoRatio)
61     errorCount = 0.0
62     for i in range(numTestVecs):
63         classifyResult = classify0(normMat[i,:], normMat[numTestVecs:m, :], datingLabels[numTestVecs:m], 3)
64         print(‘theclassifier came back with: %d, the real answer is: %d‘ % (classifyResult, datingLabels[i]))
65         if ( classifyResult != datingLabels[i]):
66             errorCount += 1.0
67         print (‘the total error rate is: %.1f%%‘ % (errorCount/float(numTestVecs) * 100))
68
69 def classifyPerson():
70     resultList = [‘not at all‘, ‘in small doses‘, ‘in large doses‘]
71     percentTats = float(input("percentage of time spent playing video games?"))
72     ffMiles = float(input("frequent flier miles earned per year?"))
73     iceCream = float(input("liters of ice cream consumed per year?"))
74     datingDataMat, datingLabels = file2matrix(‘datingTestSet2.txt‘)
75     normMat, ranges, minVals = autoNorm(datingDataMat)
76     inArr = np.array([ffMiles, percentTats, iceCream])
77     classifyResult = classify0((inArr-minVals)/ranges, normMat, datingLabels, 3)
78     print ("You will probably like this persoon:", resultList[classifyResult - 1])
79
80 # Unit test of func: file2matrix()
81 #datingDataMat, datingLabels = file2matrix(‘datingTestSet2.txt‘)
82 #print (datingDataMat)
83 #print (datingLabels)
84
85 # Usage of figure construction of matplotlib
86 #fig=plt.figure()
87 #ax = fig.add_subplot(111)
88 #ax.scatter(datingDataMat[:,1], datingDataMat[:,2], 15.0*np.array(datingLabels), 15.0*np.array(datingLabels))
89 #plt.show()
90
91 #Unit test of func: autoNorm()
92 #normMat, ranges, minVals = autoNorm(datingDataMat)
93 #print (normMat)
94 #print (ranges)
95 #print (minVals)
96
97 datingClassTest()
98 classifyPerson()

Output:

theclassifier came back with: 3, the real answer is: 3
the total error rate is: 0.0%
theclassifier came back with: 2, the real answer is: 2
the total error rate is: 0.0%
theclassifier came back with: 1, the real answer is: 1
the total error rate is: 0.0%

...

theclassifier came back with: 2, the real answer is: 2
the total error rate is: 4.0%
theclassifier came back with: 1, the real answer is: 1
the total error rate is: 4.0%
theclassifier came back with: 3, the real answer is: 1
the total error rate is: 5.0%

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 persoon: in small doses

 Reference:

《机器学习实战》

时间: 2024-08-03 08:53:24

k近邻算法python实现 -- 《机器学习实战》的相关文章

机器学习实战笔记-K近邻算法1(分类动作片与爱情片)

K近邻算法采用测量不同特征值之间的距离方法进行分类 K近邻算法特点: 优点:精度高.对异常值不敏感.无数据输入假定. 缺点:计算复杂度高.空间复杂度高. 适用数据范围:数值型和标称型. K近邻算法原理: 存在一个样本数据集合,也称作训练样本集,并且样本集中每个数据都存在标签,即我们知道样本集中每一数据与所属分类的对应关系.输人没有标签的新数据后,将新数据的每个特征与样本集中数据对应的 特征进行比较,然后算法提取样本集中特征最相似数据(最近 邻)的分类标签.一般来说,我们只选择样本数据集中前k个最

机器学习实战笔记-K近邻算法2(改进约会网站的配对效果)

案例二.:使用K-近邻算法改进约会网站的配对效果 案例分析: 海伦收集的数据集有三类特征,分别是每年获得的飞行常客里程数.玩视频游戏所耗时间百分比. 每周消费的冰淇淋公升数.我们需要将新数据的每个新数据的每个特征与样本集中数据对应的特征进行比较,然后算法提取样本集中特征最相似数据(最近邻)的分类标签.一般来说,我们只选择样本数据集中前k个最相似的数据,这就是k-近邻算法中k的出处,通常k是不大于20的整数.最后,选择k个最相似数据中出现次数最多的分类,作为新数据的分类. 流程:在约会网站上使用K

机器学习实战笔记--k近邻算法

1 #encoding:utf-8 2 from numpy import * 3 import operator 4 import matplotlib 5 import matplotlib.pyplot as plt 6 7 from os import listdir 8 9 def makePhoto(returnMat,classLabelVector): #创建散点图 10 fig = plt.figure() 11 ax = fig.add_subplot(111) #例如参数为

用Python从零开始实现K近邻算法

K近邻算法 (或简称kNN)是易于理解和实现的算法,而且是你解决问题的强大工具. http://python.jobbole.com/87407/ 在本教程中,你将基于Python(2.7)从零开始实现kNN算法.该实现主要针对分类问题,将会用鸢尾花分类问题来演示. 这篇教程主要针对Python程序员,或者你可以快速上手Python,并且对如何从零实现kNN算法感兴趣. kNN算法图片,来自Wikipedia,保留所有权利 什么是kNN kNN算法的模型就是整个训练数据集.当需要对一个未知数据实

k近邻算法的Python实现

k近邻算法的Python实现 0. 写在前面 这篇小教程适合对Python与NumPy有一定了解的朋友阅读,如果在阅读本文的源代码时感到吃力,请及时参照相关的教程或者文档. 1. 算法原理 k近邻算法(k Nearest Neighbor)可以简称为kNN.kNN是一个简单直观的算法,也是机器学习从业者入门首选的算法.先看一个简单的应用场景. 小例子 设有下表,命名为为表1 电影名称 打斗镜头数量 接吻镜头数量 电影类型 foo1 3 104 爱情片 foo2 2 100 爱情片 foo3 1

第2章 K近邻算法实战(KNN)

1.准备:使用Python导入数据 1.创建kNN.py文件,并在其中增加下面的代码: from numpy import * #导入科学计算包 import operator #运算符模块,k近邻算法执行排序操作时将使用这个模块提供的函数 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 ##print(create

机器学习随笔01 - k近邻算法

算法名称: k近邻算法 (kNN: k-Nearest Neighbor) 问题提出: 根据已有对象的归类数据,给新对象(事物)归类. 核心思想: 将对象分解为特征,因为对象的特征决定了事对象的分类. 度量每个特征的程度,将其数字化. 所有特征值构成元组,作为该对象的坐标. 计算待检测对象和所有已知对象的距离,选择距离最接近的k个已知对象 (k近邻中的k来源于此). 这k个对象中出现次数最多的分类就是待检测对象的分类. 重要前提: 需要有一批已经正确归类了的对象存在.也就是通常说的训练数据. 重

机器学习(四) 机器学习(四) 分类算法--K近邻算法 KNN (下)

六.网格搜索与 K 邻近算法中更多的超参数 七.数据归一化 Feature Scaling 解决方案:将所有的数据映射到同一尺度 八.scikit-learn 中的 Scaler preprocessing.py import numpy as np class StandardScaler: def __init__(self): self.mean_ = None self.scale_ = None def fit(self, X): """根据训练数据集X获得数据的均

02-16 k近邻算法

[TOC] 更新.更全的<机器学习>的更新网站,更有python.go.数据结构与算法.爬虫.人工智能教学等着你:https://www.cnblogs.com/nickchen121/ k近邻算法 k近邻算法(k-nearest neighbors,KNN)是一种基本的分类和回归方法,本文只探讨分类问题中的k近邻算法,回归问题通常是得出最近的$k$个实例的标记值,然后取这$k$实例标记值的平均数或中位数. k近邻算法经常被人们应用于生活当中,比如傅玄曾说过"近朱者赤近墨者黑&quo