机器学习实战 笔记 debug(一) kNN

代码
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
    sortedDistIndices = distances.argsort()
    classCount = {}
    for i in range(k):
        voteIlabel = labels[sortedDistIndices[i]]
        classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1
    sortedClassCount = sorted(classCount.iteritems(),
                              key=operator.itemgetter(1), reverse=True)
    return sortedClassCount[0][0]




bug
1.pycharm console 在tool里
2.console中 输入kNN.classify0([0,0],group,labels,3)报错

module 'kNN' has no attribute 'classify0'

确保kNN.py在工作路径,在console中import kNN 或者 from kNN import *;编辑kNN.py后可能需要重启pycharm,或者使用reload

多次重复使用import语句时,不会重新加载被指定的模块,只是把对该模块的内存地址给引用到本地变量环境。

3.console中 输入kNN.classify0([0,0],group,labels,3)报错

‘dict' object has no attribute 'iteritems'

因为python2和python3的不兼容,需要将iteritems变为items


结果

机器学习实战 笔记 debug(一) kNN_第1张图片

你可能感兴趣的:(机器学习实战)