【问题标题】:Is there any way to convert a tensorflow lite (.tflite) file back to a keras file (.h5)?有什么方法可以将 tensorflow lite (.tflite) 文件转换回 keras 文件 (.h5)?
【发布时间】:2020-04-20 21:06:22
【问题描述】:

由于一个粗心的错误,我丢失了我的数据集。我手上只剩下我的 tflite 文件。是否有任何解决方案可以反转 h5 文件。我在这方面做了很好的研究,但没有找到解决方案。

【问题讨论】:

    标签: tensorflow tensorflow2.0 tensorflow-datasets tensorflow-lite


    【解决方案1】:

    从 TensorFlow SaveModel 或 tf.keras H5 模型到 .tflite 的转换是一个不可逆的过程。具体来说,TFLite转换器在编译过程中对原始模型拓扑进行了优化,这导致了一些信息丢失。此外,原始 tf.keras 模型的损失和优化器配置被丢弃,因为这些不是推理所必需的。

    但是,.tflite 文件仍然包含一些可以帮助您恢复原始训练模型的信息。最重要的是,权重值是可用的,尽管它们可能会被量化,这可能会导致一些精度损失。

    下面的代码示例向您展示了如何在 .tflite 文件从经过简单训练的 tf.keras.Model 创建后读取权重值。

    import numpy as np
    import tensorflow as tf
    
    # First, create and train a dummy model for demonstration purposes.
    model = tf.keras.Sequential([
        tf.keras.layers.Dense(10, input_shape=[5], activation="relu"),
        tf.keras.layers.Dense(1, activation="sigmoid")])
    model.compile(loss="binary_crossentropy", optimizer="sgd")
    
    xs = np.ones([8, 5])
    ys = np.zeros([8, 1])
    model.fit(xs, ys, epochs=1)
    
    # Convert it to a TFLite model file.
    converter = tf.lite.TFLiteConverter.from_keras_model(model)
    tflite_model = converter.convert()
    open("converted.tflite", "wb").write(tflite_model)
    
    # Use `tf.lite.Interpreter` to load the written .tflite back from the file system.
    interpreter = tf.lite.Interpreter(model_path="converted.tflite")
    all_tensor_details = interpreter.get_tensor_details()
    interpreter.allocate_tensors()
    
    for tensor_item in all_tensor_details:
      print("Weight %s:" % tensor_item["name"])
      print(interpreter.tensor(tensor_item["index"])())
    

    这些从 .tflite 文件加载回来的权重值可以与tf.keras.Model.set_weights() 方法一起使用,这将允许您将权重值重新注入到 Python 中的可训练模型的新实例中。显然,这要求您仍然可以访问定义模型架构的代码。

    【讨论】:

      猜你喜欢
      • 2019-04-14
      • 2020-09-10
      • 1970-01-01
      • 2020-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-09
      • 2020-12-03
      相关资源
      最近更新 更多