如何在sklearn cross_val_score中使用自定义评分功能

时间:2018-12-19 12:02:00

标签: python python-3.x machine-learning scikit-learn sklearn-pandas

我想在cross_val_score函数中使用 Adjusted Rsquare 。我尝试使用make_scorer函数,但无法正常工作。

from sklearn.cross_validation import train_test_split
X_tr, X_test, y_tr, y_test = train_test_split(X, Y, test_size=0.2, random_state=0)

regression = LinearRegression(normalize=True)
from sklearn.metrics.scorer import make_scorer
from sklearn.metrics import r2_score
def adjusted_rsquare(y_true,y_pred):
    adjusted_r_squared = 1 - (1-r2_score(y_true, y_pred))*(len(y_pred)-1)/(len(y_pred)-X_test.shape[1]-1)
    return adjusted_r_squared

my_scorer = make_scorer(adjusted_rsquare, greater_is_better=True)
score = np.mean(cross_val_score(regression, X_tr, y_tr, scoring=my_scorer,cv=crossvalidation, n_jobs=1))

正在处理错误:

IndexError: positional indexers are out-of-bounds

有什么方法可以使用我的自定义函数,即; adjusted_rsquarecross_val_score

1 个答案:

答案 0 :(得分:0)

adjusted_rsquare(X,Y)是一个数字,它不是一个函数,只需像这样创建计分器即可:

my_scorer = make_scorer(adjusted_rsquare, greater_is_better=True)

您还需要change the score function

def adjusted_rsquare(y_true, y_pred, **kwargs):

那是您应该使用的原型。您将实际结果与应有的结果进行比较。