我一直在研究基本的DecisionTree分类器,我需要我的模型在每个节点处提出问题。基本上,我的疾病预测者应该根据用户告诉的症状来猜测疾病。所以我想在每个阶段询问用户是否有特定的症状(在节点处分裂)并使用它来预测输出。
详细,这是我当前的代码段:
import pandas as pd
import numpy as np
from sklearn import tree
..
..
#import data from db and store in variables
..
clf = tree.DecisionTreeClassifier(criterion='entropy', splitter='best')
clf = clf.fit(relations,diseaseCodes)
print(clf.predict([relations[10]]))
这里,我必须一次性提供所有值的完整列表。我想在每个步骤中问用户问题,例如您现在患有哪种症状,并根据其对疾病进行分类。
注意::我知道我的决策树已过拟合。
您可以从this answer改编它,它打印出树的决策路径
为此,您可以手动遍历拟合的树,通过公共api访问不可用的属性。
首先,让我们使用虹膜数据集获得拟合树:
data = load_iris()
clf = DecisionTreeClassifier(max_depth=3).fit(data['data'],data['target'])
让我们可视化这棵树,主要是调试我们的最终程序:
plt.figure(figsize=(10,8))
plot_tree(clf,feature_names=data['feature_names'],class_names=data['target_names'],filled=True);
现在是主要部分。从link,我们知道-
二叉树tree_表示为多个并行数组。每个数组的第i个元素保存有关节点
i
的信息。我们需要的数组是
feature
,“值”和threshold
。因此,从根(i=0
)开始,我们首先收集访问的每个节点的特征和阈值,询问用户该特定特征的值,然后根据该特征向左或向右遍历。当我们到达一片叶子时,我们在该叶子中找到了最常出现的类,并最终退出了循环。tree = clf.tree_ node = 0 #Index of root node while True: feat,thres = tree.feature[node],tree.threshold[node] print(feat,thres) v = float(input(f"The value of {data['feature_names'][feat]}: ")) if v<=thres: node = tree.children_left[node] else: node = tree.children_right[node] if tree.children_left[node] == tree.children_right[node]: #Check for leaf label = np.argmax(tree.value[node]) print("We've reached a leaf") print(f"Predicted Label is: {data['target_names'][label]}") break
上面树的这种运行的示例是:
3 0.800000011920929
The value of petal width (cm): 1
3 1.75
The value of petal width (cm): 1.5
2 4.950000047683716
The value of petal length (cm): 5.96
We've reached a leaf
Predicted Label is: virginica