如何获取scikit-learn的DecisionTreeRegressor中节点的MSE?

Roa*_*ach 7 python scikit-learn

在生成的决策树回归模型中,graphviz用于查看树结构时有一个MSE属性。我需要获取每个叶子节点的MSE,并根据MSE进行后续操作。但是,在阅读文档后,我找不到提供输出 MSE 的方法。其他属性如特征名称、样本数、预测值等,都有对应的方法:

树状结构

使用help(sklearn.tree._tree.Tree),我可以看到大多数属性都有一些输出值的方法,但是我没有看到有关 MSE 的任何内容。

帮助模块 sklearn.tree._tree 中的 Tree 类 帮助模块 sklearn.tree._tree 中的 Tree 类

mak*_*kis 6

好问题。你需要tree_reg.tree_.impurity.

简短的回答:

tree_reg = tree.DecisionTreeRegressor(max_depth=2)
tree_reg.fit(X_train, y_train)

extracted_MSEs = tree_reg.tree_.impurity # The Hidden magic is HERE

for idx, MSE in enumerate(tree_reg.tree_.impurity):
    print("Node {} has MSE {}".format(idx,MSE))

Node 0 has MSE 86.873403833
Node 1 has MSE 40.3211827171
Node 2 has MSE 25.6934820064
Node 3 has MSE 19.0053469592
Node 4 has MSE 74.6839429717
Node 5 has MSE 38.3057346817
Node 6 has MSE 39.6709615385

Run Code Online (Sandbox Code Playgroud)

使用boston具有视觉输出的数据集的长答案:

import pandas as pd
import numpy as np
from sklearn import ensemble, model_selection, metrics, datasets, tree
import graphviz

house_prices = datasets.load_boston()

X_train, X_test, y_train, y_test = model_selection.train_test_split(
    pd.DataFrame(house_prices.data, columns=house_prices.feature_names),
    pd.Series(house_prices.target, name="med_price"),
    test_size=0.20, random_state=42)

tree_reg = tree.DecisionTreeRegressor(max_depth=2)
tree_reg.fit(X_train, y_train)

extracted_MSEs = tree_reg.tree_.impurity # YOU NEED THIS 
print(extracted_MSEs)
#[86.87340383 40.32118272 25.69348201 19.00534696 74.68394297 38.30573468 39.67096154]

# Compare visually
dot_data = tree.export_graphviz(tree_reg, out_file=None, feature_names=X_train.columns)
graph = graphviz.Source(dot_data)

#this will create an boston.pdf file with the rule path
graph.render("boston")
Run Code Online (Sandbox Code Playgroud)

将 MSE 值与视觉输出进行比较:

在此处输入图片说明