【问题标题】:How to integrate a keras model to a tensorflow network如何将 keras 模型集成到 tensorflow 网络中
【发布时间】:2019-01-02 02:19:29
【问题描述】:

我想将经过 keras 训练的模型集成到 tensorflow 网络中,以帮助训练 tensorflow 模型,即不需要再次训练 keras 模型,它只会对 tensorflow 模型产生损失。下图是基本的网络架构。

以下代码是为 keras 模型生成损失。但是,不幸的是,它未能加载预训练的 keras 模型,尽管它没有给出任何错误。即,代码可以工作,但它只是加载了一个随机模型(变量的随机值),它返回一个随机值,而不是预训练模型生成的值。

def keras_loss(sess,prediction):
  #import package
  from keras.models import Model
  from keras.models import Sequential
  from keras.layers import Dense, Dropout,InputLayer
  from keras.applications.inception_resnet_v2 import InceptionResNetV2
  from keras.applications.inception_resnet_v2 import preprocess_input  
  from keras.preprocessing.image import load_img, img_to_array
  from keras import backend as K

  K.set_session(sess)  #sess is the tensorflow model
  K.set_learning_phase(False)
  base_model = InceptionResNetV2 (input_shape=(None, None, 3), include_top=False, pooling='avg', weights=None)
  x = Dropout(0.75)(base_model.output)
  x = Dense(10, activation='softmax')(x)

  model = Model(base_model.input, x) #load the pretrained model
  model.load_weights('./inception_resnet_weights.h5')
  score = model(prediction)  #prediction is a tf tensor

  return score

我阅读了stackoverflow上的相关说明: 1Calling a Keras model on a TensorFlow tensor but keep weights [2]Tensorflow op in Keras model [3]Implementing a tensorflow graph into a Keras model

但它仍然无法解决我的问题。有人可以帮助我吗? 提前致谢

【问题讨论】:

  • 如果您在 InceptionResNetV2 中使用关键字参数加载权重,是否仍会获得随机权重:weights='imagenet'?

标签: tensorflow keras


【解决方案1】:

来自kerasdocs

权重:无(随机初始化)或“imagenet”(ImageNet 上的预训练)之一。

您想使用weights='imagenet' 而不是None

【讨论】:

  • 要加载的模型是我们的微调模型“inception_resnet_weights.h5”,而不是网站上的默认模型。如果我使用weights='imagenet',它会生成一个 URL 错误。
猜你喜欢
  • 2018-12-08
  • 1970-01-01
  • 1970-01-01
  • 2020-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-04
  • 1970-01-01
相关资源
最近更新 更多