自定义评分函数随机森林回归器



使用RandomSearchCV,我设法找到了一个具有最佳超参数的RandomForestRegressor。 但是,为此,我使用了符合我特定需求的自定义分数函数。

现在,我不知道如何使用

best_estimator_ - 一个随机森林回归器 - 由搜索返回

使用我的自定义评分功能。

有没有办法将自定义评分函数传递给RandomForestRegressor

>RandomizedSearchCV中的评分函数将仅计算网格中指定的每个超参数组合的模型中预测数据的分数,并且测试折叠中平均得分最高的超参数获胜。

它不会以任何方式改变 RandomForest 内部算法的行为(当然,除了查找超参数(。

现在您已经有了best_estimator_(RandomForestRegressor(,已经设置了找到的最佳超参数,并且模型已经在您发送给RandomizedSearchCV的整个数据上进行了训练(如果您使用了refit=True,默认情况下True(。

所以我不确定你想怎么把这个记分器传递给模型。best_estimator_模型可以直接用于通过predict()方法获取对新数据的预测。之后,可以使用您使用的自定义评分将预测与实际模型进行比较。没有别的了。

一个简单的例子是:

from scipy.stats import randint as sp_randint
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import RandomizedSearchCV, train_test_split
from sklearn.datasets import load_boston
from sklearn.metrics import r2_score, make_scorer
X, y = load_boston().data, load_boston().target
X_train, X_test, y_train, y_test = train_test_split(X, y)
clf = RandomForestRegressor()
# Your custom scoring strategy
def my_custom_score(y_true, y_pred):
return r2_score(y_true, y_pred)
# Wrapping it in make_scorer to able to use in RandomizedSearch
my_scorer = make_scorer(my_custom_score)
# Hyper Parameters to be tuned
param_dist = {"max_depth": [3, None],
"max_features": sp_randint(1, 11),
"min_samples_split": sp_randint(2, 11),}
random_search = RandomizedSearchCV(clf, param_distributions=param_dist,
n_iter=20, scoring=my_scorer)
random_search.fit(X_train, y_train)
# Best found parameters set and model trained on X_train, y_train
best_clf = random_search.best_estimator_
# Get predictions on your new data
y_test_pred = best_clf.predict(X_test)
# Calculate your score on the predictions with respect to actual values
print(my_custom_score(y_test, y_test_pred))

最新更新