You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Arduino Nano BLE 33上打印TensorFlow Lite输入张量内容?

Arduino Nano BLE 33 TFLite模型推理结果异常排查

问题概述

在Arduino Nano BLE 33板上运行TensorFlow Lite模型,输入为两个超声波传感器(Channel 1、Channel 2)的5000组距离样本,用于检测物体位置。但无论是否存在物体,推理结果始终返回“测试区域左侧有物体(准确率100%)”。硬编码测试数据后结果仍未改变,怀疑数据加载方式错误,需要打印输入张量内容排查。

当前数据加载代码:

tflInputTensor->data.f[samplesRead*2+0] = channel1;
tflInputTensor->data.f[samplesRead*2+1] = channel2;

核心测试代码:

const int numSamples = 5000;
int samplesRead = numSamples;
void loop() 
{
  float durationCh1, durationCh2;

  while(samplesRead ==  numSamples) 
  {
    samplesRead = 0;
    break;
  }
  // for(i=0; i<5000; i++)  
  while(samplesRead < numSamples)
  {  

    tflInputTensor->data.f[samplesRead*2+0] = 4512.00;
    tflInputTensor->data.f[samplesRead*2+1] = 4428.00;

    samplesRead++;    
    Serial.println(samplesRead);

    if(samplesRead == numSamples)
    { 
 
      TfLiteStatus invokeStatus = tflInterpreter->Invoke();
      Serial.println("Invoke");      
      if (invokeStatus != kTfLiteOk) 
      {
        Serial.println("Invoke failed!");
        while (1);
        return;
      }

      // Loop through the output tensor values from the model
      for (int i = 0; i < NUM_LOC; i++) 
      {
        Serial.print(GRIDS[i]);
        Serial.print(": ");
        Serial.println(tflOutputTensor->data.f[i],9); // The int here gives the decimal places
      }
      Serial.println();
      delay(2000);
    }
  }
}

排查方案

1. 打印输入张量验证数据加载

在调用Invoke()前添加代码,打印输入张量的部分或全部数据,确认数据是否正确写入:

if(samplesRead == numSamples)
{ 
  // 打印前10组数据(避免串口输出过载)
  Serial.println("Input Tensor Data (first 10 pairs):");
  for(int i=0; i<10; i++){
    Serial.print("Sample ");
    Serial.print(i);
    Serial.print(": Ch1=");
    Serial.print(tflInputTensor->data.f[i*2]);
    Serial.print(", Ch2=");
    Serial.println(tflInputTensor->data.f[i*2+1]);
  }
  Serial.println("---");

  TfLiteStatus invokeStatus = tflInterpreter->Invoke();
  // 后续代码不变...
}

若需打印全部5000组数据,建议分批输出(如每100组打印一次),或使用串口助手日志保存功能,避免缓冲区溢出。

2. 确认输入张量形状与模型匹配

检查模型输入张量的维度是否和代码加载逻辑一致,比如是否为[1, 10000](5000样本×2通道的一维平铺)或[1, 5000, 2](样本数×通道数的二维格式)。可在setup()中添加以下代码打印形状信息:

Serial.println("Input Tensor Shape:");
TfLiteIntArray* inputShape = tflInputTensor->dims;
for(int i=0; i<inputShape->size; i++){
  Serial.print(inputShape->data[i]);
  Serial.print(" ");
}
Serial.println();

如果模型训练时的输入格式与当前加载逻辑不匹配,会导致数据读取顺序错误,进而输出异常结果。

3. 检查数据预处理一致性

确认推理时的数据预处理(如归一化、标准化)是否与模型训练时完全一致。若训练时对传感器数据做了缩放处理,推理时未同步执行,会导致输入数据分布异常,引发错误输出。

4. 重置输入张量(可选)

每次推理前清空输入张量内存,避免旧数据残留影响结果:

// 在samplesRead = 0;之后添加
memset(tflInputTensor->data.f, 0, sizeof(float) * numSamples * 2);

内容的提问来源于stack exchange,提问作者ofithch79

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 22:47:49