python - 如何在python sklearn中正确使用featureUnion数字和文本特征

标签 python scikit-learn

我第一次尝试在 sklearn 管道中使用 featureunion 来组合数字(2 列)和文本特征(1 列)以进行多类分类。

from sklearn.preprocessing import FunctionTransformer
from sklearn.pipeline import Pipeline
from sklearn.multiclass import OneVsRestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import FeatureUnion

get_text_data = FunctionTransformer(lambda x: x['text'], validate=False)
get_numeric_data = FunctionTransformer(lambda x: x[['num1','num2']], validate=False)

process_and_join_features = FeatureUnion(
         [
            ('numeric_features', Pipeline([
                ('selector', get_numeric_data),
                ('clf', OneVsRestClassifier(LogisticRegression()))
            ])),
             ('text_features', Pipeline([
                ('selector', get_text_data),
                ('vec', CountVectorizer()),
                ('clf', OneVsRestClassifier(LogisticRegression()))
            ]))
         ]
    )

在此代码中,'text' 是文本列,'num1'、'num2' 是 2 个数字列。

错误信息是

TypeError: All estimators should implement fit and transform. 'Pipeline(memory=None,
 steps=[('selector', FunctionTransformer(accept_sparse=False,
      func=<function <lambda> at 0x7fefa8efd840>, inv_kw_args=None,
      inverse_func=None, kw_args=None, pass_y='deprecated',
      validate=False)), ('clf', OneVsRestClassifier(estimator=LogisticRegression(C=1.0, class_weigh...=None, solver='liblinear', tol=0.0001,
      verbose=0, warm_start=False),
      n_jobs=1))])' (type <class 'sklearn.pipeline.Pipeline'>) doesn't

我错过了什么步骤?

最佳答案

FeatureUnion 应该用作管道中的一个步骤,而不是围绕管道。你得到的错误是因为你有一个分类器而不是最后一步 - 联合试图在所有转换器上调用 fittransform 并且分类器没有 transform 方法。

简单地重新设计一个带有分类器的外部管道作为最后一步:

process_and_join_features = Pipeline([
    ('features', FeatureUnion([
            ('numeric_features', Pipeline([
                ('selector', get_numeric_data)
            ])),
             ('text_features', Pipeline([
                ('selector', get_text_data),
                ('vec', CountVectorizer())
            ]))
         ])),
    ('clf', OneVsRestClassifier(LogisticRegression()))
])

另见 here在 scikit-learn 网站上有一个很好的例子来做这种事情。

关于python - 如何在python sklearn中正确使用featureUnion数字和文本特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47745288/

相关文章:

Python:递归删除空文件夹

Python:为什么特征向量与第一个 PCA 权重不同?

python - 如何用正则表达式匹配多行

python - 如何在 scikit learn 中保存 TFIDF 矢量器?

python-3.x - sklearn - PCA 的标签点

python - 如何在 Python 中创建共现矩阵?

pandas - 应用sklearn时保持pandas索引

python - scikit-learn 中 DictionaryLearning 和 MiniBatchDictionaryLearning 的区别

python - Scikit-learn 中仅针对 DataFrame 的一部分进行 One-Hot 编码

python - 我无法将 MySQLdb 导入我的 Python 程序