2014-09-20 153 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