标签: tensorflow-lite

TF Lite的Toco转换器args用于量化感知训练的描述

这些天来,我一直在努力寻找有关在TPU支持下部署TF模型的错误。

我可以在不运行TPU支持的情况下获得模型,但是一旦启用量化功能,我就会迷路。

我处于以下情况:

  1. 创建模型并对其进行训练
  2. 创建模型的评估图
  3. 冻结模型并将结果保存为协议缓冲区
  4. 在没有TPU支持的情况下成功转换并部署了它

最后一点,我使用了TFLiteConverter的Python API。生成功能性tflite模型的脚本是

import tensorflow as tf

graph_def_file = 'frozen_model.pb'
inputs = ['dense_input']
outputs = ['dense/BiasAdd']

converter = tf.lite.TFLiteConverter.from_frozen_graph(graph_def_file, inputs, outputs)
converter.inference_type = tf.lite.constants.FLOAT
input_arrays = converter.get_input_arrays()

converter.optimizations = [tf.lite.Optimize.OPTIMIZE_FOR_SIZE]

tflite_model = converter.convert()

open('model.tflite', 'wb').write(tflite_model)
Run Code Online (Sandbox Code Playgroud)

这告诉我,到目前为止我的方法似乎还可以。现在,如果我想使用Coral TPU棒,就必须对我的模型进行量化(在训练过程中考虑了这一点)。我要做的就是修改转换器脚本。我认为我必须将其更改为

import tensorflow as tf

graph_def_file = 'frozen_model.pb'
inputs = ['dense_input']
outputs = ['dense/BiasAdd']

converter = tf.lite.TFLiteConverter.from_frozen_graph(graph_def_file, inputs, outputs)
converter.inference_type = tf.lite.constants.QUANTIZED_UINT8      ## Indicates TPU compatibility
input_arrays = converter.get_input_arrays()

converter.quantized_input_stats = {input_arrays[0]: (0., 1.)}     ## mean, std_dev
converter.default_ranges_stats …
Run Code Online (Sandbox Code Playgroud)

python python-3.x tensorflow tensorflow-lite

24
推荐指数
1
解决办法
368
查看次数

(-5:错误参数)在函数“矩形”中 - 无法解析“pt1”。索引为 0 的序列项类型错误

当我检测到我的 tflite 文件时,问题发生了。

我写的命令。

python detect.py --weights ./checkpoints/yolov4-tiny-tf.tflite --size 416 --model yolov4 --image D:\yolov4\training\tensorflow-yolov4-tflite-master\data\rice.jpg --framework tflite --tiny true
Run Code Online (Sandbox Code Playgroud)

以及错误的信息:

cv2.rectangle(image, c1, c2, bbox_color, bbox_thick)
cv2.error: OpenCV(4.5.2) :-1: error: (-5:Bad argument) in function 'rectangle'
> Overload resolution failed:
>  - Can't parse 'pt1'. Sequence item with index 0 has a wrong type
>  - Can't parse 'pt1'. Sequence item with index 0 has a wrong type
>  - Can't parse 'rec'. Expected sequence length 4, got 2
>  - Can't parse …
Run Code Online (Sandbox Code Playgroud)

python opencv tensorflow-lite yolov4

20
推荐指数
1
解决办法
10万
查看次数

如何测试.tflite模型以证明其行为与使用相同测试数据的原始模型相同?

我已经根据训练过的模型生成了一个.tflite模型,我想测试一下tfilte模型给出与原始模型相同的结果.

给出相同的测试数据并获得相同的结果.

python tensorflow tensorflow-lite

18
推荐指数
1
解决办法
8500
查看次数

tensorflow lite模型与python模型相比给出了非常不同的准确度值

我正在使用tensorflow 1.10 Python 3.6

我的代码基于TensorFlow提供的预制虹膜分类模型.这意味着,我使用的是Tensorflow DNN预制分类器,具有以下区别:

  • 10个功能代替4.
  • 5个班而不是3个.

测试和培训文件可以从以下链接下载:https: //www.dropbox.com/sh/nmu8i2i8xe6hvfq/AADQEOIHH8e-kUHQf8zmmDMDa?dl=0

