【问题标题】:Error by creating my own scorer with make_scorer in sklearn在 sklearn 中使用 make_scorer 创建自己的记分器时出错
【发布时间】:2021-12-30 18:07:26
【问题描述】:

在我看到的所有示例中,sklearn 的make_scorer 方法似乎都很简单,但是当我尝试在我的交叉验证中使用它时,它给了我所有的 NaN。然后我意识到make_scorer 中的某些东西不起作用,但我不知道是什么。我给你看一个小例子:

a1 = np.array([0, 9, 0])
b1 = np.array([0, 8, 0])

def my_func(y_true, y_pred):
    output = y_true[1]-y_pred[1]
    return output

my_fake_scorer = make_scorer(my_func)
my_fake_scorer(y_pred=b1, y_true=a1)

如果我跑:

my_func(y_pred=b1, y_true=a1) --> 1 (ok!)

如果我跑:

my_fake_scorer(y_pred=b1, y_true=a1) -->

TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_17304/3405218040.py in <module>
     10 
     11 my_fake_scorer = make_scorer(my_func)
---> 12 my_fake_scorer(y_pred=b1, y_true=a1)

TypeError: __call__() got an unexpected keyword argument 'y_pred'

【问题讨论】:

    标签: python machine-learning scikit-learn


    【解决方案1】:

    正如documentation 中所解释的,score_func(在您的情况下为 my_func)将 yy_pred 作为输入,而使用 make_scorer(在您的情况下为 my_fake_scorer)构建的得分手需要作为输入(拟合)estimatorXy

    from sklearn.metrics import make_scorer
    from sklearn.linear_model import LinearRegression
    from sklearn.model_selection import cross_val_score
    from sklearn.datasets import make_regression
    
    def score_func(y, y_pred):
        return y[1] - y_pred[1]
    
    scorer = make_scorer(score_func=score_func)
    
    X, y = make_regression(random_state=42)
    
    estimator = LinearRegression()
    estimator.fit(X, y)
    scorer(estimator, X, y)
    # 3.979039320256561e-13
    
    cross_val_score(
        estimator=LinearRegression(),
        scoring=scorer,
        X=X,
        y=y,
        cv=3
    )
    # array([137.27979897,   5.44388795, -32.34674175])
    

    【讨论】:

      猜你喜欢
      • 2018-03-14
      • 2020-07-26
      • 1970-01-01
      • 2017-09-17
      • 1970-01-01
      • 2015-11-30
      • 2016-12-18
      • 1970-01-01
      相关资源
      最近更新 更多