【问题标题】:How to execute inference of tensorflow model in Android如何在Android中执行张量流模型的推理
【发布时间】:2018-10-01 03:57:04
【问题描述】:
我尝试使用 Tensorflow Lite,但它有很多限制,它没有批量标准化操作,即使是简单的操作,它也会给使用 Keras 测试的相同数据带来非常奇怪的结果。这意味着使用 keras 一切正常,使用 tensorflow lite,结果是完全错误的。所以我需要一些东西来在 Android 上执行 .pb 文件。
【问题讨论】:
标签:
android
tensorflow
neural-network
tensorflow-lite
【解决方案1】:
您可以使用TensorFlowInferenceInterface 使用 .pb 文件进行预测。首先,将 .pb 文件放在应用的 assets 文件夹中。
- 在您的 build.gradle(Module: app) 文件中,添加以下依赖项,
implementation 'org.tensorflow:tensorflow-android:1.11.0'
- 然后初始化TensorFlowInferenceInterface,如果你的模型文件名是“model.pb”那么,
TensorFlowInferenceInterface tensorFlowInferenceInterface = new TensorFlowInferenceInterface(context.getAssets() , "file:///android_asset/model.pb") ;
tensorFlowInferenceInterface.feed( INPUT_NAME , inputs , 1, 28, 28); 其中INPUT_NAME 是输入层的名称。 1 , 50 是输入维度。
tensorFlowInferenceInterface.run( new String[]{ OUTPUT_NAME } ); 其中OUTPUT_NAME 是您的输出层的名称。
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 ) ;