我已经制作了一个代码来将这个分类器导出为tflite格式,但是python模型的精度高于75%但是在导出时精度会降低大约45%,这意味着大约30%的精度会丢失(这太多了) .我已经尝试了使用不同数据集的代码,并且在所有这些代码中导出后的准确性降低了很多!这让我觉得TocoConverter函数出了问题,或者我输出错误,缺少参数或类似的东西.

这是我生成模型的方式:

classifier = tf.estimator.DNNClassifier(
        feature_columns=my_feature_columns,
        hidden_units=[100, 500],
        optimizer=tf.train.AdagradOptimizer(learning_rate=0.003),
        n_classes=num_labels,
        model_dir="myModel")
Run Code Online (Sandbox Code Playgroud)

这是我用来转换为tflite的功能:

converter = tf.contrib.lite.TocoConverter.from_frozen_graph(final_model_path, input_arrays, output_arrays, input_shapes={"dnn/input_from_feature_columns/input_layer/concat": [1, 10]})
        tflite_model = converter.convert()
Run Code Online (Sandbox Code Playgroud)

我分享了完整的代码,我还计算了生成的.tflite文件的准确性.

import argparse
import tensorflow as tf

import pandas as pd
import csv

from tensorflow.python.tools import freeze_graph
from tensorflow.python.tools import optimize_for_inference_lib
import numpy as np


parser = argparse.ArgumentParser()
parser.add_argument('--batch_size', default=100, type=int, help='batch size')
parser.add_argument('--train_steps', default=1000, type=int,
                    help='number of training steps')

features_global = …
Run Code Online (Sandbox Code Playgroud)

python python-3.x tensorflow tensorflow-lite

16
推荐指数
1
解决办法
1112
查看次数

Android 访问被拒绝查找属性“ro.hardware.chipname”

所以我尝试在 Android 应用程序上使用 Tensorflow Lite。相机拍摄图像时调用以下代码:

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        val bitmap = data!!.extras!!.get("data") as Bitmap
        val tensorImage = imageProcessor.process(TensorImage(DataType.UINT8).apply { load(bitmap) })
        val outputs = model.process(tensorImage.tensorBuffer)
        val buffer = outputs.outputFeature0AsTensorBuffer
        val prediction = buffer.floatArray
        debug { "$prediction" }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,执行该行后val outputs = model.process(tensorImage.tensorBuffer),出现错误消息

E/libc: Access denied finding property "ro.hardware.chipname"

弹出。我不知道该消息的含义(即使在谷歌搜索之后),而且我似乎找不到合适的权限来允许这样做。非常感谢任何提前的帮助。

android kotlin tensorflow-lite

14
推荐指数
1
解决办法
4337
查看次数

用于推理的 TensorFlow Lite C++ API 示例

我正在尝试让 TensorFlow Lite 示例在配备 ARM Cortex-A72 处理器的机器上运行。不幸的是,由于缺少有关如何使用 C++ API 的示例,我无法部署测试模型。我将尝试解释到目前为止我所取得的成就。

创建 tflite 模型

我创建了一个简单的线性回归模型并对其进行了转换,它应该近似于函数f(x) = 2x - 1。我从一些教程中得到了这个代码片段,但我再也找不到了。

import tensorflow as tf
import numpy as np
from tensorflow import keras
from tensorflow.contrib import lite

model = keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])])
model.compile(optimizer='sgd', loss='mean_squared_error')

