我正在尝试进行情感分类,并且使用了sklearn SVM模型。我使用标记的数据训练模型,并获得89%的准确性。现在,我想使用该模型来预测未标记数据的情绪。我怎样才能做到这一点?在对未标记数据进行分类之后,如何查看其被分类为阳性还是阴性?
我使用python 3.7。下面是代码。
import random
import pandas as pd
data = pd.read_csv("label data for testing .csv", header=0)
sentiment_data = list(zip(data['Articles'], data['Sentiment']))
random.shuffle(sentiment_data)
train_x, train_y = zip(*sentiment_data[:350])
test_x, test_y = zip(*sentiment_data[350:])
from nltk import word_tokenize
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.pipeline import Pipeline
from sklearn.svm import LinearSVC
from sklearn import metrics
clf = Pipeline([
('vectorizer', CountVectorizer(analyzer="word",
tokenizer=word_tokenize,
preprocessor=lambda text: text.replace("<br />", " "),
max_features=None)),
('classifier', LinearSVC())
])
clf.fit(train_x, train_y)
pred_y = clf.predict(test_x)
print("Accuracy : ", metrics.accuracy_score(test_y, pred_y))
print("Precision : ", metrics.precision_score(test_y, pred_y))
print("Recall : ", metrics.recall_score(test_y, pred_y))
运行此代码时,我得到输出:
ConvergenceWarning:Liblinear无法收敛,增加了迭代次数。 “迭代次数。”,ConvergenceWarning)精度:0.8977272727272727精度:0.8604651162790697召回率:0.925
ConvergenceWarning是什么意思?
预先感谢!
基本上,您以与生成train_x
或test_x
相同的方式聚合未标记的数据。可能是形状为n_samples x 1
的2D矩阵,然后您可以在clf.predict
中使用它来获得预测。clf.predict
输出最可能的类别。在您的情况下,0
为负,1
为正,但是没有数据集很难分辨。ConvergenceWarning是什么意思?
LinearSVC模型使用迭代算法进行了优化。有一个参数max_iter
(默认为1000),用于控制最大迭代次数。如果在此过程中未满足停止条件,则将获得ConvergenceWarning
。只要您在准确性或其他指标方面具有可接受的性能,它就不会打扰您。
[正如Pavel已经提到的,ConvergenceWArning表示已击中max_iter
,您可以在此处阻止警告:How to disable ConvergenceWarning using sklearn?现在我要使用该模型来预测未标记的情绪数据。我该怎么办?
您将使用以下命令执行此操作:pred_y = clf.predict(test_x)
,唯一要调整的是:pred_y
(这是您的自由选择),而test_x
应该是您新的看不见的数据,它必须具有具有与数据test_x
和train_x
相同的功能。如何查看它是正还是负?
您可以运行:pred_y
,结果将为1或0。通常0应该是负数,但这取决于您的数据集[]