sklearn pipelin中的“ValueError:所有输入数组的维数必须相同”错误

2024-10-01 15:30:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用sklearn管道构建一个机器学习管道。在预处理步骤中,我尝试对两个不同的sting变量进行两种不同的处理:1)一种是BusinessType上的热编码;2)AreaCode上的平均编码,如下所示:

preprocesses_pipeline = make_pipeline (
    FeatureUnion (transformer_list = [
        ("text_features1",  make_pipeline(
            FunctionTransformer(getBusinessTypeCol, validate=False), CustomOHE()
        )),
        ("text_features2",  make_pipeline(
            FunctionTransformer(getAreaCodeCol, validate=False)
        ))
    ])
)

preprocesses_pipeline.fit_transform(trainDF[X_cols])

TransformerMini类定义为:

^{pr2}$

和函数transformer函数返回指定字段

def getBusinessTypeCol(df):
    return df['BusinessType']

def getAreaCodeCol(df):
    return df[['AreaCode1','isFail']]

现在,当我取消上面的管道时,它会产生以下错误

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-146-7f3a31a39c81> in <module>()
     15 )
     16 
---> 17 preprocesses_pipeline.fit_transform(trainDF[X_cols])

~\Anaconda3\lib\site-packages\sklearn\pipeline.py in fit_transform(self, X, y, **fit_params)
    281         Xt, fit_params = self._fit(X, y, **fit_params)
    282         if hasattr(last_step, 'fit_transform'):
--> 283             return last_step.fit_transform(Xt, y, **fit_params)
    284         elif last_step is None:
    285             return Xt

~\Anaconda3\lib\site-packages\sklearn\pipeline.py in fit_transform(self, X, y, **fit_params)
    747             Xs = sparse.hstack(Xs).tocsr()
    748         else:
--> 749             Xs = np.hstack(Xs)
    750         return Xs
    751 

~\Anaconda3\lib\site-packages\numpy\core\shape_base.py in hstack(tup)
    286         return _nx.concatenate(arrs, 0)
    287     else:
--> 288         return _nx.concatenate(arrs, 1)
    289 
    290 

ValueError: all the input arrays must have same number of dimensions

在管道中使用“MeanEncoding”似乎是在发生错误,因为删除它可以使管道正常工作。不知道到底出了什么问题。需要帮助。在


Tags: indfmakereturn管道pipelinelibtransform
1条回答
网友
1楼 · 发布于 2024-10-01 15:30:25

好吧,我来解谜。基本上,MeanEncoding()在转换之后,返回格式为(n,)的数组,而返回的调用期望格式为(n,1),因此它可以将此(n,1)与第一个管道CustomOHE()返回的其他已处理的(n,k)数组相结合。由于numpy不能组合(n,)(n,k),因此需要将其重塑为(n,1)。{cd11>如下所示:

class MeanEncoding(BaseEstimator, TransformerMixin):
    def fit(self, X, y=None):
        return self

    def transform(self, X):
        tmp = X['AreaCode1'].map(X.groupby('AreaCode1')['isFail'].mean())
        return tmp.values.reshape(len(tmp), 1)

相关问题 更多 >

    热门问题