自定义评分函数 RandomForestRegressor

Custom scoring function RandomForestRegressor

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

现在不知道怎么用

best_estimator_ - 一个 RandomForestRegressor - 由搜索返回

我的自定义评分函数。

有没有办法将自定义评分函数传递给 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))