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

How to use make_scorer Custom scoring function in sklearn

我正在尝试实现一个最高分位数 recall/precision 评分函数以插入到 gridsearchCV 中。但是,我无法弄清楚出了什么问题。我想要做的是让我的评分函数考虑概率预测、实际标签和理想情况下的十分位数阈值百分比。然后我会对分数进行排序,然后确定十分位数阈值内的转换率。例如。前 10% 人群的转化率。该转换率将是我输出的分数。越高越好。但是,当我 运行 下面的代码时,我没有得到概率分数,我也不明白评分函数的输入是什么。下面的打印语句 return 只有 1 和 0 而不是概率。

def top_decile_conversion_rate(y_prob, y_actual):
    # Function goes in here
    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):
    # Function goes in here
    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)