《机器学习 实战》第二章k-近邻算法 ,自己实现时遇到的问题,以及解决方法。做个记录。
1.写一个kNN.py保存了之后,需要重新导入这个kNN模块。报错:no module named kNN.
解决方法:1.将.py文件放到 site_packages 目录下
2.在调用文件中添加sys.path.append("模块文件目录");
import sys
sys.path.append('c:\xxxx\b.py') # 这个例子针对 windows 用户来说的
2.上面的问题解决之后,import kNN。报错:only 2 non-keyword arguments accepted。
问题所在:貌似是粗心少写了两个中括号
本来是array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]]),结果少写了最外面的两个中括号-_-||
3.继续写k-近邻算法函数,保存到kNN.py之后,输入命令:kNN.classify0([0,0],group,labels,3)
报错:module' object has no attribute 'classify0'
解决方法:重启Python IDLE即可。
把代码也贴在这里吧,如果保存到电脑里,过一段时间就忘了在哪了。还是放在这里保险点.
kNN.py:
from numpy import * import operator 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 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.iteritems(), key=operator.itemgetter(1 ),reverse= True ) return sortedClassCount[ 0 ][ 0 ]
然后打开Python Shell:
结果还不错。