[英]Sci-Kit Learn Classifier Loading issue : Vocabulary wasn't fitted or is empty! when using transform
我正在通过https://www.kaggle.com/c/word2vec-nlp-tutorial上的Sci-Kit学习教程进行学习。
我通过将教程分成2个文件来稍微偏离本教程,其中一个文件用于训练分类器,然后将分类器保存到文件中。 另一个文件,用于加载分类器并预测testFile
上的testFile
。 原始程序要求在矢量化器上执行转换,但是出现错误:
Vocabulary wasn't fitted or is empty! at the line :
test_data_features = vectorizer.transform(clean_test_reviews)
我还需要在此文件中初始化矢量化器对象,因为矢量化器位于最后一个文件中。 如果我将行更改为fit_transform
,程序将运行并按预期打印出带有标签的文件。 我确实担心,尽管可能是通过学习测试集上的vocab,然后拟合数组来造成逻辑错误。 这是加载分类器,准备测试数组,预测结果并将结果写入文件的代码。 我见过的其他答案只是加载pickle文件并尝试进行预测,但是我不确定如何将clean_test_reviews
转换为正确的数据结构然后传递给进行预测。 任何帮助表示赞赏。 谢谢!
##load the classifier
forest = joblib.load(classifier)### put in the name of the classifer, 'filename.pkl'
# Read the test data
test = pd.read_csv(infile, header=0, delimiter="\t", \
quoting=3 ) #infile is testData.tsv
# Verify that there are 25,000 rows and 2 columns
print "Test shape(Rows, Columns of Data):", test.shape
# Create an empty list and append the clean reviews one by one
num_reviews = len(test["review"])
clean_test_reviews = []
print "Cleaning and parsing the test set...\n"
for i in xrange(0,num_reviews):
if( (i+1) % 1000 == 0 ):
print "Review %d of %d\n" % (i+1, num_reviews)
clean_review = review_to_words( test["review"][i] )
clean_test_reviews.append( clean_review )
# Initialize the "CountVectorizer" object, which is scikit-learn's
# bag of words tool.
vectorizer = CountVectorizer(analyzer = "word", \ tokenizer = None, \ preprocessor = None, \ stop_words = None, \ max_features = 5000)
# Get a bag of words for the test set, and convert to a numpy array
test_data_features = vectorizer.transform(clean_test_reviews)
test_data_features = test_data_features.toarray()
print "Test data feature shape:", test_data_features.shape
# Take a look at the words in the vocabulary
vocab = vectorizer.get_feature_names()
print vocab
# Use the random forest to make sentiment label predictions
result = forest.predict(test_data_features)
# Copy the results to a pandas dataframe with an "id" column and
# a "sentiment" column
output = pd.DataFrame( data={"id":test["id"], "sentiment":result} )
# Use pandas to write the comma-separated output file
output.to_csv( outfile, index=False, quoting=3 ) # "Bag_of_Words_model.csv",
您担心担心将CountVectorizer
安装在测试集上是正确的。 使用CountVectorizer
,如果在两个不同的数据集上调用fit()
,则会得到两个具有不同词汇量的不兼容矢量化器。 相反,您应该使用pickle
或joblib
将矢量化程序保存到文件以及分类程序中。 您当前正在保存。
根据上述David Maust的回答,我能够修复它。...在第一个文件中,将矢量化器像这样转储:
joblib.dump(vectorizer.vocabulary_, dictionary_file_path) #dictionary_file_path is something like "./Vectorizer/vectorizer.pkl"
请注意vectorizer.vocabulary_属性上的下划线。 在加载文件中,像这样加载矢量化器:
vocabulary_to_load =joblib.load(dictionary_file_path)
loaded_vectorizer = CountVectorizer(vocabulary=vocabulary_to_load)
...现在使用矢量化器进行转换
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.