【问题标题】:Machine Learning Classification using categorical and text data as input使用分类和文本数据作为输入的机器学习分类
【发布时间】:2021-03-27 08:38:36
【问题描述】:

我有一个大约 400 行的数据集,其中包含几个分类数据列,还有一个文本形式的描述列作为我的分类模型的输入。我计划使用 SVM 作为我的分类模型来执行分类。由于模型不能接受非数字数据作为输入,因此我将输入特征转换为数字数据

我已经为我的描述列执行了 TF-IDF,它已将术语转换为矩阵形式。

是否需要使用标签编码转换分类特征,然后将其与 TF-IDF 合并,然后再将其输入机器学习模型?

【问题讨论】:

    标签: machine-learning scikit-learn classification


    【解决方案1】:

    使用ColumnTransformer 将不同的管道转换应用于具有不同数据类型的列。这是一个例子:

    from sklearn.compose import ColumnTransformer
    from sklearn.pipeline import Pipeline
    from sklearn.feature_extraction.text import TfidfVectorizer
    from sklearn.preprocessing import OneHotEncoder
    from sklearn.svm import SVC
    
    
    # pipeline for text data
    text_features = 'text_column'
    text_transformer = Pipeline(steps=[
        ('vectorizer', TfidfVectorizer(stop_words="english"))
    ])
    
    # pipeline for categorical data
    categorical_features = ['cat_col1', 'cat_col2',]
    categorical_transformer = Pipeline(steps=[
        ('imputer', SimpleImputer(strategy='constant', fill_value='missing')),
        ('onehot', OneHotEncoder(handle_unknown='ignore'))
    ])
    
    # you can add other transformations for other data types
    
    # combine preprocessing with ColumnTransformer
    preprocessor = ColumnTransformer(
        transformers=[
            ('text', text_transformer, text_features),
            ('cat', categorical_transformer, categorical_features)
    ])
    
    # add model to be part of pipeline
    clf_pipe =  Pipeline(steps=[('preprocessor', preprocessor),
                       ("model", SVC())
    ])
    
    # ...
    
    ## you can just use preprocessor by itself
    # X_train = preprocessor.fit_transform(X_train)
    # X_test = preprocessor.transform(X_test)
    # clf_s= SVC().fit(X_train, y_train)
    # clf_s.score(X_test, y_test)
    
    ## or better, you can use the whole.
    # clf_pipe.fit(X_train, y_train) 
    # clf_pipe.score(X_test, y_test)
    
    

    Scikit-learn Example for more details

    【讨论】:

    • 你能解释一下为什么 X 中的列数是 13,但在 X_test 和 X_train 中,列数下降到 11。我也试图从preprocessor.transform(X_test)
    • 是的!没有看到你的代码很难说。但是数据拆分时列数不应该改变。改造后,您将拥有一张宽大的桌子。如果您的矢量化器中未设置 max_features 的数量,则仅考虑在整个语料库中按词频排序的最高 max_features 的词汇表将是仅由此转换生成的列数,并且 onehotencoding 也将添加到该列数中。跨度>
    猜你喜欢
    • 2018-03-09
    • 1970-01-01
    • 2015-01-16
    • 2020-02-08
    • 2017-07-01
    • 2021-06-17
    • 2020-05-04
    • 1970-01-01
    • 2019-03-06
    相关资源
    最近更新 更多