AttributeError:未找到lower; 在scikit-learn中使用带有CountVectorizer的Pipeline

Mat*_*ien 7 python pipeline 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']
    ]
Run Code Online (Sandbox Code Playgroud)

和一些标签:

y_train = [1, 5, ... , 3]
Run Code Online (Sandbox Code Playgroud)

我想使用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)
Run Code Online (Sandbox Code Playgroud)

当我运行这个时,我收到一个错误说AttributeError: lower not found.

在这里搜索并发现了一个关于这个错误的问题,这让我相信我的文本没有被标记化存在问题(这听起来就像它击中了头部,因为我使用列表列表作为输入数据,其中每个列表包含一个单个不间断的字符串).

我制作了一个快速而肮脏的标记器来测试这个理论:

def my_tokenizer(X):
    newlist = []
    for alist in X:
        newlist.append(alist[0].split(' '))
    return newlist
Run Code Online (Sandbox Code Playgroud)

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

pipeline = Pipeline([
    ('vect', CountVectorizer(tokenizer=my_tokenizer)),
Run Code Online (Sandbox Code Playgroud)

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

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

为什么我一直收到这个错误?实际上,知道这个错误意味着什么会很好!(被lower调用将文本转换为小写或其他东西?我无法通过读取堆栈跟踪来判断).我是否滥用了Pipeline ......或者问题确实是CountVectorizer单独论证的问题?

任何建议将不胜感激.

Ibr*_*iev 6

这是因为您的数据集格式错误,您应该将“可迭代生成str,unicode或文件对象的 Iterable 传递给CountVectorizer的fit函数(或传递给管道,没关系)。不可与其他带有文本的可迭代对象一起迭代(如您的代码中一样)。在您的情况下,列表是可迭代的,并且您应该传递成员为字符串的平面列表(而不是其他列表)。

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

X_train = ['this is an dummy example',
      'in reality this line is very long',
      ...
      'here is a last text in the training set'
    ]
Run Code Online (Sandbox Code Playgroud)

看这个例子,非常有用:用于文本特征提取和评估的示例管道

  • 巧合的是,我的代码基于此示例。由于该示例从`sklearn.datasets.fetch_20newsgroups` 中提取数据,因此不清楚该数据采用什么格式(列表?矩阵?)。该文档对这个细节也不是很有帮助。 (2认同)