【问题标题】:Import Weights from Keras Classifier into TF Object Detection API将 Keras 分类器中的权重导入 TF 对象检测 API
【发布时间】:2019-04-08 17:39:59
【问题描述】:

我有一个使用 keras 训练的分类器,效果非常好。它使用keras.applications.MobileNetV2

这个分类器在大约 200 个类别上训练有素,并且具有很高的准确度。

但是,我想将此分类器的特征提取层用作对象检测模型的一部分。

我一直在使用 Tensorflow 对象检测 API,并研究 SSDLite+MobileNetV2 模型。我可以开始训练,但是训练很慢,而且大部分损失来自分类阶段。

我想做的是将我的 keras .h5 模型中的权重分配给 Tensorflow 中 MobileNetV2 的特征提取层,但我不确定最好的方法。

我可以轻松加载h5 文件,并获取图层名称列表:

import keras

keras_model = keras.models.load_model("my_classifier.h5")

keras_names = [l.name for l in keras_model.layers]

print(keras_names)

我还可以从对象检测 API 中恢复 tensorflow 检查点并导出带有权重的层:

tf.reset_default_graph()

with tf.Session() as sess:

    new_saver = tf.train.import_meta_graph('models/model.ckpt.meta')

    what = new_saver.restore(sess, 'models/model.ckpt')


    tf_names = []
    for op in sess.graph.get_operations():
        if "MobilenetV2" in op.name and "Assign" in op.name:
            tf_names.append(op.name)

    print(tf_names)

我似乎无法在 keras 和 tensorflow 的层名称之间找到很好的匹配。即使可以,我也不确定接下来的步骤。

如果有人能给我一些关于解决此问题的最佳方法的建议,我将不胜感激。

更新:

我遵循了 Sharky 的以下建议,稍作修改:

new_saver = tf.train.import_meta_graph(os.path.join(keras_checkpoint_dir, 'keras_model.ckpt.meta'))

new_saver.restore(sess, os.path.join(keras_checkpoint_dir, tf.train.latest_checkpoint(keras_checkpoint_dir)))

但不幸的是,我现在收到此错误:

NotFoundError(参见上文的回溯):从检查点恢复 失败的。这很可能是由于变量名称或其他图形键 检查点缺少的。请确保您没有 根据检查点更改了预期的图形。原始错误:

键 FeatureExtractor/MobilenetV2/expanded_conv_6/project/BatchNorm/gamma 在检查点 [[node save/RestoreV2_295 (定义在 :7) = RestoreV2[dtypes=[DT_FLOAT], _device="/job:localhost/replica:0/task:0/device:CPU:0"](_arg_save/Const_0_0, 保存/RestoreV2_295/tensor_names, 保存/恢复V2_295/shape_and_slices)]] [[{{节点 保存/恢复V2_196/_393}} = _Recvclient_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device_incarnation=1, tensor_name="edge_789_save/RestoreV2_196", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:GPU:0"]]

关于如何摆脱这个错误的任何想法?

【问题讨论】:

  • 我想最简单的方法是将keras模型转换为估计器,保存ckpt文件并使用它。这适合你的情况吗?
  • 我可以试一试,我刚刚找到了这个参考:tensorflow.org/api_docs/python/tf/keras/estimator/…。看来值得一试
  • 您可以使用tf.train.list_variables 检查检查点文件,并将其与 global_variables 集合进行比较。您还可以使用 tf.train_init_from_checkpoint 仅加载特定变量。或者可能只是名称/范围不匹配

标签: tensorflow keras


【解决方案1】:

您可以使用tf.keras.estimator.model_to_estimator

estimator = tf.keras.estimator.model_to_estimator(keras_model=model, model_dir=path)
saver = tf.train.Saver()
with tf.Session() as sess:
    saver.restore(sess, os.path.join(path/keras, tf.train.latest_checkpoint(path/keras)))
    print(tf.global_variables())

这应该可以完成工作。请注意,它将在最初指定的路径内创建一个子目录。

【讨论】:

  • 我尝试了您的建议,但遇到了另一个问题
猜你喜欢
  • 2017-06-12
  • 2021-07-22
  • 1970-01-01
  • 2021-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-20
  • 1970-01-01
相关资源
最近更新 更多