首页 文章

从Google Cloud 端硬盘将Keras模型导入Colaboratory

提问于
浏览
0

我正在尝试找到加载以.h5格式保存的Keras模型的方法,该格式存储在Google Cloud 端硬盘中,直接存入Colaboratory工作表,用作Keras模型(无需首先下载到桌面,已有方法) .

我已成功使用Drive REST API的Colaboratory教程加载.h5文件:

# Download the '.h5' file from google drive

file_id = '1uBtlaggVyWshwcyP6kEI-y_W3P8D26sz'

import io
from io import BytesIO   
from googleapiclient.http import MediaIoBaseDownload

request = drive_service.files().get_media(fileId=file_id)
downloaded = io.BytesIO()
downloader = MediaIoBaseDownload(downloaded, request)
done = False
while done is False:
  status, done = downloader.next_chunk()
  if status:
      print("Download %%%d%%." % int(status.progress() * 100))
  print("Download Complete!")

downloaded.seek(0)

print('Downloaded file contents are: {}'.format(downloaded.read()))

哪个输出:

Download %100%.
Download Complete!
Downloaded file contents are: b'\x89HDF\r\n\x1a\n\x00\x00\x00...(etc)

似乎downloaded.read()给出了一种字节字符串 .

我的问题是如何将此字节字符串转换为.h5格式,以便我可以从Keras调用load_model?

1 回答

  • 0

    最简单的选择是将其写入文件:

    with open('/tmp/model.h5', 'wb') as f:
        f.write(downloaded.read())
    

    然后创建一个文件作为 h5py.File('/tmp/model.h5') 传递给keras .

相关问题