我正在使用NLTK和SKlearn测试情绪分析模型。
Movie_reviews数据具有“ pos”和“ neg”标签。为了训练分类器,我使用“功能集”。我在训练数据上使用交叉验证,在测试数据上使用准确性。但是,交叉验证始终比准确性高得多。在下面的逻辑回归算法示例中,CV = 97(平均),准确度=70。我也使用其他算法进行了测试,但交叉验证仍然很高。
我很确定我用于交叉验证的代码不正确。
import nltk
import random
from nltk.corpus import movie_reviews
from sklearn import cross_validation
from nltk.classify.scikitlearn import SklearnClassifier
from sklearn.linear_model import LogisticRegression, SGDClassifier
documents = [(list(movie_reviews.words(fileid)), category)
for category in movie_reviews.categories()
for fileid in movie_reviews.fileids(category)]
random.shuffle(documents)
all_words = []
for w in movie_reviews.words():
all_words.append(w.lower())
all_words = nltk.FreqDist(all_words)
word_features = list(all_words.keys())[:3000]
def find_features(document):
words = set(document)
features = {}
for w in word_features:
features[w] = (w in words)
return features
featuresets = [(find_features(rev), category) for (rev, category) in documents]
training_set = featuresets[:1500]
testing_set = featuresets[1500:]
cv = cross_validation.KFold(len(training_set), n_folds=10, shuffle=True, random_state=None)
LogisticRegression_classifier = SklearnClassifier(LogisticRegression())
for traincv, testcv in cv:
classifier = LogisticRegression_classifier.train(training_set[traincv[0]:traincv[len(traincv)-1]])
print ('CV_accuracy:', nltk.classify.util.accuracy(classifier, training_set[testcv[0]:testcv[len(testcv)-1]]))
print("LogisticRegression_classifier accuracy percent:", (nltk.classify.accuracy(LogisticRegression_classifier, testing_set))*100)
最佳答案
您正在使用training_set [traincv [0]:traincv [len(traincv)-1]],这表示从traincv [0]到traincv [len(traincv)-1]的范围
在您的情况下,traincv [0]和testcv [0]将始终接近0,而traincv [len(traincv)-1]和testcv [len(testcv)-1]将接近1499。因此,您使用的几乎相同进行N折验证时用于培训和测试的数据。
在这里,您实际上需要使用traincv和testcv中存在的子集索引。
import numpy as np
training_set = np.array(training_set)
for traincv, testcv in cv:
classifier = LogisticRegression_classifier.train(training_set[traincv])
print ('CV_accuracy:', nltk.classify.util.accuracy(classifier, training_set[testcv]
关于python - 情绪分析-交叉验证无效分数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38614738/