【问题标题】:Custom scoring on GridSearchCV with fold dependent parameterGridSearchCV 上的自定义评分与折叠相关参数
【发布时间】:2018-02-28 23:19:44
【问题描述】:

问题

我正在研究一个学习排名问题,其中标准是对点进行评估的预测,但对模型性能进行分组评估。

更具体地说,估计器输出一个连续变量(很像回归器)

> y = est.predict(X); y
array([71.42857143,  0.        , 71.42857143, ...,  0.        ,
       28.57142857,  0.        ])

但评分功能需要通过查询聚合,即对预测进行分组,类似于发送给GridSearchCVgroups参数以尊重折叠分区。

> ltr_score(y_true, y_pred, groups=g)
0.023

障碍

到目前为止一切顺利。当向GridSearchCV 提供自定义评分功能时,事情变得更糟了,我无法根据 CV 折叠动态更改评分功能中的 groups 参数:

from sklearn.model_selection import GridSearchCV
from sklearn.metrics import make_scorer

ltr_scorer = make_scorer(ltr_score, groups=g)  # Here's the problem, g is fixed
param_grid = {...}

gcv = GridSearchCV(estimator=est, groups=g, param_grid=param_grid, scoring=ltr_scorer)

解决这个问题最简单的方法是什么?

一种(失败的)方法

similar question 中,一条评论询问/建议:

您为什么不能只在本地存储 {the grouping column} 并在必要时通过拆分器提供的训练测试索引进行索引来使用它?

OP 回答“似乎可行”。我认为这也是可行的,但无法使其工作。显然,GridSearchCV 将首先消耗所有交叉验证拆分索引,然后才执行拆分、拟合、预测和评分。这意味着我不能(似乎)尝试在评分时猜测创建当前拆分子选择的原始索引。

为了完整起见,我的代码:

class QuerySplitScorer:
    def __init__(self, X, y, groups):
        self._X = np.array(X)
        self._y = np.array(y)
        self._groups = np.array(groups)
        self._splits = None
        self._current_split = None

    def __iter__(self):
        self._splits = iter(GroupShuffleSplit().split(self._X, self._y, self._groups))
        return self

    def __next__(self):
        self._current_split = next(self._splits)
        return self._current_split

    def get_scorer(self):
        def scorer(y_true, y_pred):
            _, test_idx = self._current_split
            return _score(
                y_true=y_true,
                y_pred=y_pred,
                groups=self._groups[test_idx]
            )

用法:

qss = QuerySplitScorer(X, y_true, g)
gcv = GridSearchCV(estimator=est, cv=qss, scoring=qss.get_scorer(), param_grid=param_grid, verbose=1)
gcv.fit(X, y_true)

它不起作用,self._current_split 固定在最后生成的拆分处。

【问题讨论】:

  • 作为想法,您可以在GridSearchCV 上将KFold 对象作为cv 参数提供。所以你可以手动弃牌,设置得分手,然后运行搜索。
  • @iliatimofeev 这基本上就是我正在做的事情,问题是记分员没有简单的方法来识别他正在使用哪个折叠来正确地从groups 中进行子选择。你的意思是我应该通过一个弃牌?
  • 另一个疯狂的想法,y 可能是一个矩阵“zip(y,g)”,因此您将需要切割第一列的估算器包装器,但记分器两者都可以。 source

标签: python numpy scikit-learn


【解决方案1】:

据我了解,评分值是对 (value,group),但估算器不应与组一起使用。让我们把它们放在一个包装纸里,但把它们留给得分手。

简单的估算器包装器(可能需要一些完善才能完全合规)

from sklearn.base import BaseEstimator, ClassifierMixin, TransformerMixin, clone
from sklearn.linear_model import LogisticRegression
from sklearn.utils.estimator_checks import check_estimator
#from sklearn.utils.validation import check_X_y, check_array, check_is_fitted
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import make_scorer

class CutEstimator(BaseEstimator):

    def __init__(self, base_estimator):
        self.base_estimator = base_estimator

    def fit(self, X, y):
        self._base_estimator = clone(self.base_estimator)
        self._base_estimator.fit(X,y[:,0].ravel())
        return self

    def predict(self, X):
        return  self._base_estimator.predict(X)

#check_estimator(CutEstimator(LogisticRegression()))

那么我们就可以使用它了

def my_score(y, y_pred):

    return np.sum(y[:,1])


pagam_grid = {'base_estimator__C':[0.2,0.5]}

X=np.random.randn(30,3)
y=np.random.randint(3,size=(X.shape[0],1))
g=np.ones_like(y)

gs = GridSearchCV(CutEstimator(LogisticRegression()),pagam_grid,cv=3,
             scoring=make_scorer(my_score), return_train_score=True
            ).fit(X,np.hstack((y,g)))

print (gs.cv_results_['mean_test_score']) #10 as 30/3
print (gs.cv_results_['mean_train_score']) # 20 as 30 -30/3

输出:

 [ 10.  10.]
 [ 20.  20.]

更新 1:黑客方式但估算器没有变化:

pagam_grid = {'C':[0.2,0.5]}
X=np.random.randn(30,3)
y=np.random.randint(3,size=(X.shape[0]))
g=np.random.randint(3,size=(X.shape[0]))
cv = GroupShuffleSplit (3,random_state=100)
groups_info = {}
for a,b in cv.split(X, y, g):
    groups_info[hash(y[b].tobytes())] =g[b]
    groups_info[hash(y[a].tobytes())] =g[a]

def my_score(y, y_pred):
    global groups_info
    g = groups_info[hash(y.tobytes())]
    return np.sum(g)

gs = GridSearchCV(LogisticRegression(),pagam_grid,cv=cv, 
             scoring=make_scorer(my_score), return_train_score=True,
            ).fit(X,y,groups = g)
print (gs.cv_results_['mean_test_score']) 
print (gs.cv_results_['mean_train_score']) 

【讨论】:

  • 我在脑海中想过这种可能性,但它确实有点像胶带解决方案。我只想通过计分技巧来解决计分问题,甚至可能对 GridSearch 稍作改动……而不是估计器。但是解决方案就是解决方案,如果我很快找不到更好的解决方案,我会接受这个。
  • 我已经检查了GridSearchCV,您的问题位于_fit_and_score,这是从BaseSearchCV.fit 调用的普通函数,没有任何机会被覆盖。因此,如果您想将不同的y 放入fitscore 中,那么在GridSearchCV 中重写fit 也将花费大量精力。
  • 哈,使用散列是一种很好的技巧——我想即使是相同的记录也会产生(几乎可以肯定)不同的散列,因为它们是不同的对象。
猜你喜欢
  • 2017-03-04
  • 2017-08-17
  • 2018-08-07
  • 2015-10-17
  • 2014-06-23
  • 2021-07-11
  • 2018-06-21
  • 2015-01-27
  • 2015-03-10
相关资源
最近更新 更多