将保存的keras模型从gs加载到pydatalab

时间:2018-01-23 00:36:56

标签: python model keras google-cloud-datalab

我的keras模型使用model.save(model_name)

保存在google存储中

我无法在pydatalab上加载模型。当我在本地计算机上保存模型时,我可以使用load_model(filepath)打开它。 我也确实将keras.backend导入为K,基于 NameError when opening Keras model that uses Tensorflow Backend

我尝试了以下内容:

  1. model = load_model(tf.gfile.Open(model_file))
    
  2. 错误:TypeError:预期的str,bytes或os.PathLike对象,而不是GFile

    1. load_model('gs://mybucket/model.h5')
      
    2. 错误:IOError:无法打开文件(无法打开文件:name =' gs://mybucket/model.h5' ;, errno = 2,错误消息='没有此类文件或目录',flags = 0,o_flags = 0)

      1. with file_io.FileIO(model_file, 'r') as f:
        modl = load_model(f)
        
      2. 错误:TypeError:预期的str,bytes或os.PathLike对象,而不是FileIO

4 个答案:

答案 0 :(得分:3)

从gs storage

加载文件
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)

答案 1 :(得分:2)

我不认为Keras支持TensorFlow文件系统,后者又知道如何从GCS读取。

您可以尝试从GCS下载到本地路径,然后从中读取以加载模型。

答案 2 :(得分:0)

以下功能可用于在gcloud机器学习平台(感谢TíarnánMcGrath)上重新训练已经训练过的keras模型(具有新数据)。

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对我来说不再起作用,因此我每次都必须构建模型。

答案 3 :(得分:0)

也可以使用OS级命令,以防万一有人使用Colab

要堆砌Google驱动器,请使用

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/ 

现在文件model.h5在驱动器/ content / drive /我的驱动器/模型/中可用 使用以下命令移至模型目录:

!cd /content/drive/My\ Drive/models/

load_model('model.h5')

希望这会有所帮助!