Python sklearn 文本预测总是返回相同的结果



我最初使用的是MultinomialNB,代码在预测新文本方面工作得很好。但是当我将其更改为 SVC 时,它总是返回数组 (1),这意味着"不是技术",即使我预测"计算机很酷"。在检查了一下之后,它每次都返回"政治"。使用相同的代码进行多项式NB没有问题。我做错了什么?

请注意,训练数据是一个制表符分隔的文件,其中包含新闻标题和类别,类似于。

Title                                   Category
The new President of United States      politics

这是代码:

path="c:/newstrainingutf8.txt"
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
from sklearn import svm
from sklearn import metrics
news=pd.read_table(path, header=0, names=['category', 'title'], encoding='utf-8')
news['category_num']=news.category.map({'business':1,'entertainment':1,'health':1,'politics':1,'science':1, 'technology':0, 'world':1})
X=news.title
y=news.category_num
X_train, X_test, y_train, y_test=train_test_split(X,y,random_state=1)
vect=CountVectorizer()
vect.fit(X_train.values.astype('U'))
X_train_dtm = vect.transform(X_train.values.astype('U'))
X_train_dtm=vect.fit_transform(X_train.values.astype('U'))
X_test_dtm=vect.transform(X_test.values.astype('U'))
svm = svm.SVC()
svm.fit(X_train_dtm, y_train)
y_pred_class=svm.predict(X_test_dtm)
metrics.accuracy_score(y_test, y_pred_class)
svm.predict(vect.transform(['computers are cool']))
newinput="f:/newinput.txt"
newoutput="f:/newoutput.txt"
input=pd.read_table(newinput, header=0, names=['cat','title','link'], encoding='utf-8')
input.cat=svm.predict(vect.transform(input.title))
input.to_csv(newoutput, sep='t', header=None, index=None, mode='a', encoding='utf-8')

我发现解决方案只是简单地使用LinearSVC,因为SVC显然只比较一个类别与一个类别,而LinearSVC比较一个类别与其他类别。

最新更新