2017-10-14 102 views
0

我最初使用MultinomialNB并且代码在预测新文本时工作得很好。但是当我将它改为SVC时,它总是返回数组(1),这意味着'不是技术',即使我预测'电脑很酷'。经过检查显然,它每一次都会返回“政治”。 MultinomialNB使用相同的代码没有问题。 我做错了什么?Python sklearn文本预测总是返回相同的结果

请注意训练数据是一个带有新闻标题和类别的标签分隔文件,类似。

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') 

回答

0

我找到了解决办法是简单地使用LinearSVC相反,由于SVC显然只有一个比较VS一类,而LinearSVC一个比较VS休息。

+0

不明白你说的。 SVM有一个“decision_function_shape”,默认值为“ovr” - 一个与其余的。 –

+0

说实话我还是个初学者,这是阅读文档后最简单的方法。不知道还有另一种选择。我会找的,谢谢。 编辑:我阅读文档,它说它默认已经“ovr”,但由于某种原因它没有工作。 –

相关问题