一、在PyCharm 5.0.4(编写python程序的IDE) 编写kNN.py文件的代码
--------------------------
1、 kNN.py 运算符模块
--------------------------
1 from numpy import * 2 import operator 3 4 #运算符模块 创建数据集和标签 5 def createDataSet(): 6 group = array([[1.0, 1.1], [1.0, 1.0], [0, 0], [0, 0.1]]) 7 labels = [‘A‘, ‘A‘, ‘B‘, ‘B‘] 8 return group, labels
1)、打开命令行
先进入kNN.py的所在文件夹,在对kNN.py进行程序处理,效果如下图所示
--------------------------
2、 kNN.py k-近邻算法
--------------------------
1 from numpy import * 2 import operator 3 4 #运算符模块 5 def createDataSet(): 6 group = array([[1.0, 1.1], [1.0, 1.0], [0, 0], [0, 0.1]]) 7 labels = [‘A‘, ‘A‘, ‘B‘, ‘B‘] 8 return group, labels 9 10 #k-近邻算法 此模块需要使用运算符模块的group/labels 11 def classify0(inX, dataSet, labels, k): 12 dataSetSize = dataSet.shape[0] 13 diffMat = tile(inX, (dataSetSize, 1)) - dataSet 14 sqDiffMat = diffMat ** 2 15 sqDistances = sqDiffMat.sum(axis=1) 16 distances = sqDistances ** 0.5 17 sortedDistIndicies = distances.argsort() 18 classCount = {} 19 for i in range(k): 20 voteIlabel = labels[sortedDistIndicies[i]] 21 classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1 22 23 sortedClassCount = sorted(classCount.iteritems(), 24 key=operator.itemgetter(1), 25 reverse=True) 26 return sortedClassCount[0][0]
2) 在1)的基础上,进行2)的内容,可以修改参数
时间: 2024-10-20 10:42:34