我已经挣扎了这么多,但仍然无法弄清楚如何在scikit-learn管道中使用FeatureUnion
的文字功能和额外功能。
我有一个句子列表和他们的标签来训练一个模型和一个句子列表作为测试数据。然后我尝试在包词中添加一个额外的功能(如每个句子的长度)。为此,我写了一个自定义LengthTransformer
,它返回一个长度列表,并且具有与我的列车列表相同数量的元素
然后我使用TfidfVectorizer
将其与FeatureUnion
结合使用,但它无法正常工作。
到目前为止,我想出的是:
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.pipeline import Pipeline, FeatureUnion
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.svm import LinearSVC
from sklearn.multiclass import OneVsRestClassifier
from sklearn import preprocessing
class LengthTransformer(BaseEstimator, TransformerMixin):
def fit(self, X, y=None):
return self
def transform(self, X):
return [len(x) for x in X]
X_train = ["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_text = [["new york"], ["new york"], ["new york"], ["new york"], ["new york"],
["new york"], ["london"], ["london"], ["london"], ["london"],
["london"], ["london"], ["london", "new york"], ["new york", "london"]]
X_test = ['nice day in nyc',
'welcome to london',
'london is rainy',
'it is raining in britian',
'it is raining in britian and the big apple',
'it is raining in britian and nyc',
'hello welcome to new york. enjoy it here and london too']
lb = preprocessing.MultiLabelBinarizer()
Y = lb.fit_transform(y_train_text)
classifier = Pipeline([
('feats', FeatureUnion([
('tfidf', TfidfVectorizer()),
('len', LengthTransformer())
])),
('clf', OneVsRestClassifier(LinearSVC()))
])
classifier.fit(X_train, Y)
predicted = classifier.predict(X_test)
all_labels = lb.inverse_transform(predicted)
for item, labels in zip(X_test, all_labels):
print('{} => {}'.format(item, ', '.join(labels)))
答案 0 :(得分:4)
LengthTransformer.transform返回形状错误 - 它返回每个输入文档的标量,而变换器应返回每个文档的特征向量。您可以通过在LengthTransformer.transform中将[len(x) for x in X]
更改为[[len(x)] for x in X]
来使其发挥作用。