scikit-learn中LassoCV结合分组交叉验证遇报错求助
解决LassoCV结合LeaveOneGroupOut交叉验证的传参错误
这个问题我之前也碰到过,其实不是scikit-learn的bug,是你调用fit()方法时的传参方式不对!让我一步步给你解释:
第一个错误的原因
当你使用LeaveOneGroupOut()作为交叉验证策略时,这个验证器必须依赖分组信息才能工作——它需要知道每个样本属于哪个组,才能每次留出一个组作为测试集。所以当你只调用lassoCV.fit(df,y)时,没有传入分组信息,scikit-learn自然会抛出ValueError: The 'groups' parameter should not be None的错误,这个是正常的提示,没问题。
第二个错误的根源
你尝试的lassoCV.fit(df,y,groups)是把groups作为位置参数传递,但LassoCV的fit()方法签名是这样的:
fit(X, y, sample_weight=None, **kwargs)
前三个位置参数分别是X、y、sample_weight,你把groups放在第三个位置,会被当成sample_weight参数,而groups实际上需要作为关键字参数传入,这样scikit-learn才会把它传递给你的LeaveOneGroupOut交叉验证器。
正确的实现代码
只需要把groups以关键字参数的形式传入fit()方法即可:
import numpy as np from sklearn import linear_model from sklearn.model_selection import LeaveOneGroupOut # 生成模拟数据 df = np.random.rand(100,50) y = np.random.rand(100) logo = LeaveOneGroupOut() groups = np.random.randint(0,10,100) # 初始化LassoCV回归器 lassoCV = linear_model.LassoCV( eps=0.0001, n_alphas=400, max_iter=200000, cv=logo, normalize=False, random_state=9 ) # 正确调用fit方法,用关键字参数传入groups lassoCV.fit(df, y, groups=groups)
补充说明
其实不只是LassoCV,scikit-learn中所有需要分组交叉验证的模型,在调用fit()时都需要用关键字参数传入groups,这样框架才能正确地把分组信息传递给对应的交叉验证策略。
内容的提问来源于stack exchange,提问作者Archie
相关产品推荐
相关产品推荐

