[英]loading saved keras model from gs to pydatalab
我的 keras 模型使用 model.save(model_name) 保存在谷歌存儲中
我無法在 pydatalab 上加載模型。 當我將模型保存在本地機器上時,我可以使用 load_model(filepath) 打開它。 在打開使用 Tensorflow 后端的 Keras 模型時,我也基於NameError將 keras.backend 導入為 K
我嘗試了以下方法:
model = load_model(tf.gfile.Open(model_file))
錯誤:類型錯誤:預期的 str、bytes 或 os.PathLike 對象,而不是 GFile
load_model('gs://mybucket/model.h5')
錯誤:IOError: Unable to open file (unable to open file: name = 'gs://mybucket/model.h5', errno = 2, error message = 'No such file or directory', flags = 0, o_flags = 0 )
with file_io.FileIO(model_file, 'r') as f: modl = load_model(f)
錯誤:類型錯誤:預期的 str、bytes 或 os.PathLike 對象,而不是 FileIO
從 gs 存儲加載文件
from tensorflow.python.lib.io import file_io
model_file = file_io.FileIO('gs://mybucket/model.h5', mode='rb')
在本地保存模型的臨時副本
temp_model_location = './temp_model.h5'
temp_model_file = open(temp_model_location, 'wb')
temp_model_file.write(model_file.read())
temp_model_file.close()
model_file.close()
加載本地保存的模型
model = load_model(temp_model_location)
我認為 Keras 不支持 TensorFlow 文件系統,后者又知道如何從 GCS 讀取。
您可以嘗試從 GCS 下載到本地路徑,然后從中讀取以加載模型。
以下函數適用於在 gcloud 機器學習平台上重新訓練已經訓練好的 keras 模型(使用新數據)(感謝 Tíarnán McGrath)。
def load_models(model_file):
model = conv2d_model() #the architecture of my model, not compiled yet
file_stream = file_io.FileIO(model_file, mode='r')
temp_model_location = './temp_model.h5'
temp_model_file = open(temp_model_location, 'wb')
temp_model_file.write(file_stream.read())
temp_model_file.close()
file_stream.close()
model.load_weights(temp_model_location)
return model
出於某種原因, load_model
從keras.models
不為我工作了,所以我每次都要建立模型。
也可以使用操作系統級別的命令,以防有人使用 Colab
使用你的谷歌驅動器
from google.colab import drive
drive.mount('/content/drive', force_remount=True)
掛載 GCS 的代碼
from google.colab import auth
auth.authenticate_user()
project_id = 'thirumalai_bucket' #your bucket here
!gcloud config set project {project_id}
!gsutil ls
!gsutil -m cp
在你的情況下:
!gsutil -m cp gs://mybucket/model.h5 /content/drive/My\ Drive/models/
現在驅動器 /content/drive/My Drive/models/ 中可用的文件 model.h5 移動到您的模型目錄,使用:
!cd /content/drive/My\ Drive/models/
load_model('model.h5')
希望這有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.