有没有办法将tensorflow lite(.tflite)文件转换回keras文件(.h5)?

8 tensorflow tensorflow-datasets tensorflow-lite tensorflow2.0

我由于一个粗心的错误而丢失了我的数据集。我手里只剩下 tflite 文件了。有没有办法反转h5文件。我对此进行了很好的研究,但没有找到解决方案。

sca*_*cai 11

从 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"])())
Run Code Online (Sandbox Code Playgroud)

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