如何保存文本分类模型并稍后在新的看不见的数据上对其进行测试

时间:2019-06-12 04:29:50

标签: python machine-learning scikit-learn text-classification natural-language-processing

我是python的新手,正在研究二进制文本分类问题。我已经开发了文本分类模型。现在,我想保存经过训练的模型,然后再次重新加载它,以在新的测试数据文件上对其进行测试。

我在堆栈溢出时尝试了pickle和joblib来完成此任务,并尝试了其他一些建议的方法,但是无法执行此操作。使用一种方法,我成功保存了模型,但是无法在新的测试数据文件上对其进行测试。任何帮助将不胜感激。抱歉,如果我不能很好地解释问题,因为我是python的新手。

Dataset = pd.read_csv('trainingdata.csv')
my_types = ['Requirement','Non-Requirement']


X_train, X_test, y_train, y_test = model_selection.train_test_split(Dataset['description'],Dataset['types'],test_size=0.0, random_state=45)

tfidf_vect_ngram = TfidfVectorizer(analyzer='word', 
token_pattern=r'\w{1,}', ngram_range=(1,1), max_features=5000)
tfidf_vect_ngram.fit(Dataset['description'])
X_train_Tfidf =  tfidf_vect_ngram.transform(X_train)

logreg = LogisticRegression(n_jobs=1, C=1e5)
logreg.fit(X_train_Tfidf, y_train)

import pickle
filename = 'finalized_model.sav'
pickle.dump(logreg, open(filename, 'wb'))

loaded_model = pickle.load(open(filename, 'rb'))
result = loaded_model.score('testdata.csv')
print(result)    

我也尝试过这个。

with open('text_classifier', 'wb') as picklefile:  
    pickle.dump(logreg,picklefile)

with open('text_classifier', 'rb') as training_model:  
    model = pickle.load(training_model)

result = model.predict('testdata.csv')
print(result)

我尝试过的另一种解决方案。

from keras.models import load_model

logreg.save('my_model.h5') 
del logreg

model = load_model('my_model.h5')
result=model('projectay.csv')
print(result)

尽管尝试了多种解决方案,但无法获得所需的结果。由于我在机器学习和python方面的专业知识较少,我可能会犯一些错误。可能有人请指出我在哪里做错了。谢谢您。

1 个答案:

答案 0 :(得分:0)

首先,您已训练并保存的逻辑回归模型适用于tfidf值数组。那么,为什么在加载模型之后对.csv文件进行预测?您是否不应该首先使用pandas加载csv文件并将其通过df.to_csv(r'C:\Users\myname\Desktop\export_test.csv', index = None, header=True) ,然后将数组/列传递给已加载的模型?因此,您还需要保存tfidf_vect_ngram。基本上

tfidf_vect_ngram

如果这不是问题,您是否还可以发布错误日志/输出,而不是简单地说它不起作用。这样我们就可以找出问题出在哪里。