如何在sklearn中使用make_scorer自定义评分函数

我正在尝试实现一个用于插入gridsearchCV的顶部十分位召回/精确度评分函数。然而,我无法找出问题所在。我希望我的评分函数能够接受概率预测、实际标签,并理想情况下接受百分比形式的十分位阈值。然后,我将对分数进行排名,并在十分位阈值内识别转换率。例如,顶部10%人群的转换率。该转换率将是我输出的分数,分数越高越好。然而,当我运行下面的代码时,我没有得到概率分数,并且我不明白评分函数的输入是什么。下面的打印语句只返回1和0,而不是概率。

def top_decile_conversion_rate(y_prob, y_actual):    # 函数内容在此处
    print y_prob, y_actual
    return 0.5
features = pd.DataFrame({"f1":np.random.randint(1,1000,500) , "f2":np.random.randint(1,1000,500),
                          "label":[round(x) for x in np.random.random_sample(500)]})
my_scorer = make_scorer(top_decile_conversion_rate, greater_is_better=True)
gs = grid_search.GridSearchCV(
    estimator=LogisticRegression(),
    param_grid={'C': [i for i in range(1, 3)], 'class_weight': [None], 'penalty':['l2']},
    cv=2,
    scoring=my_scorer )
model = gs.fit(features[["f1","f2"]], features.label)

回答:

解决方案是在make_scorer函数中添加一个名为needs_proba=True的参数!这样可以正常工作。

def top_decile_conversion_rate(y_prob, y_actual):    # 函数内容在此处
    print "---prob--"
    print y_prob
    print "---actual--"
    print y_actual
    print "---end--"
    return 0.5
features = pd.DataFrame({"f1":np.random.randint(1,1000,500) , "f2":np.random.randint(1,1000,500),
                          "label":[round(x) for x in np.random.random_sample(500)]})
my_scorer = make_scorer(top_decile_conversion_rate, greater_is_better=True,needs_proba=True)
gs = grid_search.GridSearchCV(
    estimator=LogisticRegression(),
    param_grid={'C': [i for i in range(1, 3)], 'class_weight': [None], 'penalty':['l2']},
    cv=20,
    scoring=my_scorer )
model = gs.fit(features[["f1","f2"]], features.label)

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注