如何通过保存训练模型使用pickle来减少编译时间?

这是一段情感分析代码,每次我更改输入时,编译需要10到15分钟。有什么方法可以减少这个时间?使用pickle保存分类器或者其他方法,哪个更可取?这里没有提到其他函数。

inpTweets = csv.reader(open('training_neatfile_4.csv', 'r' ,encoding='ISO-8859-1'), delimiter=',')stopWords = getStopWordList('stopwords.txt')count = 0;featureList = []tweets = []for row in inpTweets:    sentiment = row[0]    tweet = row[1]    processedTweet = processTweet(tweet)    featureVector = getFeatureVector(processedTweet, stopWords)    featureList.extend(featureVector)    tweets.append((featureVector, sentiment));#end loop# Remove featureList duplicatesfeatureList = list(set(featureList))# Generate the training settraining_set = nltk.classify.util.apply_features(extract_features, tweets)# Train the Naive Bayes classifiernb_classifier = nltk.NaiveBayesClassifier.train(training_set)# Test the classifiertestTweet = 'He is a brainless kid'processedTestTweet = processTweet(testTweet)sentiment = nb_classifier.classify(extract_features(getFeatureVector(processedTestTweet, stopWords)))print ("testTweet = %s, sentiment = %s\n" % (testTweet, sentiment))

回答:

训练一个NaiveBayesClassifier(或其他任何分类器)需要很长时间(取决于训练数据的输入),如果你在训练后保存分类器的对象(NBClassifier),可以避免重新训练,从而节省时间。

以下是使用pickle保存对象的方法,你可以在你的代码中使用它来保存或加载分类器。

import picklepickle.dump(object, file)

你可以通过保存NaiveBayesClassifier的对象(nb_classifier)来保存它,如下所示。

with open('model.pkl', 'wb') as nb_classifier_model:    pickle.dump(nb_classifier, nb_classifier_model)

然后,你可以这样检索它:

with open('model.pkl', 'rb') as nb_classifier_model:    nb_classifier = pickle.load(nb_classifier_model)

这就是你可以实现目标的方法,按需使用即可。

希望这对你有帮助!

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注