步骤:
(1)修改WORKSPACE 配置(sdk & ndk)
# Uncomment and update the paths in these entries to build the Android demo.
android_sdk_repository(
name = "androidsdk",
api_level = 23,
# Ensure that you have the build_tools_version below installed in the
# SDK manager as it updates periodically.
build_tools_version = "25.0.0",
# Replace with path to Android SDK on your system
path = "/Users/scucheri/Library/Android/sdk",
)
#
# Android NDK r12b is recommended (higher may cause issues with Bazel)
android_ndk_repository(
name="androidndk",
path="/Users/scucheri/Library/Android/android-ndk-r12b",
# This needs to be 14 or higher to compile TensorFlow.
# Note that the NDK version is not the API level.
api_level=14)
(2)在tensorflow根目录下 运行 ./configure 进行一些设置
(3)根据现有的模型文件.pb生成注册文件 ops_to_register.h,这个文件会被放置在tensorflow根目录下:
bazel build tensorflow/python/tools:print_selective_registration_header && \
bazel-bin/tensorflow/python/tools/print_selective_registration_header \
--graphs=/Users/scucheri/AllMyProjects/AI_android/tensorflow_models/optimized_frozen_lstm.pb > ops_to_register.h
(4)将生成的 ops_to_register.h 文件复制到./tensorflow/core/framework 目录下
(5)运行bazel生成so文件,--copt="-DSUPPORT_SELECTIVE_REGISTRATION" 就是表示需要开启选择注册的opt。这个非常有用,试了一下,原本9.7M的so文件,在用LSTM算法生成的.pb模型文件选择它需要的计算方法打包之后,缩减到了2.4M ! 多么惊喜的一件事~
bazel build -c opt --copt="-DSELECTIVE_REGISTRATION" \
--copt="-DSUPPORT_SELECTIVE_REGISTRATION" \
//tensorflow/contrib/android:libtensorflow_inference.so \
--host_crosstool_top=@bazel_tools//tools/cpp:toolchain \
--crosstool_top=//external:android/crosstool --cpu=armeabi-v7a
若想生成包括全部计算方法的.so,如下:
bazel build -c opt //tensorflow/contrib/android:libtensorflow_inference.so \
--crosstool_top=//external:android/crosstool \
--host_crosstool_top=@bazel_tools//tools/cpp:toolchain \
--cpu=armeabi-v7a
如果出错,试一下bazel clean 之后重新运行
结果:bazel-bin/tensorflow/contrib/android/libtensorflow_inference.so
(6)生成jar
bazel build //tensorflow/contrib/android:android_tensorflow_inference_java
结果:bazel-bin/tensorflow/contrib/android/libandroid_tensorflow_inference_java.jar
参考:
https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/android