AttributeError: lower not found; using a Pipeline with a CountVectorizer in scikit-learn

AttributeError: lower not found; using a Pipeline with a CountVectorizer in scikit-learn

我有这样一个语料库:

X_train = [ ['this is an dummy example'] 
      ['in reality this line is very long']
      ...
      ['here is a last text in the training set']
    ]

和一些标签:

y_train = [1, 5, ... , 3]

我想按如下方式使用 Pipeline 和 GridSearch:

pipeline = Pipeline([
    ('vect', CountVectorizer()),
    ('tfidf', TfidfTransformer()),
    ('reg', SGDRegressor())
])


parameters = {
    'vect__max_df': (0.5, 0.75, 1.0),
    'tfidf__use_idf': (True, False),
    'reg__alpha': (0.00001, 0.000001),
}

grid_search = GridSearchCV(pipeline, parameters, n_jobs=1, verbose=1)

grid_search.fit(X_train, y_train)

当我 运行 执行此操作时,我收到一条错误消息 AttributeError: lower not found

我搜索并发现了一个关于这个错误的问题 ,这让我相信我的文本没有被标记化是有问题的(这听起来像是一针见血,因为我使用列表列表作为输入数据,其中每个列表包含一个完整的字符串)。

我制作了一个快速但肮脏的分词器来测试这个理论:

def my_tokenizer(X):
    newlist = []
    for alist in X:
        newlist.append(alist[0].split(' '))
    return newlist

它做了它应该做的,但是当我在 CountVectorizer 的参数中使用它时:

pipeline = Pipeline([
    ('vect', CountVectorizer(tokenizer=my_tokenizer)),

...我仍然得到同样的错误,好像什么都没发生一样。

我确实注意到我可以通过在我的管道中注释掉 CountVectorizer 来避免错误。这很奇怪......我认为你不能使用 TfidfTransformer() 而不首先有一个数据结构来转换......在这种情况下是计数矩阵。

为什么我总是收到这个错误?实际上,如果知道这个错误是什么意思就好了! (调用 lower 是为了将文本转换为小写字母还是什么?我无法通过读取堆栈跟踪来判断)。我是在滥用管道......还是问题真的只是 CountVectorizer 的参数问题?

如有任何建议,我们将不胜感激。

因为你的数据集格式不对,你应该把"An iterable which yields either str, unicode or file objects"传给CountVectorizer的fit函数(或者传给pipeline,无所谓)。不可迭代其他带有文本的迭代器(如在您的代码中)。在你的情况下 List 是可迭代的,你应该传递其成员是字符串(而不是另一个列表)的平面列表。

即您的数据集应如下所示:

X_train = ['this is an dummy example',
      'in reality this line is very long',
      ...
      'here is a last text in the training set'
    ]

看看这个例子,很有用:Sample pipeline for text feature extraction and evaluation

你可以像这样传递数据:

from sklearn import metrics
text_clf.fit(list(X_train), list(y_train))
predicted = text_clf.predict(list(X_test))
print(metrics.classification_report(list(y_test), predicted))