- 追加された行はこの色です。
- 削除された行はこの色です。
- Pickel へ行く。
#author("2023-12-16T16:25:01+09:00;2023-12-16T16:14:10+09:00","default:inoue.ko","inoue.ko")
* Pickel
https://docs.python.org/ja/3/library/pickle.html
~
pickle モジュールは Python オブジェクトの直列化および直列化されたオブジェクトを復元するためのモジュールです。''機械学習においては、学習済みのモデルの Save & Load に利用されます。''
&small(注)Pickle 化:直列化 serialization、整列化 marshalling、平坦化 flattening と同義);
~
~
**事例
以下、学習済みモデルを利用する際の pickle の活用事例です。
__[[Pre_trainedModel.ipynb>https://github.com/koichi-inoue/DataScience/blob/main/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)です。
__[[NeuralNetwork_Iris.ipynb>https://github.com/koichi-inoue/DataScience/blob/main/NeuralNetwork_Iris.ipynb]]__
~
~