如何使用sklearn Pipeline和FeatureUnion选择多个(数字和文本)列进行文本分类?

2024-05-08

我开发了一个用于多标签分类的文本模型。这OneVsRest分类器 http://scikit-learn.org/stable/modules/generated/sklearn.multiclass.OneVsRestClassifier.htmlLinearSVC模型使用sklearnsPipeline and FeatureUnion用于模型准备。

主要输入功能由一个名为的文本列组成response还有 5 个主题概率(从之前的 LDA 主题模型生成),称为t1_prob - t5_prob预测 5 个可能的标签。管道中还有其他特征创建步骤用于生成TfidfVectorizer.

我最终用以下方式调用每一列项目选择器 http://scikit-learn.org/stable/auto_examples/hetero_feature_union.html并对这些主题概率列分别执行 ArrayCaster(函数定义请参阅下面的代码)5 次。有没有更好的使用方法特征联盟 http://scikit-learn.org/stable/modules/generated/sklearn.pipeline.FeatureUnion.html#sklearn.pipeline.FeatureUnion选择管道中的多个列? (所以我不必做5次)

我想知道是否有必要复制topic1_feature -topic5_feature代码或者是否可以以更简洁的方式选择多列?

我输入的数据是 Pandas 数据帧:

id response label_1 label_2 label3  label_4 label_5     t1_prob t2_prob t3_prob t4_prob t5_prob
1   Text from response...   0.0 0.0 0.0 0.0 0.0 0.0     0.0625  0.0625  0.1875  0.0625  0.1250
2   Text to model with...   0.0 0.0 0.0 0.0 0.0 0.0     0.1333  0.1333  0.0667  0.0667  0.0667  
3   Text to work with ...   0.0 0.0 0.0 0.0 0.0 0.0     0.1111  0.0938  0.0393  0.0198  0.2759  
4   Free text comments ...  0.0 0.0 1.0 1.0 0.0 0.0     0.2162  0.1104  0.0341  0.0847  0.0559  

x_train 是response以及 5 个主题概率列(t1_prob、t2_prob、t3_prob、t4_prob、t5_prob)。

y_train 是 5label我称之为的专栏.values返回 DataFrame 的 numpy 表示。 (标签_1、标签_2、标签3、标签_4、标签_5)

示例数据框:

import pandas as pd
column_headers = ["id", "response", 
                  "label_1", "label_2", "label3", "label_4", "label_5",
                  "t1_prob", "t2_prob", "t3_prob", "t4_prob", "t5_prob"]

input_data = [
    [1, "Text from response",0.0,0.0,1.0,0.0,0.0,0.0625,0.0625,0.1875,0.0625,0.1250],
    [2, "Text to model with",0.0,0.0,0.0,0.0,0.0,0.1333,0.1333,0.0667,0.0667,0.0667],
    [3, "Text to work with",0.0,0.0,0.0,0.0,0.0,0.1111,0.0938,0.0393,0.0198,0.2759],
    [4, "Free text comments",0.0,0.0,1.0,1.0,1.0,0.2162,0.1104,0.0341,0.0847,0.0559]
    ]

df = pd.DataFrame(input_data, columns = column_headers)
df = df.set_index('id')
df

我认为我的实现有点绕,因为 FeatureUnion 在组合二维数组时只会处理它们,所以像 DataFrame 这样的任何其他类型对我来说都是有问题的。然而,这个例子是有效的——我只是在寻找改进它并使其更加干燥的方法。

from sklearn.pipeline import Pipeline, FeatureUnion
from sklearn.base import BaseEstimator, TransformerMixin

class ItemSelector(BaseEstimator, TransformerMixin):
    def __init__(self, column):
        self.column = column

    def fit(self, X, y=None):
        return self

    def transform(self, X, y=None):
        return X[self.column]

class ArrayCaster(BaseEstimator, TransformerMixin):
    def fit(self, x, y=None):
        return self

    def transform(self, data):
        return np.transpose(np.matrix(data))


def basic_text_model(trainX, testX, trainY, testY, classLabels, plotPath):
    '''OneVsRestClassifier for multi-label prediction''' 
pipeline = Pipeline([
    ('features', FeatureUnion([
            ('topic1_feature', Pipeline([
                ('selector', ItemSelector(column='t1_prob')),
                ('caster', ArrayCaster())
            ])),
            ('topic2_feature', Pipeline([
                ('selector', ItemSelector(column='t2_prob')),
                ('caster', ArrayCaster())
            ])),
            ('topic3_feature', Pipeline([
                ('selector', ItemSelector(column='t3_prob')),
                ('caster', ArrayCaster())
            ])),
            ('topic4_feature', Pipeline([
                ('selector', ItemSelector(column='t4_prob')),
                ('caster', ArrayCaster())
            ])),
            ('topic5_feature', Pipeline([
                ('selector', ItemSelector(column='t5_prob')),
                ('caster', ArrayCaster())
            ])),
           ('word_features', Pipeline([
                    ('vect', CountVectorizer(analyzer="word", stop_words='english')), 
                    ('tfidf', TfidfTransformer(use_idf = True)),
            ])),
     ])),
    ('clf', OneVsRestClassifier(svm.LinearSVC(random_state=random_state))) 
])

# Fit the model
pipeline.fit(trainX, trainY)
predicted = pipeline.predict(testX)

我将 ArrayCaster 合并到这个过程中就是源于此answer https://stackoverflow.com/questions/25795511/unable-to-use-featureunion-in-scikit-learn-due-to-different-dimensions.


我使用以下方法找到了这个问题的答案函数转换器 http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.FunctionTransformer.html受到@Marcus V 解决方案的启发question https://stackoverflow.com/questions/47745288/how-to-featureunion-numerical-and-text-features-in-python-sklearn-properly。修改后的管道更加简洁。

from sklearn.preprocessing import FunctionTransformer

get_numeric_data = FunctionTransformer(lambda x: x[['t1_prob', 't2_prob', 't3_prob', 't4_prob', 't5_prob']], validate=False)

pipeline = Pipeline(
    [
        (
            "features",
            FeatureUnion(
                [
                    ("numeric_features", Pipeline([("selector", get_numeric_data)])),
                    (
                        "word_features",
                        Pipeline(
                            [
                                ("vect", CountVectorizer(analyzer="word", stop_words="english")),
                                ("tfidf", TfidfTransformer(use_idf=True)),
                            ]
                        ),
                    ),
                ]
            ),
        ),
        ("clf", OneVsRestClassifier(svm.LinearSVC(random_state=10))),
    ]
)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用sklearn Pipeline和FeatureUnion选择多个(数字和文本)列进行文本分类? 的相关文章

随机推荐