xs = np.array([ -1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float)
ys = np.array([ -3.0, -1.0, 1.0, 3.0, 5.0, 7.0], dtype=float)

model.fit(xs, ys, epochs=500)

print(model.predict([10.0]))

keras_file = 'linear.h5'
keras.models.save_model(model, keras_file)

converter = lite.TocoConverter.from_keras_model_file(keras_file)
tflite_model = converter.convert()
open('linear.tflite', 'wb').write(tflite_model)
Run Code Online (Sandbox Code Playgroud)

这将创建一个名为 …

c++ inference tensorflow tensorflow-lite

12
推荐指数
2
解决办法
1万
查看次数

如何修复“在解释器中至少有 1 个以 numpy 数组或切片的形式引用内部数据”并在 tf.lite 上运行推理

我正在尝试在 mnist keras 模型上使用 tf.lite 运行推理,我通过根据进行训练后量化进行了优化

RuntimeError: There is at least 1 reference to internal data
in the interpreter in the form of a numpy array or slice. Be sure to
only hold the function returned from tensor() if you are using raw
data access.
Run Code Online (Sandbox Code Playgroud)

它发生在我将图像调整为 4 维或解释器本身(如注释行所示)之后;因为在此之前的错误类似于“预期 4 个维度,但发现 3 个”。这是代码:

import tensorflow as tf
tf.enable_eager_execution()
import numpy as np
from tensorflow.keras.datasets import mnist
import matplotlib.pyplot as plt
%matplotlib inline

mnist_train, mnist_test = tf.keras.datasets.mnist.load_data()
images, labels = …
Run Code Online (Sandbox Code Playgroud)

python-3.x tensorflow tensorflow-lite

11
推荐指数
1
解决办法
4128
查看次数

为 TFliteconverter 创建代表性数据集的正确方法是什么?

我试图推断tinyYOLO-V2INT8重量和激活。我可以使用 TFliteConverter 将权重转换为 INT8。对于INT8激活,我必须给出代表性数据集来估计缩放因子。我创建此类数据集的方法似乎是错误的。

正确的程序是什么?

def rep_data_gen():
    a = []
    for i in range(160):
        inst = anns[i]
        file_name = inst['filename']
        img = cv2.imread(img_dir + file_name)
        img = cv2.resize(img, (NORM_H, NORM_W))
        img = img / 255.0
        img = img.astype('float32')
        a.append(img)
    a = np.array(a)
    print(a.shape) # a is np array of 160 3D images
    img = tf.data.Dataset.from_tensor_slices(a).batch(1)
    for i in img.take(BATCH_SIZE):
        print(i)
        yield [i]
# https://www.tensorflow.org/lite/performance/post_training_quantization
converter = tf.lite.TFLiteConverter.from_keras_model_file("./yolo.h5")
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.target_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter.inference_input_type …
Run Code Online (Sandbox Code Playgroud)

dataset tensorflow tensorflow-lite

11
推荐指数
1
解决办法
5240
查看次数

是否有使用 TF Lite 的有关 OCR 的示例/演示?

我看到 OCR 在 TFDevSummit2019 的 TFLite 使用列表中。是否有使用 TF Lite 的有关 OCR 的示例/演示?

描述:我想基于deeplearning训练一个足够小的OCR模型,转换成tflite格式,然后部署到手机上。我工作了几天,仍然无法获得 tflite 格式的 OCR 模型。

(“图片”部分的OCR,希望得到一些解决方案~~) TFDevSummit2019

ocr mobile tensorflow-lite

10
推荐指数
0
解决办法
831
查看次数

如何在 C++ 项目中使用 TF Lite 库

在过去的 1-2 天里,我一直在为如何构建 TensorFlow Lite 而苦苦挣扎,以便我可以在我自己的 C\C++ 项目中将其用作标头或库。

例如,我有一个带有 main.cpp 的 C++ 项目,代码如下:

#include "tensorflow/lite/model.h"
#include "tensorflow/lite/interpreter.h"
#include "tensorflow/lite/kernels/register.h"

int main()
{
    std::unique_ptr<tflite::FlatBufferModel> model;
    model = tflite::FlatBufferModel::BuildFromBuffer(h5_converted_tflite, h5_converted_tflite_len);

    tflite::ops::builtin::BuiltinOpResolver resolver;
    std::unique_ptr<tflite::Interpreter> interpreter;
    tflite::InterpreterBuilder(*model, resolver)(&interpreter);

    // Resize input tensors, if desired.
    interpreter->AllocateTensors();

    float* input = interpreter->typed_input_tensor<float>(0);
    // Fill `input`.

    interpreter->Invoke();

    float* output = interpreter->typed_output_tensor<float>(0);
}
Run Code Online (Sandbox Code Playgroud)

我应该从哪里下载\构建什么,以便我可以成功编译此代码?目前它显然说找不到 h 文件,当我克隆 TF 存储库并将其添加到包含文件夹时,它没有找到“flatbuffers.h”文件,当我手动添加它时,它给出我有很多链接错误。任何帮助将不胜感激在这里...

提前致谢

c++ tensorflow tensorflow-lite

10
推荐指数
1
解决办法
4218
查看次数