>>> import trees Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> import trees File "D:\Python\trees.py", line 9 labelCounts[currentLabel] = 0 ^ TabError: inconsistent use of tabs and spaces in indentation
>>> import trees Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> import trees File "D:\Python\trees.py", line 9 labelCounts[currentLabel] = 0 ^ IndentationError: expected an indented block
>>> import trees Traceback (most recent call last): File "<pyshell#5>", line 1, in <module> import trees File "D:\Python\trees.py", line 11 shannonEnt = 0.0 ^ IndentationError: unindent does not match any outer indentation level以上三种都是有关缩进问题的报错,第二段代码是由于没有缩进导致报错,;第一段和第三段是由于空格和tab混用……
所以要注意缩进问题,空格和tab不能混用。
例子来源于《机器学习实战》决策树
def classify(inputTree, featLabels, testVec): firstStr = inputTree.keys()[0] #line 78 secondDict = inputTree[firstStr] featIndex = featLabels.index(firstStr) for key in secondDict.keys(): if testVec[featIndex] == key: if type(secondDict[key]).__name__ == 'dict': classLabel = classify(secondDict[key], featLabels, testVec) else: classLabel = secondDict[key] return classLabel如果使用上面的决策树分类函数,报错:
>>> trees.classify(myTree, labels, [1,0]) Traceback (most recent call last): File "<pyshell#9>", line 1, in <module> trees.classify(myTree, labels, [1,0]) File "D:\Python\trees.py", line 78, in classify firstStr = inputTree.keys()[0] TypeError: 'dict_keys' object does not support indexing这是因为Python2.x与3.x的差别导致的。这时我们可以用list(inputTree.keys())或者list(inputTree)来解决。
详细代码如下:
def classify(inputTree, featLabels, testVec): firstStr = list(inputTree.keys())[0] secondDict = inputTree[firstStr] featIndex = featLabels.index(firstStr) for key in secondDict.keys(): if testVec[featIndex] == key: if type(secondDict[key]).__name__ == 'dict': classLabel = classify(secondDict[key], featLabels, testVec) else: classLabel = secondDict[key] return classLabel
>>> trees.classify(myTree, labels, [1,0]) 'no'