python - 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"]
.
解决方案
我认为使用 scikit-learn 执行此操作的现代而巧妙的方法将使用ColumnTransformer
and 看起来像这样:
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 超参数。
推荐阅读
- php - Laravel API 更改 api 的链接
- android - 需要使用哪些类在android中的准确时间获取每日提醒
- elasticsearch - 我们如何添加功能,例如您的意思和建议
- firebase - 使用 Firebase Firestore 跟踪应用
- dart - Dart:为什么创建的实例不相同但它们访问的变量是相同的?
- json - 如何使用 API 中的 Rest Post 方法以 Xamarin 形式在标签中显示 JSON 数据
- html - cdk-virtual-scroll-viewport 有没有办法从底部元素开始而不滚动?
- java - 从一组 Java Pojo 类创建 JSON 结构
- php - 在 prestashop 中的自定义模块上创建自定义控制器后台
- javascript - 如何提醒用户更改未保存