我正在使用 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)
我目前正在尝试执行上述操作,其中管道旨在处理文本,并且正在根据 df["empirical"]
测试模型的准确性。
最佳答案
您可以将稀疏矩阵从 TFIDF 转换器转换为数据框,然后只需将数值列作为额外列分配给该数据框。让我通过一个例子向您展示这一点:
from sklearn.feature_extraction.text import TfidfVectorizer
import pandas as pd
corpus = [
'This is the first document.',
'This document is the second document.',
'And this is the third one.',
'Is this the first document?',
]
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(corpus)
textMatDf = pd.DataFrame(X.toarray())
textMatDf['numCol'] = df['equal_cnt']
现在这个textMatDf可以用于训练和验证。
关于python - Sklearn 使用自然语言处理数值数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59889272/