15

我有一个一维数组,每个元素中都有大字符串。我正在尝试使用 aCountVectorizer将文本数据转换为数值向量。但是,我收到一条错误消息:

AttributeError: 'numpy.ndarray' object has no attribute 'lower'

mealarray每个元素中都包含大字符串。有 5000 个这样的样本。我正在尝试将其矢量化,如下所示:

vectorizer = CountVectorizer(
    stop_words='english',
    ngram_range=(1, 1),  #ngram_range=(1, 1) is the default
    dtype='double',
)
data = vectorizer.fit_transform(mealarray)

完整的堆栈跟踪:

File "/Library/Python/2.7/site-packages/sklearn/feature_extraction/text.py", line 817, in fit_transform
    self.fixed_vocabulary_)
  File "/Library/Python/2.7/site-packages/sklearn/feature_extraction/text.py", line 748, in _count_vocab
    for feature in analyze(doc):
  File "/Library/Python/2.7/site-packages/sklearn/feature_extraction/text.py", line 234, in <lambda>
    tokenize(preprocess(self.decode(doc))), stop_words)
  File "/Library/Python/2.7/site-packages/sklearn/feature_extraction/text.py", line 200, in <lambda>
    return lambda x: strip_accents(x.lower())
AttributeError: 'numpy.ndarray' object has no attribute 'lower'
4

4 回答 4

19

检查形状mealarray。如果 to 的参数fit_transform是字符串数组,则它必须是一维数组。(即,mealarray.shape必须为(n,).)例如,如果mealarray形状为(n, 1).

你可以尝试类似的东西

data = vectorizer.fit_transform(mealarray.ravel())
于 2014-10-14T18:09:18.497 回答
8

得到了我的问题的答案。基本上,CountVectorizer 将列表(带有字符串内容)作为参数而不是数组。这解决了我的问题。

于 2014-10-14T18:57:25.963 回答
2

更好的解决方案是显式调用 pandas 系列并将其传递给 CountVectorizer():

>>> tex = df4['Text']
>>> type(tex)
<class 'pandas.core.series.Series'>
X_train_counts = count_vect.fit_transform(tex)

下一个不起作用,因为它是一个框架而不是系列

>>> tex2 = (df4.ix[0:,[11]])
>>> type(tex2)
<class 'pandas.core.frame.DataFrame'>
于 2018-07-18T16:40:49.853 回答
1

我得到了同样的错误:

AttributeError: 'numpy.ndarray' object has no attribute 'lower'

为了解决这个问题,我做了以下事情:

  1. 验证数组的维度: name_of_array1.shape
  2. 我的输出是:(n,1) 然后flatten()用来将二维数组转换为一维: flat_array = name_of_array1.flatten()
  3. 现在,我可以使用CountVectorizer(),因为这适用于一个参数列表作为字符串。
于 2021-10-04T11:58:19.447 回答