python - 用于实时识别的 TensorFlow Lite 推理
问题描述
我有一个使用三轴加速度计识别活动日常生活和跌倒的项目。我已经训练了 LSTM 模型并获得了很高的准确性。我即将完成它,但目前我正面临推理阶段的问题。
我决定将模型转换为 TensorFlow lite 以便将其加载到我的 Raspberry Pi 中,并且我已经成功地做到了。
现在我想在已经连接到我的 Raspberry Pi 的加速度计传感器上对训练后的模型进行实时识别。
我知道 RNN/LSTM 需要 (Time_steps, Features) 并且在我的情况下是 (200,3)。而且我知道我还必须让加速度计在 200 个样本窗口中读取样本(对吗?)。
到目前为止,我已经编写了完成此任务的代码:
def get_sample():
sample_list = []
sample_count = 0
total=[0,0,0]
last_time = time.time_ns() / 1000000000
while sample_count < 200/3:
if time.time() - last_time >= 0.01:
adxl345 = ADXL345()
axes = adxl345.getAxes(True)
total[0] += axes['x']
total[1] += axes['y']
total[2] += axes['z']
sample = list(total)
sample_list += [
(sample[0] + 9.80665) / (9.80665 * 2),
(sample[1] + 9.80665) / (9.80665 * 2),
(sample[2] + 9.80665) / (9.80665 * 2)]
last_time = time.time_ns() / 1000000000
sample_count += 1
time.sleep(0.001)
sample_list.pop()
return sample_list
当我运行以下代码时:
interpreter = tflite.Interpreter(model_path=model_file)
interpreter.allocate_tensors()
# Get input and output tensors.
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
sample_list = np.array(np.asarray(np.asarray(sample_list, dtype=np.float32)))
interpreter.set_tensor(input_details[0]['index'], [[sample_list]])
interpreter.invoke()
我知道有问题!也许以我理解推理或 LSTM 的方式。请你帮助我好吗?
这个问题花了很多时间,直到现在还没有弄清楚。提前致谢。
解决方案
您可以通过执行以下操作来调整输入张量的大小:
input_details = interpreter.get_input_details()
interpreter.resize_tensor_input(input_details[0]["index"], input.shape)
interpreter.allocate_tensors()
interpreter.set_tensor(input_details[0]['index'], input)
我认为您可能会遇到其他问题的提示:
- 如果没有看到生成 LSTM 模型的代码,很难预测它是否会起作用。
- Raspberry Pi 是一个资源非常有限的环境。它可能需要进一步优化才能实时运行(同样,取决于您如何构建模型和使用它)。
推荐阅读
- javascript - 错误:收到未知参数:来源
- node.js - Firebase (GCP) 云函数在本地运行 (nodejs 8) 有 EMPTY 请求查询
- git - 如何通过 .gitattributes 覆盖子目录中的行尾以无扩展名+指定扩展名?
- testing - 是否可以在 testcafe E2E 测试中取消初始化/重新初始化/删除角色?
- javascript - 无法从 node_modules 动态加载脚本
- r - 使用 ggplot geom_tile 绘图为空
- parallel-processing - 是否可以在多个 Gnu Parallel 进程之间共享一个昂贵的对象?
- x86 - 不同的进程可以同时运行 RDTSC 吗?
- rest - 设计一个rest api,它的查询参数大于某个值
- maps - 删除地图检查和加载