GAFeatureSelectionCV是否支持StratifiedGroupKFold交叉验证及用法咨询
解决GAFeatureSelectionCV结合StratifiedGroupKFold的分组特征选择问题
针对你的需求,这里有两种可行的解决方法,都能让StratifiedGroupKFold正确识别分组信息,同时适配GAFeatureSelectionCV的使用:
方法一:在fit时直接传入groups参数
GAFeatureSelectionCV的fit方法继承自sklearn的搜索类,会自动将groups参数传递给交叉验证策略的split方法。你只需要正常初始化StratifiedGroupKFold,然后在调用fit时传入患者ID即可:
from sklearn_genetic import GAFeatureSelectionCV from sklearn.model_selection import StratifiedGroupKFold from sklearn.neural_network import MLPClassifier # 初始化基础分类器 clf = MLPClassifier(hidden_layer_sizes=(50, 30)) # 初始化分层组交叉验证(建议设置random_state保证可复现) cv = StratifiedGroupKFold(n_splits=3, shuffle=True, random_state=42) # 初始化遗传算法特征选择器 evolved_selector = GAFeatureSelectionCV( estimator=clf, cv=cv, scoring='accuracy', population_size=10, generations=20, n_jobs=-1, verbose=True ) # 关键:调用fit时传入groups参数(患者ID数组) evolved_selector.fit(X, y, groups=patient_ids)
这种方法最简洁,也是适配带分组的交叉验证策略的常规方式。
方法二:预先生成分组拆分索引作为cv参数
如果你的sklearn-genetic-opt版本较旧,或者遇到groups参数传递的问题,可以提前用StratifiedGroupKFold生成所有训练/验证集的索引对,然后直接将这个索引列表作为cv参数传入:
from sklearn_genetic import GAFeatureSelectionCV from sklearn.model_selection import StratifiedGroupKFold from sklearn.neural_network import MLPClassifier # 预先生成分组拆分的索引对 cv_strategy = StratifiedGroupKFold(n_splits=3, shuffle=True, random_state=42) splits = list(cv_strategy.split(X, y, groups=patient_ids)) # 初始化特征选择器,传入预生成的拆分索引 evolved_selector = GAFeatureSelectionCV( estimator=clf, cv=splits, scoring='accuracy', population_size=10, generations=20, n_jobs=-1, verbose=True ) # 此时fit无需再传入groups evolved_selector.fit(X, y)
sklearn允许cv参数接受包含(训练集索引, 验证集索引)元组的列表,GAFeatureSelectionCV会直接使用这些预定义的拆分逻辑。
注意事项
- 确保
patient_ids的长度与X、y的样本数量完全一致 - 使用
shuffle=True时务必设置random_state,避免每次运行的拆分结果不一致 - 建议使用sklearn-genetic-opt 0.9.0及以上版本,以保证
groups参数的兼容性
内容的提问来源于stack exchange,提问作者Emily Wong
相关产品推荐
相关产品推荐

