如何使用预训练的TensorFlow Lite模型进行输入解释

我正在使用一个预训练的TensorFlow Lite模型,通过我创建的一个简短程序来获取一些样本输出:

import cv2 as cvimport numpy as npimport osimport tensorflow as tfimport numpy as npdef decode_img(img):  # 将压缩字符串转换为3D uint8张量  img = tf.image.decode_jpeg(img, channels=3)  # 使用`convert_image_dtype`将图像转换为[0,1]范围内的浮点数  img = tf.image.convert_image_dtype(img, tf.float32)  # 调整图像大小到所需尺寸  return tf.reshape(tf.image.resize(img, [257, 257]), [1, 257, 257, 3])model = tf.lite.Interpreter('models\posenet_mobilenet_v1_100_257x257_multi_kpt_stripped.tflite')input_details = model.get_input_details()output_details = model.get_output_details()img = tf.io.read_file('photos\standing\\1.jpg')input_data = decode_img(img)print('input shape: {}'.format(input_data.shape))model.set_tensor(input_details[0]['index'], input_data)model.invoke()output_data = model.get_tensor(output_details[0]['index'])print('output: {}'.format(output_data))

在控制台打印输入形状后,程序没有进一步的操作就结束了。原本应该打印输出的那行代码从未执行。

输出:

C:\python imagetest.py INFO: 已初始化TensorFlow Lite运行时。 2020-01-21 08:07:32.567619: I tensorflow/core/platform/cpu_feature_guard.cc:145] 此TensorFlow二进制文件已使用Intel(R) MKL-DNN进行优化,以在性能关键操作中使用以下CPU指令:AVX AVX2 要在非MKL-DNN操作中启用它们,请使用适当的编译器标志重新构建TensorFlow。 2020-01-21 08:07:32.578283: I tensorflow/core/common_runtime/process_util.cc:115] 使用默认的inter op设置创建新线程池:8。 使用inter_op_parallelism_threads调整以获得最佳性能。 input shape: (1, 257, 257, 3)

使用Interpreter类正确使用预训练的TFLite模型的方法是什么?


回答:

通过以下代码成功使其工作:

img = cv.imread('photos\standing\\3.jpg')img = tf.reshape(tf.image.resize(img, [257,257]), [1,257,257,3])model = tf.lite.Interpreter('models\posenet_mobilenet_v1_100_257x257_multi_kpt_stripped.tflite')model.allocate_tensors()input_details = model.get_input_details()output_details = model.get_output_details()floating_model = input_details[0]['dtype'] == np.float32if floating_model:    img = (np.float32(img) - 127.5) / 127.5model.set_tensor(input_details[0]['index'], img)model.invoke()output_data =  model.get_tensor(output_details[0]['index'])offset_data = model.get_tensor(output_details[1]['index'])

我注意到的唯一区别是初始调用了allocate_tensors()

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注