【问题标题】:make_scorer giving an error: 'str' object is not callable make_scorermake_scorer 给出错误:'str' 对象不可调用 make_scorer
【发布时间】:2017-06-12 23:16:26
【问题描述】:

我正在使用以下代码来优化随机森林算法,但这会引发类型错误:'str' object is not callable。你能帮我确定可能是什么原因吗?拟合线在 scorer.py 文件中为这个“score = scorer(estimator, X_test, y_test)”抛出错误

from sklearn.grid_search import GridSearchCV
from sklearn.metrics import roc_auc_score, make_scorer
clf_scorer = make_scorer('roc_auc')
rfc = RandomForestClassifier(n_estimators=100,oob_score=True)
param_grid = {
    'max_depth':[4,8,12],
}

cv_rfc = GridSearchCV(estimator=rfc, param_grid=param_grid, cv=5, 
scoring=clf_scorer)
cv_rfc.fit(train_data,target)

以下是来自 cross_validation.py 的给出错误的代码:

def _score(estimator, X_test, y_test, scorer):
    """Compute the score of an estimator on a given test set."""
    if y_test is None:
        score = scorer(estimator, X_test)
    else:
        **score = scorer(estimator, X_test, y_test)**
    if hasattr(score, 'item'):
        try:
            # e.g. unwrap memmapped scalars
            score = score.item()
        except ValueError:
            # non-scalar?
            pass
    if not isinstance(score, numbers.Number):
        raise ValueError("scoring must return a number, got %s (%s) instead."
                         % (str(score), type(score)))
    return score

【问题讨论】:

  • 该行不在您发布的代码中。请发布实际代码。
  • 另外,请始终发布错误的堆栈跟踪。错误的实际代码是一个加号,但并不总是需要。

标签: python string typeerror grid-search


【解决方案1】:

将第三行更改为:

clf_scorer = make_scorer(roc_auc_score)

第一个参数score_func 需要是一个可调用的评分函数。

【讨论】:

  • 基于这个链接scikit-learn.org/stable/modules/model_evaluation.html我们应该可以输入字符串'roc_auc'作为得分手的参数,对吧?
  • @AbhiGupta 是的,你可以,但不能在 make_scorer 中,你可以直接在 gridSearchCV 构造函数中使用'roc_auc'。
  • 没错。不幸的是,字符串功能不适用于 make_scorer。说不定他们以后加进去会是件好事……
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-30
  • 1970-01-01
  • 1970-01-01
  • 2016-12-18
  • 2021-01-16
  • 2018-04-24
  • 1970-01-01
相关资源
最近更新 更多