【问题标题】:Custom 'Precision at k' scoring object in sklearn for GridSearchCVGridSearchCV 的 sklearn 中的自定义“k 精度”评分对象
【发布时间】:2015-10-17 04:18:29
【问题描述】:

我目前正在尝试使用 scikit-learn 中的 GridSearchCV 调整超参数,使用“Precision at k”评分指标,如果我将分类器得分的前第 k 个百分位数分类为正类,这将给我精确度。我知道可以使用 make_scorer 创建一个自定义记分器并创建一个 score 函数。这就是我现在拥有的:

from sklearn import metrics
from sklearn.grid_search import GridSearchCV
from sklearn.linear_model import LogisticRegression

def precision_at_k(y_true, y_score, k):
    df = pd.DataFrame({'true': y_true, 'score': y_score}).sort('score')
    threshold = df.iloc[int(k*len(df)),1]
    y_pred = pd.Series([1 if i >= threshold else 0 for i in df['score']])
    return metrics.precision_score(y_true, y_pred)

custom_scorer = metrics.make_scorer(precision_at_k, needs_proba=True, k=0.1)

X = np.random.randn(100, 10)
Y = np.random.binomial(1, 0.3, 100)

train_index = range(0, 70)
test_index = range(70, 100)
train_x = X[train_index]
train_Y = Y[train_index]
test_x = X[test_index]
test_Y = Y[test_index]

clf = LogisticRegression()
params = {'C': [0.01, 0.1, 1, 10]}
clf_gs = GridSearchCV(clf, params, scoring=custom_scorer)
clf_gs.fit(train_x, train_Y)

但是,尝试拨打 fit 时会得到 Exception: Data must be 1-dimensional,但我不知道为什么。任何人都可以帮忙吗?提前致谢。

【问题讨论】:

  • 我在阅读此discussion 后发现了一个不错的实现here 希望它有所帮助

标签: python scikit-learn cross-validation grid-search


【解决方案1】:

pd.DataFrame 的参数应该是 'list' 而不是 'numpy.arrays'

所以,只需尝试将 y_true 转换为 python 列表...

df = pd.DataFrame({'true': y_true.tolist(), 'score': y_score.tolist()}).sort('score')

【讨论】:

    猜你喜欢
    • 2015-10-15
    • 2020-07-28
    • 2023-03-21
    • 2018-11-05
    • 2018-09-09
    • 2019-06-01
    • 2016-02-20
    • 1970-01-01
    • 2018-11-28
    相关资源
    最近更新 更多