Python 自定义评分函数

Python 自定义评分函数,python,scikit-learn,random-forest,Python,Scikit Learn,Random Forest,使用RandomSearchCV,我设法找到了一个具有最佳超参数的randomsforestregressor。 但是,为了实现这一点,我使用了一个与我的特定需求相匹配的自定义分数函数 现在,我不知道如何使用 最佳估计量-一个随机森林回归器-由搜索返回 使用我的自定义评分功能 是否有方法将自定义评分函数传递给RandomForestRegressionor?RandomizedSearchCV中的评分函数将仅计算网格中指定的每个超参数组合的模型预测数据的评分,测试中平均得分最高的超参数获胜 它不

使用
RandomSearchCV
,我设法找到了一个具有最佳超参数的
randomsforestregressor
。 但是,为了实现这一点,我使用了一个与我的特定需求相匹配的自定义分数函数

现在,我不知道如何使用

最佳估计量-一个随机森林回归器-由搜索返回

使用我的自定义评分功能


是否有方法将自定义评分函数传递给
RandomForestRegressionor

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

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

现在您有了
best_estimator\uuuu
(一个RandomForestRegressionor),已经设置了找到最好的超参数,并且模型已经针对发送到
RandomizedSearchCV
的整个数据进行了训练(如果您使用
refit=True
,默认情况下为
True

所以我不确定你想把那个得分手传给模特做什么。通过使用
predict()
方法,可以直接使用
best\u估计器
模型对新数据进行预测。之后,您使用的自定义评分可用于将预测与实际模型进行比较。没什么了

一个简单的例子是:

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))

@tehlinger
best\u estimator\u
是拟合模型。好吧,我只是对超调和拟合之间的区别理解得不好。非常感谢你