我正在尝试将我们的 Tensoflow 模型从 Python+Keras 版本迁移到嵌入式平台上使用 C++ 的 Tensorflow Lite。
看来我不知道如何正确设置解释器的输入。
输入形状应为 (1, 224, 224, 3)。
作为输入,我使用 openCV 拍摄图像,并将其转换为 CV_BGR2RGB。
std::unique_ptr<tflite::FlatBufferModel> model_stage1 =
tflite::FlatBufferModel::BuildFromFile("model1.tflite");
TFLITE_MINIMAL_CHECK(model_stage1 != nullptr);
// Build the interpreter
tflite::ops::builtin::BuiltinOpResolver resolver_stage1;
std::unique_ptr<Interpreter> interpreter_stage1;
tflite::InterpreterBuilder(*model_stage1, resolver_stage1)(&interpreter_stage1);
TFLITE_MINIMAL_CHECK(interpreter_stage1 != nullptr);
cv::Mat cvimg = cv::imread(imagefile);
if(cvimg.data == NULL) {
printf("=== IMAGE READ ERROR ===\n");
return 0;
}
cv::cvtColor(cvimg, cvimg, CV_BGR2RGB);
uchar* input_1 = interpreter_stage1->typed_input_tensor<uchar>(0);
memcpy( ... );
Run Code Online (Sandbox Code Playgroud)
我对这种 uchar 类型的 memcpy 正确设置有疑问。
当我这样做时,我在工作过程中出现段错误:
memcpy(input_1, cvimg.data, cvimg.total() * cvimg.elemSize());
Run Code Online (Sandbox Code Playgroud)
在这种情况下我应该如何正确填写输入?
我正在使用 MLKiT 加载自定义 tensoflow 模型在读取模型时出现以下错误
java.lang.IllegalArgumentException:无法在类型为 UINT8 的 TensorFlowLite 张量和类型为 [[[[F 的 Java 对象(与 TensorFlowLite 类型 FLOAT32 兼容)之间进行转换。
我正在使用以下代码使用 tlflite 文件进行对象检测
private fun bitmapToInputArray(bitmap: Bitmap): Array<Array<Array<FloatArray>>> {
var bitmap = bitmap
bitmap = Bitmap.createScaledBitmap(bitmap, 224, 224, true)
val batchNum = 0
val input = Array(1) { Array(224) { Array(224) { FloatArray(3) } } }
for (x in 0..223) {
for (y in 0..223) {
val pixel = bitmap.getPixel(x, y)
// Normalize channel values to [-1.0, 1.0]. This requirement varies by …Run Code Online (Sandbox Code Playgroud) 为了能够运行TensorFlow支持本机TensorFlow操作的精简模型,libtensorflow-lite必须重新编译静态库。C++可以在此处找到执行此操作的说明。
它指出
使用 bazel 管道构建 TensorFlow Lite 库时,可以包含和启用额外的 TensorFlow ops 库,如下所示:
如有必要,通过添加 --config=monolithic 构建标志来启用单体构建。
将 TensorFlow ops 委托库依赖添加到构建依赖中:tensorflow/lite/delegates/flex:delegate。
请注意,只要委托链接到客户端库,在运行时创建解释器时将自动安装必要的 TfLiteDelegate。没有必要像其他委托类型通常需要的那样显式安装委托实例。
问题是构建静态库的标准方法是通过 shell 脚本/make(请参阅此处的文档;这是用于arm64,但也有脚本可用于x86_64)。我没有明显的方法可以tensorflow-lite通过bazel那里的构建命令进行构建和修改。
有没有人在尝试构建arm64/x86_64架构模型时成功构建了这个并且可以分享这个?我是新手,bazel找不到详细的演练。
编辑
在@jdehesa 提出的故障排除步骤之后,我能够构建libtensorflowlite.so,但遇到了另一个问题。我的应用程序构建成功,但在执行应用程序时,.so找不到该文件:
./myapp: error while loading shared libraries: libtensorflowlite.so: cannot open shared object file: No such file or directory
Run Code Online (Sandbox Code Playgroud)
由于其他.so文件位于可以找到的同一目录中,因此路径是正确的。此外,如果使用静态库,该应用程序也能正常工作。
为了重现该问题,我使用了tensorflow/tensorflow:devel-gpu-py3docker 构建映像(此处提供了 …
我在玩 tflite 并在我的多核 CPU 上观察到在推理期间它没有受到很大的压力。我通过预先用 numpy 创建随机输入数据(类似于图像的随机矩阵)消除了 IO 瓶颈,但随后 tflite 仍然没有充分利用 CPU 的潜力。
该文档提到了调整使用线程数的可能性。但是我无法在 Python API 中找到如何做到这一点。但是因为我看到人们为不同的模型使用多个解释器实例,所以我认为一个人可能会使用同一模型的多个实例并在不同的线程/进程上运行它们。我编写了以下简短脚本:
import numpy as np
import os, time
import tflite_runtime.interpreter as tflite
from multiprocessing import Pool
# global, but for each process the module is loaded, so only one global var per process
interpreter = None
input_details = None
output_details = None
def init_interpreter(model_path):
global interpreter
global input_details
global output_details
interpreter = tflite.Interpreter(model_path=model_path)
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
interpreter.allocate_tensors()
print('done init') …Run Code Online (Sandbox Code Playgroud) python parallel-processing multiprocessing tensorflow tensorflow-lite
我正在尝试使用谷歌的示例,但使用我自己的数据集:
我创建了一个类似于代码中下载的文件夹,其中包含训练和测试文件夹以及 txt 文件。
就我而言,data_path 如下:
data_path = '/Users/developer/.keras/datasets/chat'
每当我尝试运行时,它model = text_classifier.create(train_data)都会抛出错误,
ValueError: When passing an infinitely repeating dataset, you must specify the `steps_per_epoch` argument.
这是什么意思以及我应该在哪里寻找问题?
import numpy as np
import os
import tensorflow as tf
assert tf.__version__.startswith('2')
from tensorflow_examples.lite.model_customization.core.data_util.text_dataloader import TextClassifierDataLoader
from tensorflow_examples.lite.model_customization.core.model_export_format import ModelExportFormat
import tensorflow_examples.lite.model_customization.core.task.text_classifier as text_classifier
# data_path = tf.keras.utils.get_file(
# fname='aclImdb',
# origin='http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz',
# untar=True)
data_path = '/Users/developer/.keras/datasets/chat'
train_data = TextClassifierDataLoader.from_folder(os.path.join(data_path, 'train'), class_labels=['greeting', 'goodbye'])
test_data = TextClassifierDataLoader.from_folder(os.path.join(data_path, 'test'), shuffle=False)
model = text_classifier.create(train_data) …Run Code Online (Sandbox Code Playgroud) python tensorflow tensorflow-datasets tensorflow-lite tensorflow2.0
好的,所以在我的应用程序中,我尝试使用人脸网络模型实现人脸识别,该模型转换为 tflite 平均约为 93 MB,但是该模型最终会增加我的 apk 的大小。所以我正在努力寻找替代方法来处理这个问题
首先我能想到的是以某种方式压缩它,然后在安装应用程序时解压缩
另一种方法是我应该将该模型上传到服务器,并在下载后将其加载到我的应用程序中。但是我似乎不知道如何实现这一点:
默认情况下,face net 允许从 assets 文件夹中实现
var facenet = FaceNet(getAssets());
Run Code Online (Sandbox Code Playgroud)
但是,如果我正在下载该模型,如何将其加载到我的应用程序中?
这是我的脸网初始化代码:
public FaceNet(AssetManager assetManager) throws IOException {
tfliteModel = loadModelFile(assetManager);
tflite = new Interpreter(tfliteModel, tfliteOptions);
imgData = ByteBuffer.allocateDirect(
BATCH_SIZE
* IMAGE_HEIGHT
* IMAGE_WIDTH
* NUM_CHANNELS
* NUM_BYTES_PER_CHANNEL);
imgData.order(ByteOrder.nativeOrder());
}
private MappedByteBuffer loadModelFile(AssetManager assetManager) throws IOException {
AssetFileDescriptor fileDescriptor = assetManager.openFd(MODEL_PATH);
FileInputStream inputStream = new FileInputStream(fileDescriptor.getFileDescriptor());
FileChannel fileChannel = inputStream.getChannel();
long startOffset = fileDescriptor.getStartOffset();
long declaredLength = fileDescriptor.getDeclaredLength();
return fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength); …Run Code Online (Sandbox Code Playgroud) 我正在尝试 tflite C++ API 来运行我构建的模型。我通过以下代码片段将模型转换为 tflite 格式:
import tensorflow as tf
converter = tf.lite.TFLiteConverter.from_keras_model_file('model.h5')
tfmodel = converter.convert()
open("model.tflite", "wb").write(tfmodel)
Run Code Online (Sandbox Code Playgroud)
我正在按照tflite 官方指南中提供的步骤进行操作,到目前为止我的代码如下所示
// Load the model
std::unique_ptr<tflite::FlatBufferModel> model = tflite::FlatBufferModel::BuildFromFile("model.tflite");
// Build the interpreter
tflite::ops::builtin::BuiltinOpResolver resolver;
std::unique_ptr<tflite::Interpreter> interpreter;
tflite::InterpreterBuilder builder(*model, resolver);
builder(&interpreter);
interpreter->AllocateTensors();
// Check interpreter state
tflite::PrintInterpreterState(_interpreter.get());
Run Code Online (Sandbox Code Playgroud)
这表明我的输入层的形状为 (1, 2050, 6)。为了从 C++ 提供输入,我遵循了这个线程,我的输入代码如下所示:
std::vector<std::vector<double>> tensor; // I filled this vector, (dims are 2050, 6)
int input = interpreter->inputs()[0];
float* input_data_ptr = interpreter->typed_input_tensor<float>(input);
for (int i = 0; …Run Code Online (Sandbox Code Playgroud) 所以,我有这个项目,我必须:
前两点进展顺利,但最后一点让我陷入困境。我可以得到一个输出(一个 3D 张量 - 形状:[1][128][98]),但我不知道如何解码它。
我有两个主要问题:
我试图用原始网络(--image 选项)推断相同的图像,结果没问题,所以我想也许我在加载 tflite 模型或图像时犯了一些错误。我还认为,也许我必须执行光束(或贪婪)搜索,而不仅仅是寻找更高的价值。
所以我的问题是,输出真的是一个有概率的张量还是我遗漏了什么?如何以正确的方式解码输出?
TFlite 转换:
import tensorflow as tf
import numpy as np
from tensorflow import keras
import tensorflow.keras.models as models
import …Run Code Online (Sandbox Code Playgroud) 我有 Apple M1 Pro 芯片,但无法运行我的张量流项目。我按照Apple 网站上的安装说明进行操作。
当我运行时pip install -r requirements.txt,我的所有 python 软件包都会安装,除了tflite-model-maker. 我收到以下错误:
ERROR: Cannot install -r requirements.txt (line 19) and tflite-support because these package versions have conflicting dependencies.
The conflict is caused by:
tflite-model-maker 0.3.4 depends on tensorflow>=2.6.0
tflite-model-maker 0.3.3 depends on tensorflow>=2.6.0
tflite-model-maker 0.3.2 depends on tensorflow>=2.4.0
tflite-model-maker 0.3.1 depends on tensorflow>=2.4.0
tflite-model-maker 0.3.0 depends on tensorflow>=2.4.0
tflite-model-maker 0.2.5 depends on tensorflow>=2.4.0
The user requested tflite-support
tflite-model-maker 0.2.4 depends on tflite-support==0.1.0rc4
tflite-model-maker …Run Code Online (Sandbox Code Playgroud) 我有 2 个 tflite 模型作为 s3 对象托管在 aws 上。在我的反应打字稿应用程序中,如果浏览器在移动设备上打开,我将尝试加载这些模型。否则,网络应用程序将使用其他更高效的模型。

我已经配置了 s3 存储桶,因此我可以通过更改 CORS 配置从该 Web 应用程序访问它。这样可行。如果我转到网络选项卡,我会看到模型的获取:
使用 Chrome,我可以从移动显示更改为桌面显示。桌面显示不会产生任何错误。但是,手机给我带来了我不明白的错误。
忽略GET错误和console.log date_created。它们来自我的代码的另一部分,与此无关。
我搜索了各种资源来将 tflite 部署到网络应用程序,但没有找到任何有用的东西。
- - - - - - - - - 编辑 - - - - - - - - - -
我尝试过使用这篇 github 帖子中讨论的方法

但只得到以下错误(可以忽略GET错误和isMobile console.log):
machine-learning typescript reactjs tensorflow tensorflow-lite
tensorflow-lite ×10
tensorflow ×7
python ×4
android ×3
c++ ×2
kotlin ×2
apple-m1 ×1
assets ×1
bazel ×1
java ×1
pip ×1
reactjs ×1
tensor ×1
typescript ×1