首页 > 解决方案 > 用于实时识别的 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 的方式。请你帮助我好吗?

这个问题花了很多时间,直到现在还没有弄清楚。提前致谢。

标签: pythontensorflowraspberry-pireal-timetensorflow-lite

解决方案


您可以通过执行以下操作来调整输入张量的大小:

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 是一个资源非常有限的环境。它可能需要进一步优化才能实时运行(同样,取决于您如何构建模型和使用它)。

推荐阅读