首页 > 解决方案 > 修改“max_depth”时,如何将 DecisionTreeRegressor 的结果保存到不同的数组?

问题描述

我有以下问题:我正在使用 DecisionTreeRegressor 并且需要在更改“max_depth”时保存我的 RSME(训练和测试)的结果。

from sklearn.tree import DecisionTreeRegressor
tree_reg = DecisionTreeRegressor(max_depth=25)
tree_reg.fit(X_train, y_train)

y_train_pred = tree_reg.predict(X_train)
from sklearn.metrics import mean_squared_error
tree_train_mse = mean_squared_error(y_train, y_train_pred)
print("RMSE Train: ", np.sqrt(tree_train_mse))
RMSE Train:  2178.5783334392877 # this is the value to save

y_test_pred = tree_reg.predict(X_test)
tree_test_mse = mean_squared_error(y_test, y_test_pred)
print("RMSE Test: ", np.sqrt(tree_test_mse))
RMSE Test:  25188.114240007588 # this is other value to save

标签: pythonnumpyscikit-learn

解决方案


如果您希望以纯txt格式保存文件,您可以使用它保存它

with open('RMSE.txt', 'a') as f: # note that "a" is to append each line on top of your file
    f.write("max_depth: " + max_depth)
    f.write("RMSE Train: " + np.sqrt(tree_train_mse))
    f.write("RMSE Test: " + np.sqrt(tree_test_mse))
    f.write('\n')

如果您正在执行可能会破坏脚本的长时间操作,那么将所有内容都保存在您的计算机内存中通常是不好的。您可以做的是保存到一个普通txt文件中,以便将来访问。


推荐阅读