使用StackingClassifier时遇ValueError: too many values to unpack (expected 2)求助
解决StackingClassifier的ValueError问题
错误根源
你的estimators格式不符合Scikit-learn的要求:StackingClassifier要求estimators是由(name, estimator)二元组组成的列表,但你现在把所有模型都塞进了一个大元组里,整个列表仅含一个元素,这个元素包含14个值(7组模型名+模型实例),导致框架尝试解包时无法按照预期的2个值处理,从而抛出too many values to unpack (expected 2)错误。
修正后的代码
将每个模型单独封装成(name, estimator)的二元组,组成规范的列表:
estimators = [ ('GaussianNB', GaussianNB(var_smoothing = 0.533669923120631)), ('LogisticRegression', LogisticRegression(C=0.001, max_iter=1500, penalty='none', random_state=42, solver='newton-cg')), ('DecisionTreeClassifier', DecisionTreeClassifier(ccp_alpha=0.001, criterion='entropy', max_depth=14, max_features='auto', random_state=42)), ('RandomForestClassifier', RandomForestClassifier(ccp_alpha=0.001, criterion='entropy', max_depth=14, random_state=42)), ('SVC', SVC(kernel = 'linear', random_state=42)), ('KNeighborsClassifier', KNeighborsClassifier(algorithm='ball_tree', n_neighbors=3)), ('GradientBoostingClassifier', GradientBoostingClassifier(learning_rate=0.2, max_depth=10, max_features='sqrt', n_estimators=10, subsample=0.8)) ] meta_model = LogisticRegressionCV() stacking_model = StackingClassifier(estimators = estimators, final_estimator = meta_model, passthrough = True, cv = 5, verbose = 2).fit(X_train, y_train)
核心修改点
- 每个模型单独成为
('模型名', 模型实例)的二元组,用括号包裹 - 所有二元组并列放在
estimators列表中,彼此用逗号分隔
调整后Scikit-learn就能正确识别每个基础模型,顺利完成堆叠集成的训练流程。
内容的提问来源于stack exchange,提问作者Alexander
相关产品推荐
相关产品推荐

