【问题标题】:ValueError: Input array dimensions not right for CountVectorizer()ValueError:CountVectorizer() 的输入数组尺寸不正确
【发布时间】:2019-10-11 09:17:22
【问题描述】:

在 sklearn 管道中使用 make_column_transformer() 时,我在尝试使用 CountVectorizer 时遇到错误。

我的 DataFrame 有两列,'desc-title''SPchangeHigh'。 这是两行的 sn-p:

features = pd.DataFrame([["T. Rowe Price sells most of its Tesla shares", .002152],
                         ["Gannett to retain all seats in MNG proxy fight", 0.002152]],
                        columns=["desc-title", "SPchangeHigh"])

我可以毫无问题地运行以下管道:

preprocess = make_column_transformer(
    (StandardScaler(),['SPchangeHigh']),
    ( OneHotEncoder(),['desc-title'])
)
preprocess.fit_transform(features.head(2)) 

但是,当我将 OneHotEncoder() 替换为 CountVectorizer(tokenizer=tokenize) 时,它会失败:

preprocess = make_column_transformer(
    (StandardScaler(),['SPchangeHigh']),
    ( CountVectorizer(tokenizer=tokenize),['desc-title'])
)
preprocess.fit_transform(features.head(2))

我得到的错误是:


ValueError                                Traceback (most recent call last)
<ipython-input-71-d77f136b9586> in <module>()
      3     ( CountVectorizer(tokenizer=tokenize),['desc-title'])
      4 )
----> 5 preprocess.fit_transform(features.head(2))

C:\anaconda3\lib\site-packages\sklearn\compose\_column_transformer.py in fit_transform(self, X, y)
    488         self._validate_output(Xs)
    489 
--> 490         return self._hstack(list(Xs))
    491 
    492     def transform(self, X):

C:\anaconda3\lib\site-packages\sklearn\compose\_column_transformer.py in _hstack(self, Xs)
    545         else:
    546             Xs = [f.toarray() if sparse.issparse(f) else f for f in Xs]
--> 547             return np.hstack(Xs)
    548 
    549 

C:\anaconda3\lib\site-packages\numpy\core\shape_base.py in hstack(tup)
    338         return _nx.concatenate(arrs, 0)
    339     else:
--> 340         return _nx.concatenate(arrs, 1)
    341 
    342 

ValueError: all the input array dimensions except for the concatenation axis must match exactly

如果有人可以帮助我,我将不胜感激。

【问题讨论】:

  • 你用什么做分词器?

标签: python scikit-learn pipeline


【解决方案1】:

删除 'desc-title' 周围的括号。您需要一个一维数组,而不是列向量。

preprocess = make_column_transformer(
    (StandardScaler(),['SPchangeHigh']),
    ( CountVectorizer(),'desc-title')
)
preprocess.fit_transform(features.head(2))

Sklearn documentation describes this nuanced specification:

将列选择器指定为 'column' 的区别(如 一个简单的字符串)和 ['column'] (作为一个元素的列表)是 传递给变压器的阵列的形状。在第一 情况下,将传递一个一维数组,而在第二种情况下 它将是一个具有一列的二维数组,即一列 向量

...

请注意,有些转换器需要一维输入( 面向标签的),而其他一些,如 OneHotEncoder 或 Imputer, 期望二维输入,形状为 [n_samples, n_features]。

【讨论】:

  • 您先生,刚刚节省了我数小时的调试时间!谢谢
猜你喜欢
  • 1970-01-01
  • 2022-01-19
  • 2011-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-19
  • 2021-09-14
  • 1970-01-01
相关资源
最近更新 更多