2014-09-20 154 views
0

有沒有辦法在Python中的內存或文件系統中保存類的實例?我可以用shelve來做到這一點嗎?如何在Python中保存類的實例

以下行是this tutorial的一部分,需要很長時間才能執行,我需要將其緩存以供下一個程序執行。

clf = MultinomialNB().fit(X_train_counts, training_data['targets']) 

clf類型:

>>> type(clf) 
<class 'sklearn.naive_bayes.MultinomialNB'> 

回答

2

是的,你可以使用shelve堅持一個類的實例。 shelve爲您提供了一個字典界面,使過程相對透明。

下面,shelve使用pickle library;如果shelve API不符合您的需求,您可以直接進入該模塊。

scikit-learn明確支持pickle,看到Model persistence

After training a scikit-learn model, it is desirable to have a way to persist the model for future use without having to retrain. The following section gives you an example of how to persist a model with pickle.

+0

不鹹菜有一些用戶自定義對象的問題? – 2014-09-20 18:26:13

+1

@JakobBowyer:不,不是。 Pickle可能對某些類型的對象有問題,但它不是特定於用戶定義的對象。 – 2014-09-20 18:30:50

+0

@MartijnPieters:謝謝。我使用'os.path.isfile'來檢查轉儲文件是否存在加載。這是正確的方式嗎?我使用鏈接中提到的joblib。 – hpn 2014-09-20 19:16:22