python - sklearn中make_scorer中的自定义函数
问题描述
我正在尝试创建一个自定义评分函数以在 GridSearchCV 中实现分类问题,但我认为我不太了解它的工作原理(我已阅读文档)。我的目标是对错误分类的类型赋予不同的权重。我的代码如下所示。good
并且excellent
是我的样本所属的两个类别。我认为问题在于何时GridSearchCV
将真实值和预测值传递给score_func
但我不知道如何解决它。
def score_func(y, y_pred):
'''score function for grid search'''
error = 0
for i in range(len(y)):
if y[i] == 'excellent':
if y_pred[i] == 'excellent':
error += 10
elif y_pred[i] == 'good':
error += 5
return error
score_f = make_scorer(score_func, needs_proba=False ,needs_threshold=False)
RF = make_pipeline(
StandardScaler(),
RandomForestClassifier(random_state=101, criterion = 'gini')
)
gs_rf = GridSearchCV(estimator=RF, param_grid=param_grid, scoring=score_f,
cv=KFold(5, True, random_state=1234)).fit(X_data,y_data)
提前致谢!
解决方案
如果您的目标是为标签关联权重,则无需创建函数。
只需使用class_weight
参数 from RandomForestClassifier
。
weight_dict = {'excellent':10, 'good':5}
RandomForestClassifier(random_state=101, criterion='gini', class_weight=weight_dict)
推荐阅读
- javascript - 我在 django 中实现 css 和 js 动画文件时遇到问题
- python - 将频率“MS”设置为熊猫数据时间对象 - python
- c++ - -fshort-wchar 和 std::wstring - 分段错误
- c - 将多个动态流合并为一个
- python - RPG角色模拟器创建随机角色
- kotlin - 如何将字符串传递给 Kotlin 中的变量类型 URL?
- python - 在python中排序的“错误”字典的零索引位置插入列名作为(“错误”,“计数”)
- java - Exoplayer 线程错误 NoSuchElementExceptionat java.util.ArrayDeque.removeFirst
- amazon-web-services - 如何自动化 aws 托管 UI 的徽标
- vba - 在报表中使用 VBA 循环根据查询字段创建多个 PDF