如何在 sklearn DecisionTreeClassifier 中走特定路径

问题描述 投票:0回答:1

这里有点菜鸟,我很难找到解决方案:

这是我的决策树:

这是输出

print(dt.tree_.__getstate__())

{'max_depth': 3, 'node_count': 7,
'nodes': array([( 1,  6, 19,  0.5, 0.41848786, 1382, 1382.),
( 2,  5, 12,  0.5, 0.49534472,  912,  912.),
( 3,  4,  3,  0.5, 0.43366519,  604,  604.),
(-1, -1, -2, -2. , 0.33618881,  449,  449.),
(-1, -1, -2, -2. , 0.47150884,  155,  155.),
(-1, -1, -2, -2. , 0.        ,  308,  308.),
(-1, 1, -2, -2. , 0.        ,  470,  470.)],
dtype=[('left_child', '<i8'), ('right_child', '<i8'), ('feature', '<i8'), ('threshold', '<f8'), ('impurity', '<f8'), ('n_node_samples', '<i8'), ('weighted_n_node_samples', '<f8')]), 'values': array([[[970., 412.]],
[[500., 412.]],
[[192., 412.]],
[[ 96., 353.]],
[[ 96.,  59.]],
[[308.,   0.]],
[[470.,   0.]]])}

(我冒昧地重新格式化了一下,因为 SO 一直在抱怨)。

这是我的任务:

  • 确定样本决策树的最终结果(类别):
buying_vhigh = 1
persons_2 = 0
safety_low = 0

我的问题是:有没有办法在代码(python)中做到这一点?显然通过检查是微不足道的,但我希望能够让机器去做。

python scikit-learn decision-tree
1个回答
0
投票

一种方法是将您的值放入字典中,然后依次将其放入

DataFrame
。通过这样做,变量被命名并且它们不必以正确的顺序排列。但是上课的关键部分是使用
dt.predict()

import pandas as pd

# Define the given sample with feature names
sample = {
    'buying_vhigh': 1,
    'persons_2': 0,
    'safety_low': 0
}

# Create a pandas DataFrame with the given sample
sample_df = pd.DataFrame([sample])

# Use the predict method to make a prediction for the given sample
prediction = dt.predict(sample_df)

# Print the predicted class
print("The predicted class is:", prediction[0])
© www.soinside.com 2019 - 2024. All rights reserved.