Pickel
https://docs.python.org/ja/3/library/pickle.html
pickle モジュールは Python オブジェクトの直列化および直列化されたオブジェクトを復元するためのモジュールです。機械学習においては、学習済みのモデルの Save & Load に利用されます。
注)Pickle 化:直列化 serialization、整列化 marshalling、平坦化 flattening と同義
事例
以下、学習済みモデルを利用する際の pickle の活用事例です。
Pre_trainedModel.ipynb
ノートの前半は、GitHub に置かれた学習済みモデル(model.pkl)を読み込んで iris の分類を行う事例。ノートの後半は、GoogleDrive を利用した保存と読み込みの書き方の事例を紹介しています。
GitHubに置かれたファイルを Load する事例
- はじめにァイルの入出力に関わるライブラリの読み込みが必要になります。
import requests from io import BytesIO
- 具体的な読み込みは、以下のようなコードになります。
model_url = 'https://github.com/koichi-inoue/DataScience/raw/main/model.pkl' response = requests.get(model_url) if response.status_code == 200: model_bytes = BytesIO(response.content) with open("model.pkl", "wb") as f: f.write(model_bytes.getvalue()) with open("model.pkl", "rb") as f: loaded_model = pickle.load(f) else: print(f"エラー: {response.status_code}")
Google Drive を利用した保存と読み込み
- Googleドライブを利用する場合は、GoogleDrive のマウントが必要です。
from google.colab import drive drive.mount('/content/drive')
- モデルの SAVE は以下のような書き方になります。
with open('/content/drive/My Drive/・・Path/To・・/model.pkl', 'wb') as file: pickle.dump(model, file)
- モデルの LOAD は以下のような書き方になります。
with open('/content/drive/My Drive/・・Path/To・・/model.pkl', 'rb') as file: loaded_model = pickle.load(file)
使用例
以下、scikit-learn の NeuralNetwork を用いた「iris の分類」と、学種済みモデルを GoogleDrive に保存するコードサンプル(.ipnb)です。