【问题标题】:How to get weights in tflite using c++ api?如何使用 c++ api 在 tflite 中获取权重?
【发布时间】:2020-09-07 19:38:35
【问题描述】:

我在设备上使用 .tflite 模型。最后一层是 ConditionalRandomField 层,我需要该层的权重来进行预测。 如何使用 c++ api 获取权重?

相关:How can I view weights in a .tflite file?

Netron 或 flatc 无法满足我的需求。设备太重了。

似乎 TfLiteNode 将权重存储在 void* user_data 或 void* builtin_data 中。如何阅读它们?

更新:

结论:.tflite 不存储 CRF 权重,而 .h5 剂量。 (也许是因为它们不影响输出。)

我做什么:

// obtain from model.
Interpreter *interpreter;
// get the last index of nodes.
// I'm not sure if the index sequence of nodes is the direction which tensors or layers flows.
const TfLiteNode *node = &((interpreter->node_and_registration(interpreter->nodes_size()-1))->first);

// then follow the answer of @yyoon

【问题讨论】:

  • .tflite 模型中层的权重是固定的,因此通常您不需要在设备运行时读取这些权重。你能解释一下你为什么需要这个吗?
  • @yyoon 在命名实体识别任务中,ConditionalRandomField 层的权重不会影响输出,但会影响最佳路径。没有 CRF
  • 所以我的问题实际上是关于为什么您需要使用 TFLite API“在运行时”读取值。您能否提前从 .tflite 模型中读取权重,然后在您的应用程序中烘焙这些值以进行预测?
  • @yyoon 如果没有 CRF 权重,我只能使用 [max(P(i))] 作为 NER 标签。使用 CRF 权重,维特比算法将应用于输出以获得标签的最佳路径。目前,我在训练时将 CRF 权重与 .​​tflite 一起保存为 .txt。但我认为这是一个不好的做法。 “提前从 .tflite 模型中读取权重”而不是来自训练是我所要求的。
  • 有道理。请在下面查看我的答案。

标签: tensorflow-lite


【解决方案1】:

在 TFLite 节点中,权重应该存储在 inputs 数组中,其中包含对应的 TfLiteTensor* 的索引。

所以,如果你已经获得了最后一层的TfLiteNode*,你可以这样做来读取权重值。

TfLiteContext* context; // You would usually have access to this already.
TfLiteNode* node;       // <obtain this from the graph>;

for (int i = 0; i < node->inputs->size; ++i) {
  TfLiteTensor* input_tensor = GetInput(context, node, i);

  // Determine if this is a weight tensor.
  // Usually the weights will be memory-mapped read-only tensor
  // directly baked in the TFLite model (flatbuffer).
  if (input_tensor->allocation_type == kTfLiteMmapRo) {
    // Read the values from input_tensor, based on its type.
    // For example, if you have float weights,
    const float* weights = GetTensorData<float>(input_tensor);

    // <read the weight values...>
  }
}

【讨论】:

  • 谢谢。 GetTensorData 有效。您对 TfLiteTensor 和 TfLiteNode 的解释使我对 tflite 结构更加清晰。顺便说一句,我想知道你是怎么学会这些的。 TFLITE 文档对诸如“通常权重将是内存映射的只读张量”之类的功能或规则几乎没有提及?
  • 很高兴它有帮助!我所做的是回答(1)我使用netron工具(github.com/lutzroeder/netron)打开了mobilenet_v1模型,并检查了权重在哪里。它们被列在输入中。 (2) 为了确认,我浏览了 conv2D op 实现 (github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/…) 并确认它正在从输入张量中读取权重(过滤器、偏差)并使用 GetTensorData()。
猜你喜欢
  • 2022-01-05
  • 2019-02-06
  • 2021-11-15
  • 1970-01-01
  • 1970-01-01
  • 2017-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多