属性错误:未找到下层;在 scikit-learn 中使用带有 CountVectorizer 的 Pipeline

2024-05-08

我有一个这样的语料库:

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.

我搜索并发现了有关此错误的问题here https://stackoverflow.com/questions/28103992/tfidf-vectorizer-giving-error,这让我相信我的文本没有被标记化存在问题(这听起来像是击中要害,因为我使用列表列表作为输入数据,其中每个列表包含一个完整的字符串) 。

我编写了一个快速而肮脏的分词器来测试这个理论:

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独自的?

任何建议将不胜感激。


这是因为您的数据集格式错误,您应该通过“产生 str、unicode 或文件对象的迭代” http://scikit-learn.org/dev/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html#sklearn.feature_extraction.text.CountVectorizer.fit进入 CountVectorizer 的拟合函数(或进入管道,没关系)。不可迭代带有文本的其他可迭代对象(如您的代码中所示)。在您的情况下,列表是可迭代的,您应该传递其成员是字符串的平面列表(而不是另一个列表)。

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

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

看看这个例子,非常有用:用于文本特征提取和评估的示例管道 http://scikit-learn.org/dev/auto_examples/model_selection/grid_search_text_feature_extraction.html

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

属性错误:未找到下层;在 scikit-learn 中使用带有 CountVectorizer 的 Pipeline 的相关文章

随机推荐