决策树模型python实现代码
时间: 2024-06-02 15:05:40 浏览: 179
Machine-Learning-决策树python代码
决策树模型的Python实现代码如下所示:
1. 创建决策树
```python
def createTree(dataSet, labels):
classList = [example[-1] for example in dataSet]
if classList.count(classList[0]) == len(classList):
return classList[0]
if len(dataSet[0]) == 1:
return majorityCnt(classList)
bestFeat = chooseBestFeatureToSplit(dataSet)
bestFeatLabel = labels[bestFeat]
myTree = {bestFeatLabel: {}}
del (labels[bestFeat])
featValues = [example[bestFeat] for example in dataSet]
uniqueVals = set(featValues)
for value in uniqueVals:
subLabels = labels[:]
myTree[bestFeatLabel][value] = createTree(splitDataSet(dataSet, bestFeat, value), subLabels)
return myTree
```
2. 使用决策树进行分类
```python
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
```
3. 存储和加载决策树
```python
import pickle
def storeTree(inputTree, filename):
with open(filename, 'wb') as fw:
pickle.dump(inputTree, fw)
def grabTree(filename):
with open(filename, 'rb') as fr:
return pickle.load(fr)
```
以上是决策树模型的Python实现代码,其中包括了创建决策树、使用决策树进行分类、存储和加载决策树等功能。
阅读全文