【发布时间】:2016-12-31 11:00:38
【问题描述】:
我正在使用词袋对文本进行分类。它运行良好,但我想知道如何添加一个不是单词的功能。
这是我的示例代码。
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",
"new york is also called the big apple",
"nyc is nice",
"the capital of great britain is london. london is a huge metropolis which has a great many number of people living in it. london is also a very old town with a rich and vibrant cultural history.",
"london is in the uk. they speak english there. london is a sprawling big city where it's super easy to get lost and i've got lost many times.",
"london is in england, which is a part of great britain. some cool things to check out in london are the museum and buckingham palace.",
"london is in great britain. it rains a lot in britain and london's fogs are a constant theme in books based in london, such as sherlock holmes. the weather is really bad there.",])
y_train = [[0],[0],[0],[0],[1],[1],[1],[1]]
X_test = np.array(["it's a nice day in nyc",
'i loved the time i spent in london, the weather was great, though there was a nip in the air and i had to wear a jacket.'
])
target_names = ['Class 1', 'Class 2']
classifier = Pipeline([
('vectorizer', CountVectorizer(min_df=1,max_df=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))
现在很明显,关于伦敦的文字往往比关于纽约的文字长得多。如何将文本长度添加为特征? 我是否必须使用另一种分类方式,然后结合两个预测?有没有什么办法可以和词袋一起做呢? 一些示例代码会很棒——我对机器学习和 scikit 学习非常陌生。
【问题讨论】:
-
您的代码没有运行,即因为您在只有一个目标时使用了 OneVsRestClassifier。
-
使用 sklearn 的 FeatureUnion,以下链接几乎完全符合您的要求:zacstewart.com/2014/08/05/…
标签: python machine-learning scikit-learn classification text-classification