如何在Python中使用NLTK NaiveBayesClassifier训练和测试模型后如何预测情感?

问题描述 投票:0回答:1

我正在使用NLTK NaiveBayesClassifier进行情感分类。我训练和测试了带有标签数据的模型。现在,我要预测未标记数据的情绪。但是,我遇到了错误。出现错误的行是:

score_1 = analyzer.evaluate(list(zip(new_data['Articles'])))

错误是:

ValueError:没有足够的值要解压(预期2,得到1)

下面是代码:

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)
new_data = pd.read_csv("Japan Data.csv", header=0)
train_x, train_y = zip(*sentiment_data[:350])
test_x, test_y = zip(*sentiment_data[350:])

from unidecode import unidecode
from nltk import word_tokenize
from nltk.classify import NaiveBayesClassifier
from nltk.sentiment import SentimentAnalyzer
from nltk.sentiment.util import extract_unigram_feats

TRAINING_COUNT = 350


def clean_text(text):
    text = text.replace("<br />", " ")

    return text


analyzer = SentimentAnalyzer()
vocabulary = analyzer.all_words([(word_tokenize(unidecode(clean_text(instance))))
                                 for instance in train_x[:TRAINING_COUNT]])
print("Vocabulary: ", len(vocabulary))

print("Computing Unigran Features ...")

unigram_features = analyzer.unigram_word_feats(vocabulary, min_freq=10)

print("Unigram Features: ", len(unigram_features))

analyzer.add_feat_extractor(extract_unigram_feats, unigrams=unigram_features)

# Build the training set
_train_X = analyzer.apply_features([(word_tokenize(unidecode(clean_text(instance))))
                                    for instance in train_x[:TRAINING_COUNT]], labeled=False)

# Build the test set
_test_X = analyzer.apply_features([(word_tokenize(unidecode(clean_text(instance))))
                                   for instance in test_x], labeled=False)

trainer = NaiveBayesClassifier.train
classifier = analyzer.train(trainer, zip(_train_X, train_y[:TRAINING_COUNT]))

score = analyzer.evaluate(list(zip(_test_X, test_y)))
print("Accuracy: ", score['Accuracy'])

score_1 = analyzer.evaluate(list(zip(new_data['Articles'])))
print(score_1)

我知道出现问题是因为我必须给两个参数是出现错误的行,但我不知道该怎么做。

预先感谢。

nltk python-3.7 sentiment-analysis predict naivebayes
1个回答
0
投票

为您提供错误的行将调用SentimentAnalyzer.evaluate(...)方法。此方法执行以下操作。

评估并打印测试仪上的分类器性能。

请参见SentimentAnalyzer.evaluate

该方法具有一个必需参数:test_set。

test_set –用作金集的(令牌,标签)元组的列表。

您正在通过

list(zip(new_data['Articles']))

功能。我认为您收到了错误消息,因为

list(zip(new_data['Articles']))

不创建元组列表。您可以通过创建包含列表的变量并进行打印或在调试时查看变量的值来进行检查。E.G。

test_set = list(zip(new_data['Articles']))
print("begin test_set")
print(test_set)
print("end test_set")

您正在呼叫评估,在给出错误的那一行的上方三行。

score = analyzer.evaluate(list(zip(_test_X, test_y)))

我猜您想调用SentimentAnalyzer.classify(instance)来预测未标记的数据。参见SentimentAnalyzer.classify

© www.soinside.com 2019 - 2024. All rights reserved.