pandas 使用 Graphviz 绘制决策树时出现“特征名称的长度与特征数量不匹配”错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47826905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
'Length of feature names doesn't match with number of features' error while plotting decision tree using Graphviz
提问by pankaj
I am trying to visualize a decision tree using graphviz and while trying to plot the decision tree I am getting the below error :
我正在尝试使用 graphviz 可视化决策树,并在尝试绘制决策树时出现以下错误:
~\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\tree\export.py in export_graphviz(decision_tree, out_file, max_depth, feature_names, class_names, label, filled, leaves_parallel, impurity, node_ids, proportion, rotate, rounded, special_characters, precision)
427 "does not match number of features, %d"
428 % (len(feature_names),
--> 429 decision_tree.n_features_))
430
431 # The depth of each node for plotting with 'leaf' option
ValueError: Length of feature_names, 225 does not match number of features,
208
208
My code
我的代码
dt=DecisionTreeClassifier(class_weight="balanced", min_samples_leaf=30)
fit_decision=dt.fit(X_train_res,y_train_res)
from graphviz import Source
from sklearn import tree
Source( tree.export_graphviz(fit_decision, out_file=None, feature_names=data.columns))
Can you tell me what went wrong?
你能告诉我出了什么问题吗?
回答by Mohammed Kashif
Your data.columns contains names of all the features+label since it is not divided into X_train_res and y_train_res. You need to pass the feature names in in X_train_res instead of data.columns to get the exact features else it will include the labels as well. I am assuming that X_train and y_train are derived from data
in this case.
您的 data.columns 包含所有特征+标签的名称,因为它没有分为 X_train_res 和 y_train_res。您需要在 X_train_res 而不是 data.columns 中传递特征名称以获取确切的特征,否则它将包括标签。我假设 X_train 和 y_train 来自data
这种情况。