如何在 Android 中执行张量流模型的推理

How to execute inference of tensorflow model in Android

我试过使用 Tensorflow Lite,但它有很多限制,它没有批量归一化操作,即使使用简单的操作,它也会对使用 Keras 测试的相同数据给出非常奇怪的结果。这意味着使用 keras 一切正常,使用 tensorflow lite,结果是完全错误的。所以我需要一些东西来在 Android.

上执行 .pb 文件

您可以使用 TensorFlowInferenceInterface 通过 .pb 文件进行预测。首先,将 .pb 文件放在您应用的资产文件夹中。

  1. 在您的 build.gradle(Module: app) 文件中,添加以下依赖项, implementation 'org.tensorflow:tensorflow-android:1.11.0'
  2. 然后初始化TensorFlowInferenceInterface,如果你的模型文件名是"model.pb"那么, TensorFlowInferenceInterface tensorFlowInferenceInterface = new TensorFlowInferenceInterface(context.getAssets() , "file:///android_asset/model.pb") ;
  3. tensorFlowInferenceInterface.feed( INPUT_NAME , inputs , 1, 28, 28); 其中 INPUT_NAME 是输入层的名称。 1 , 50 是输入维度。

  4. tensorFlowInferenceInterface.run( new String[]{ OUTPUT_NAME } ); 其中 OUTPUT_NAME 是输出层的名称。

  5. float[] outputs = new float[ nuymber_of_classes ]; tensorFlowInferenceInterface.fetch( OUTPUT_NAME , outputs ) ;

outputs 是根据您的模型预测的浮点值。

完整代码如下:

TensorFlowInferenceInterface tensorFlowInferenceInterface = new 
TensorFlowInferenceInterface(context.getAssets() , "file:///android_asset/model.pb");
tensorFlowInferenceInterface.feed( INPUT_NAME , inputs , 1, 28, 28);
tensorFlowInferenceInterface.run( new String[]{ OUTPUT_NAME } );
float[] outputs = new float[ nuymber_of_classes ];
tensorFlowInferenceInterface.fetch( OUTPUT_NAME , outputs ) ;