Pythonエラー
一、インデント問題の報告ミスについて
インデントの問題に注意してください.スペースとtabは混用できません.
二、「dict_keys」オブジェクトはインデックスをサポートしない
例は「機械学習実戦」決定ツリーに由来する
詳細コードは次のとおりです.
>>> import trees
Traceback (most recent call last):
File "", line 1, in
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 "", line 1, in
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 "", line 1, in
import trees
File "D:\Python\trees.py", line 11
shannonEnt = 0.0
^
IndentationError: unindent does not match any outer indentation level
以上の3つはいずれもインデント問題に関するエラーであり、2段目のコードはインデントがないためエラーである.1段目と3段目はスペースとtabの混用で・・・インデントの問題に注意してください.スペースとtabは混用できません.
二、「dict_keys」オブジェクトはインデックスをサポートしない
例は「機械学習実戦」決定ツリーに由来する
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 "", line 1, in
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
これはPython 2のためです.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'