首页 > 解决方案 > Sklearn 使用带有数字数据的自然语言处理

问题描述

我正在将 sklearn 用于一个项目,并且我有两列可用于预测。一栏是text,是系列文章,另一栏是 ,equal_cnts是实数。我正在尝试创建一个使用 SVM 对文本和数字进行训练的模型,但我无法弄清楚如何使用这两个功能。

vect = CountVectorizer(ngram_range=(1, 2))
tfidf = TfidfTransformer()
svm = svm.SVC(kernel='linear', C = 100, gamma = 0.1)

text_clf = Pipeline([('vect', vect), ('tfidf', tfidf), ('svm', svm)])
scores = cross_val_score(text_clf, pd.concat([df['text'], df['equal_cnt']], axis = 1), df['empirical'], cv=10)

我目前正在尝试执行上述操作,其中 Pipeline 旨在处理文本,并且模型正在针对df["empirical"].

标签: pythonpandasscikit-learnnltk

解决方案


我认为使用 scikit-learn 执行此操作的现代而巧妙的方法将使用ColumnTransformerand 看起来像这样:

from sklearn.pipeline import make_pipeline
from sklearn.compose import ColumnTransformer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.svm import SVC

X = df.drop("empirical", axis=1)
y = df["empirical"]

preprocessor = ColumnTransformer(
    # We apply a TF-IDF vectorizer to the "text" column
    [("text", TfidfVectorizer(max_features=10), "text"),], 
    # the "passthrough" value for the "remainder" parameter lets 'equal_cnt' pass 
    # through the first stage of the pipeline without modifying this column
    remainder="passthrough"  
)
classifier = SVC(kernel='linear', C=1., gamma='scale')

pipeline = make_pipeline(preprocessor, classifier)

scores = cross_val_score(pipeline, X, y, cv=10)

当然,您可以根据需要调整 TF-IDF 和 SVM 超参数。


推荐阅读