You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scikit-Learn中VotingRegressor整合PLS与SVR报错求助

问题:VotingRegressor结合PLSRegression与SVR时报错

问题说明

在Scikit-Learn中使用VotingRegressor结合PLSRegression和SVR模型时,加入PLS模型就会触发维度不匹配的错误,单独使用SVR或其他模型则可正常运行。

代码示例

reg1 = cross_decomposition.PLSRegression()
reg2 = svm.SVR()
regr = VotingRegressor(estimators=[('gb', reg1), ('rf', reg2)])
regr.fit(training_features, training_outputs)

错误信息

File "C:\Users\lesag\AppData\Local\Programs\Python\Python311\Lib\site-packages\sklearn\ensemble\_voting.py", line 68, in _predict
    return np.asarray([est.predict(X) for est in self.estimators_]).T
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 2 dimensions. The detected shape was (2, 1) + inhomogeneous part.

解决方案

问题根源

PLSRegression默认参数n_components=2,其predict方法输出的是二维数组(形状为(n_samples, 2));而SVR的predict方法输出的是一维数组(形状为(n_samples,))。两者输出维度不匹配,导致VotingRegressor无法正常拼接结果,触发报错。

两种解决方式

  1. 指定PLS的成分数为1
    初始化PLSRegression时设置n_components=1,让其predict输出和SVR一致的一维数组:

    reg1 = cross_decomposition.PLSRegression(n_components=1)
    reg2 = svm.SVR()
    regr = VotingRegressor(estimators=[('pls', reg1), ('svr', reg2)])
    regr.fit(training_features, training_outputs)
    
  2. 自定义包装器适配PLS输出
    如果需要保留多成分的PLS模型,可以写一个包装类,将PLS的多维预测结果转换为一维(比如取第一列,或对多列做均值):

    from sklearn.base import BaseEstimator, RegressorMixin
    import cross_decomposition
    import svm
    
    class PLSWrapper(BaseEstimator, RegressorMixin):
        def __init__(self, n_components=2):
            self.pls = cross_decomposition.PLSRegression(n_components=n_components)
        
        def fit(self, X, y):
            self.pls.fit(X, y)
            return self
        
        def predict(self, X):
            # 这里取预测结果的第一列,可根据需求替换为其他聚合逻辑
            return self.pls.predict(X)[:, 0]
    
    reg1 = PLSWrapper(n_components=2)
    reg2 = svm.SVR()
    regr = VotingRegressor(estimators=[('pls', reg1), ('svr', reg2)])
    regr.fit(training_features, training_outputs)
    

内容的提问来源于stack exchange,提问作者Ethan LeSage

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 19:05:15