【发布时间】:2018-02-28 23:19:44
【问题描述】:
问题
我正在研究一个学习排名问题,其中标准是对点进行评估的预测,但对模型性能进行分组评估。
更具体地说,估计器输出一个连续变量(很像回归器)
> y = est.predict(X); y
array([71.42857143, 0. , 71.42857143, ..., 0. ,
28.57142857, 0. ])
但评分功能需要通过查询聚合,即对预测进行分组,类似于发送给GridSearchCV的groups参数以尊重折叠分区。
> 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