【问题标题】:How to save a text classification model and test it later on a new unseen data如何保存文本分类模型并稍后在新的看不见的数据上进行测试
【发布时间】:2019-10-26 12:36:03
【问题描述】:

我是 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 方面的专业知识较少,我可能会犯一些错误。有人请指出我在哪里做错了。感谢期待。

【问题讨论】:

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


    【解决方案1】:

    首先,您训练并保存的逻辑回归模型适用于 tfidf 值数组。那么,为什么在加载模型后,您要在 .csv 文件上进行预测?你不应该先用 pandas 加载 csv 文件并通过tfidf_vect_ngram 传递它,然后将数组/列传递给加载的模型吗?所以你还需要保存tfidf_vect_ngram。基本上

    X_test_tfidf = tfidf_vect_ngram.transform(X_test) # X_test can be the entire column if you are loading from a separate file
    result = loaded_model.predict(X_test_tfidf)
    score = loaded_model.score(X_test_tfidf, y_test)
    

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

    【讨论】:

      猜你喜欢
      • 2021-02-08
      • 2023-03-14
      • 2021-01-25
      • 1970-01-01
      • 2017-08-06
      • 1970-01-01
      • 2018-08-16
      • 2018-08-27
      • 2020-02-10
      相关资源
      最近更新 更多