python - 训练 "Decision Tree"VS “Decision Path”

标签 python machine-learning

我正在使用 scikit“决策树”分类器来预测迁移项目的“工作量”。我的要求的另一部分是找到影响预测的特征。

我训练了模型,得到了一个层次树,其中所有特征都位于不同的节点。

我认为当我提供测试记录时,将使用同一棵树来预测大小。但令我惊讶的是,事实并非如此!!

预测后,我打印了 Decision_path 以查看“该预测中考虑的特征”。

这个决策路径与模型构建的树完全不同。

如果树不用来预测,树还有什么用。

如何使用决策路径来获取该预测中的重要特征?

如果我导出这些规则集并用于查找决策路径,则会给出错误的特征或与决策路径的输出不匹配。

编辑 1

添加了通用代码。它给出了类似的输出。

from __future__ import print_function
import pandas as pd
import numpy as np

from sklearn import preprocessing
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn import tree
# Create tree object 
import graphviz
import pydotplus
import collections

file_path = "sample_data_generic.csv"
data = pd.read_csv( file_path )
data.head()

df = data.copy()
cols = df.columns
col_len = len(cols)
features_category = []

for col_index in range( col_len ):
    if df[ cols[col_index] ].dtype == 'object' or df[ cols[col_index] ].dtype == 'float64':
        df[ cols[col_index] ] = df[ cols[col_index] ].astype('category')
        features_category.append( cols[col_index] )

#redefining the variable value as it is throwing some error in the below lines due to the presence of next line char?!
features_category = ['Cloud Provider', 'OS Upgrade Path', 'Target_OS_NAME', 'Target_OS_VERSION', 'os_version']

# create dataframe for target variable
df_target = df['Size']
df.drop('Size', axis=1, inplace=True)

df = pd.get_dummies(df, columns=features_category, dtype='int')

df.head()

df_x_data = df.copy()
df_x_data.head()
y_data = df_target
target_classes = y_data.unique()
target_classes = target_classes.astype('category')
test_size_val = 0.3

x_train, x_test, y_train, y_test = train_test_split(df_x_data, y_data, test_size=test_size_val, random_state=1)


print("number of test samples :", x_test.shape[0])
print("number of training samples:",x_train.shape[0])

x_train.sort_values(['Comps'], ascending=[True]) #, 'Estimation'
model = tree.DecisionTreeClassifier()
model = model.fit(x_train, y_train)
model.score(x_test, y_test)
dot_data = tree.export_graphviz(model, out_file=None, 
                     feature_names=x_train.columns,  
                     class_names=target_classes,  
                     filled=True, rounded=True,  
                     special_characters=True)  
graph = pydotplus.graph_from_dot_data(dot_data)
print('graph: ', graph)
colors = ('white','red', 'green')

edges = collections.defaultdict(list)

for edge in graph.get_edge_list():
    edges[edge.get_source()].append(int(edge.get_destination()))
print( edges )
for edge in edges:
    edges[edge].sort()
    for i in range(2):
        dest = graph.get_node(str(edges[edge][i]))[0]
        dest.set_fillcolor(colors[i])
        
graph.write_png('decision_tree_2019_generic.png')

from IPython.display import Image
Image(filename = 'decision_tree_2019_generic.png')

to_predict = x_test[3:4]
model.predict( to_predict )

to_predict.values

applied = model.apply( to_predict )
applied

to_predict

decision_path = model.decision_path( to_predict )
print( decision_path.indices, '\n' )
print( decision_path[:1][:1])

predict_cols = decision_path.indices

predicted_row = to_predict
cols = predicted_row.columns
#print("len of cols: ", len(cols) )
for col in predict_cols:
    print( cols[col], predicted_row[ cols[col] ].values )

样本数据:目前是生成的数据。

云提供商、Comps、env、主机、操作系统升级路径、Target_OS_NAME、Target_OS_VERSION、大小​​、os_version AWS,11,2,3833,非直接,Linux,4,M,2 谷歌云,16,6,4779,直接,Mac,3,S,1 AWS,18,6,6677,非直接,Linux,7,S,8 谷歌云,34,2,1650,直接,Windows,5,B,1 AWS,35,6,9569,直接,Windows,6,M,3 AWS,36,6,7421,非直接,Windows,3,B,5 谷歌云,49,4,3469,直接,Mac,6,B,1 AWS,54,5,5677,直接,Mac,4,M,8

enter image description here

但是预测的测试数据的决策路径是: 比较 [206] --> 环境 [3] --> 主机 [637]

提前致谢

最佳答案

我认为您误解了decision_path的返回值:它使用树内部表示中的节点索引返回一个稀疏矩阵,指示预测经过树的哪些节点。这些并不意味着(实际上也没有)与数据集的列对齐。相反,如果您想访问哪些功能与预测经过的节点相关,请尝试:

predict_nodes = decision_path.indices
predicted_row = to_predict
cols = predicted_row.columns
for node in predict_nodes:
    col = model.tree_.feature[node]
    print( cols[col], predicted_row[ cols[col] ].values )

请注意,叶节点显然没有测试功能,并且(根据我的经验)返回功能索引的负值,因此也要注意这一点。

要了解有关树内部结构的更多信息,请参阅 this例如,并且(按照文档的建议)使用 help(sklearn.tree._tree.Tree)

关于python - 训练 "Decision Tree"VS “Decision Path”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54058350/

相关文章:

python - 在 Python 中枚举相机

python - 列表推导比 for 循环有什么优势?

image - 如何从头开始创建和格式化图像数据集以用于机器学习?

python - 是否可以读取一个空的 csv 文件?

python - Micromamba 和 Dockerfile 错误 :/bin/bash: activate: No such file or directory

python - asp.net 破解 sessionId 使用 python 脚本被暴力破解的可能性

machine-learning - 使用 ANN 计算位置向量的长度以及它与 x 轴之间的角度

python - ValueError : Error when checking input: expected cu_dnnlstm_22_input to have 3 dimensions, 但得到形状为 (2101, 17) 的数组

machine-learning - 使用 scikit-learn 对文本文档进行分类的交叉验证

machine-learning - 如何更新反卷积层的权重?