gpt4 book ai didi

python - 使用折叠相关参数对 GridSearchCV 进行自定义评分

转载 作者:太空宇宙 更新时间:2023-11-03 15:47:39 27 4
gpt4 key购买 nike

问题

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

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

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

但是打分函数需要查询聚合,即分组预测,类似groups参数传给GridSearchCV尊重fold分区。

> 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 中, 一条评论询问/建议:

Why cant you just store {the grouping column} locally and utilize it if necessary by indexing with the train test indices provided by the splitter?

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 固定在最后生成的拆分处。

最佳答案

据我了解,评分值是成对的(值、组),但估算器不应与组一起使用。让我们将它们切在 wrapper 中,但将它们留给记分员。

简单的估算器包装器(可能需要一些改进才能完全符合要求)

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'])

关于python - 使用折叠相关参数对 GridSearchCV 进行自定义评分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49017257/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com