gpt4 book ai didi

python - 受过训练的 "Decision Tree"VS “Decision Path”

转载 作者:太空宇宙 更新时间:2023-11-04 00:06:01 25 4
gpt4 key购买 nike

我正在使用 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 )

示例数据:是目前生成的数据。

Cloud Provider,Comps,env,hosts,OS Upgrade Path,Target_OS_NAME,Target_OS_VERSION,Size,os_versionAWS,11,2,3833,不直接,Linux,4,M,2谷歌云,16,6,4779,Direct,Mac,3,S,1AWS,18,6,6677,不直接,Linux,7,S,8谷歌云,34,2,1650,直接,Windows,5,B,1AWS,35,6,9569,Direct,Windows,6,M,3AWS,36,6,7421,不直接,Windows,3,B,5谷歌云,49,4,3469,Direct,Mac,6,B,1AWS,54,5,5677,Direct,Mac,4,M,8

enter image description here

但是预测的测试数据的决策路径是:Comps [206] --> env [3] --> hosts [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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com