How to get the MSE of the node in the DecisionTreeRegressor of scikit-learn?
Nice question. You need tree_reg.tree_.impurity
.
Short answer:
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
Long answer using the boston
dataset with visual output:
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")
Compare MSE values with visual Output: