你想要的是所谓的多标签分类。 Scikits-learn 可以做到这一点。看这里:http://scikit-learn.org/dev/modules/multiclass.html.
我不确定你的例子出了什么问题,我的 sklearn 版本显然没有 WordNGramAnalyzer。也许这是使用更多训练示例或尝试不同分类器的问题?但请注意,多标签分类器期望目标是元组列表/标签列表。
以下对我有用:
import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.svm import LinearSVC
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.multiclass import OneVsRestClassifier
X_train = np.array(["new york is a hell of a town",
"new york was originally dutch",
"the big apple is great",
"new york is also called the big apple",
"nyc is nice",
"people abbreviate new york city as nyc",
"the capital of great britain is london",
"london is in the uk",
"london is in england",
"london is in great britain",
"it rains a lot in london",
"london hosts the british museum",
"new york is great and so is london",
"i like london better than new york"])
y_train = [[0],[0],[0],[0],[0],[0],[1],[1],[1],[1],[1],[1],[0,1],[0,1]]
X_test = np.array(['nice day in nyc',
'welcome to london',
'hello welcome to new york. enjoy it here and london too'])
target_names = ['New York', 'London']
classifier = Pipeline([
('vectorizer', CountVectorizer(min_n=1,max_n=2)),
('tfidf', TfidfTransformer()),
('clf', OneVsRestClassifier(LinearSVC()))])
classifier.fit(X_train, y_train)
predicted = classifier.predict(X_test)
for item, labels in zip(X_test, predicted):
print '%s => %s' % (item, ', '.join(target_names[x] for x in labels))
对我来说,这会产生输出:
nice day in nyc => New York
welcome to london => London
hello welcome to new york. enjoy it here and london too => New York, London