python3 环境下import KNN 后报错
Traceback (most recent call last):
File “”, line 1, in
ModuleNotFoundError: No module named ‘KNN’
解决:没有保存成.py 文件
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)//对每行求和 axis=0 对列求和
distances=sqDistances**0.5
sortedDistIndicies=distances.argsort()
classCount={}
//选择距离最小的k个点
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)//True按降序排列 默认升序
return sortedClassCount[0][0]
改进约会网站实例
def file2matrix(filename):
fr = open(filename)
numberOfLines = len(fr.readlines())
returnMat = zeros((numberOfLines,3)) #创造任意维度数组 默认浮点型
classLabelVector = []
fr = open(filename)
index = 0
for line in fr.readlines():
line = line.strip() #去掉所有回车符
listFromLine = line.split('\t') #将整行数据划分成列表
returnMat[index,:] = listFromLine[0:3]
classLabelVector.append(int(listFromLine[-1]))
index += 1
return returnMat,classLabelVector