有什么方法可以将.tflite文件转换回keas(h5)?

问题描述 投票:0回答:1

我因粗心的错误而丢失了数据集。我只剩下我的tflite文件。是否有任何解决方案可以将h5文件回退。我已经对此进行了不错的研究,但没有找到解决方案。

tensorflow tensorflow2.0 tensorflow-datasets tensorflow-lite tf-lite
1个回答
0
投票

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

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

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

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_layers_details = interpreter.get_tensor_details()
interpreter.allocate_tensors()

for layer in all_layers_details:
  print("Weight %s:" % layer["name"])
  print(interpreter.tensor(layer["index"])())

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

© www.soinside.com 2019 - 2024. All rights reserved.