「オブジェクトを永続化する」とは、基本的に、メモリに格納されたオブジェクトを表すバイナリ コードをハード ドライブ上のファイルにダンプすることを意味します。ハード ドライブ内のファイルからメモリにリロードされます。
scikit-learn が含まれてjoblib
いるか、stdlibが含まれていて、その仕事pickle
をcPickle
するでしょう。cPickle
それはかなり速いので、私は好む傾向があります。ipython の %timeit コマンドを使用:
>>> from sklearn.feature_extraction.text import TfidfVectorizer as TFIDF
>>> t = TFIDF()
>>> t.fit_transform(['hello world'], ['this is a test'])
# generic serializer - deserializer test
>>> def dump_load_test(tfidf, serializer):
...: with open('vectorizer.bin', 'w') as f:
...: serializer.dump(tfidf, f)
...: with open('vectorizer.bin', 'r') as f:
...: return serializer.load(f)
# joblib has a slightly different interface
>>> def joblib_test(tfidf):
...: joblib.dump(tfidf, 'tfidf.bin')
...: return joblib.load('tfidf.bin')
# Now, time it!
>>> %timeit joblib_test(t)
100 loops, best of 3: 3.09 ms per loop
>>> %timeit dump_load_test(t, pickle)
100 loops, best of 3: 2.16 ms per loop
>>> %timeit dump_load_test(t, cPickle)
1000 loops, best of 3: 879 µs per loop
複数のオブジェクトを 1 つのファイルに格納する場合は、それらを格納するデータ構造を簡単に作成してから、データ構造自体をダンプできます。これはtuple
、list
またはで動作しdict
ます。あなたの質問の例から:
# train
vectorizer = TfidfVectorizer()
X_train = vectorizer.fit_transform(corpus)
selector = SelectKBest(chi2, k = 5000 )
X_train_sel = selector.fit_transform(X_train, y_train)
# dump as a dict
data_struct = {'vectorizer': vectorizer, 'selector': selector}
# use the 'with' keyword to automatically close the file after the dump
with open('storage.bin', 'wb') as f:
cPickle.dump(data_struct, f)
後で、または別のプログラムで、次のステートメントはプログラムのメモリにデータ構造を戻します。
# reload
with open('storage.bin', 'rb') as f:
data_struct = cPickle.load(f)
vectorizer, selector = data_struct['vectorizer'], data_struct['selector']
# do stuff...
vectors = vectorizer.transform(...)
vec_sel = selector.transform(vectors)