“ ValueError:所有输入数组必须具有相同数量的维数” sklearn管道中出现错误

时间:2018-10-30 13:55:43

标签: python scikit-learn pipeline

我正在使用sklearn管道构建机器学习管道。在预处理步骤中,我尝试对两个不同的字符串变量进行两种不同的处理: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])

将TransformerMixin类定义为:

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

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

    def transform(self, X):
        tmp = pd.get_dummies(X)
        return tmp.values

和FunctionTransformer函数返回所需的字段

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”的行上发生错误,因为删除它会使管​​道正常工作。不知道到底是什么问题。需要帮助。

1 个答案:

答案 0 :(得分:3)

好的,我解决了这个难题。基本上,MeanEncoding()在转换后会返回格式为(n,)的数组,而返回的调用期望的格式为(n,1),因此它可以将此(n,1)与其他已处理的{第一个管道(n,k)返回的{1}}。由于CustomOHE()无法合并numpy(n,),因此需要将其重塑为(n,k)。因此,现在我的(n,1)类如下所示:

MeanEncoding