访问内部张量并将新节点添加到 tflite 模型?

Access internal tensors and add a new node to a tflite model?

我对 TensorFlow 和 TensorFlow Lite 还很陌生。我遵循了有关如何使用 toco 量化模型并将其转换为定点计算的教程。现在我有一个 tflite 文件,它应该只执行定点操作。我有两个问题

  1. 如何在 python 中测试它?如何访问 tflite 文件中的所有操作和结果?
  2. 有没有办法在这个 tflite 文件中添加新节点或操作?如果有怎么办?

如果有人能指导我,我将不胜感激。

感谢和问候,
阿比纳夫·乔治

Is there a way to add a new node or operation in this tflite file? If so how?

不幸的是,没有,这实际上是一件好事。 TF-Lite 被设计为非常轻便但有效,使用映射文件、平面缓冲区、静态执行计划等来减少内存占用。这样做的代价是您失去了 TensorFlow 的任何灵活性。

TF-Lite 是一个部署框架。但是,早些时候 Google IO,TF 团队提到了在设备上进行训练的可能性,因此将来可能会提供某种灵活性,但现在不会。


How do I test this in python? How do i access all the operations and results in the tflite file?

不能访问所有内部操作,只能访问输入和输出。原因很简单:内部张量不会被保存,因为它们的内存部分也用于其他操作(这就是它的内存占用如此低的原因)。

如果您只想查看输出,可以使用 Python API 如下(代码不言自明):

import pprint
from tensorflow.contrib.lite.python import interpreter as interpreter_wrapper

# Load the model and allocate the static memory plan
interpreter = interpreter_wrapper.Interpreter(model_path='model.tflite')
interpreter.allocate_tensors()

# print out the input details
input_details = interpreter.get_input_details()
print('input_details:')
pp = pprint.PrettyPrinter(indent=2)
pp.pprint(input_details)

# print out the output details
output_details = interpreter.get_output_details()
print('output_details:')
pp = pprint.PrettyPrinter(indent=2)
pp.pprint(output_details)

# set input (img is a `numpy array`)
interpreter.set_tensor(input_details[0]['index'], img)

# forward pass
interpreter.invoke()

# get output of the network
output = interpreter.get_tensor(output_details[0]['index'])

What if I call interpreter.get_tensor for non-input and non-output tensors?

执行相应操作后,您将不会得到该张量中包含的实际数据。如前所述,张量的内存部分与其他张量共享以实现最大效率。