首页 > 解决方案 > 带有数组的 Python Sklearn 管道

问题描述

我正在尝试使用 Python 和 Sklearn 创建一个分类器。我目前已成功导入所有数据。我一直在尝试从这里开始学习教程,并在进行过程中对其进行了一些更改。后来进入该项目,我意识到他们的训练和测试数据与我的大不相同。如果我理解正确,他们有这样的事情:

X_train = ['Article or News article here', 'Anther News Article or Article here', ...]
y_train = ['Article Type', 'Article Type', ...]
#Same for the X_test and y_test

虽然我有这样的事情:

X_train = [['Dylan went in the house. Robert left the house', 'Where is Dylan?'], ['Mary ate the apple. Tom ate the cake', 'Who ate the cake?'], ...]
y_train = ['In the house.', 'Tom ate the cake']
#Same for the X_test and y_test

当我尝试使用管道训练分类器时:

text_clf = Pipeline([('vect', CountVectorizer(stop_words='english')),
     ('tfidf', TfidfTransformer(use_idf=True)),
     ('clf', SGDClassifier(loss='hinge', penalty='l2', alpha=1e-3, random_state=42, 
     verbose=1)),])

我得到错误:

AttributeError: 'list' object has no attribute 'lower'

在这一行:

text_clf.fit(X_train, y_train)

经过研究,我现在知道这是因为我正在为我的X_train数据输入一个数组而不是字符串。所以我的问题是,我如何构建一个管道来接受我的数据的数组和我的X_train数据的字符串y_train?这可能与管道有关吗?

标签: pythonscikit-learnpipeline

解决方案


您可以使用该属性将每个列表作为单个文档tokenizer告知,并将选项设置为喜欢这个CountVectorizerlowercaseFalse

text_clf = Pipeline([('vect', CountVectorizer(tokenizer=lambda single_doc: single_doc,stop_words='english',lowercase=False)),
 ('tfidf', TfidfTransformer(use_idf=True)),
 ('clf', SGDClassifier(loss='hinge', penalty='l2', alpha=1e-3, random_state=42, 
 verbose=1)),])

推荐阅读