Android中运行Tensorflow程序3-遇到的错误及解决

来源:互联网 发布:二小姐捏脸数据 编辑:程序博客网 时间:2024/06/05 09:23

A/native: tensor.cc:487 Check failed: dtype() == expected_dtype (9 vs. 3)

原因解释

出现这种错误的原因是:程序预期的数据是tf.int32,然而真正的数据是tf.int64。在我的应用中,出现以上错误的程序如下。
在TF模型中,有如下的定义。

self.predictions = tf.argmax(self.logits, 1, name="predictions")

这里,函数tf.argmax返回的Tensor的类型是tf.int64
在进行了freeze_graphoptimize_for_inference之后,我在Android app中按照如下方式调用模型进行了预测:

    tensorFlowInferenceInterface = new TensorFlowInferenceInterface();    tensorFlowInferenceInterface.initializeTensorFlow(assetManager,MODEL_FILE);    tensorFlowInferenceInterface.fillNodeInt(INPUT_X,INPUT_X_SIZE,input);    tensorFlowInferenceInterface.fillNodeFloat(INPUT_DROPOUT_KEEP_PROB,new int[]{1},new float[]{myDropKeepProb});    tensorFlowInferenceInterface.runInference(new String[] {PREDICTIONS});    int[] resu = new int[1];    tensorFlowInferenceInterface.readNodeInt(PREDICTIONS,resu);

那么在最后一句的时候报出了上述错误。

解决方法

在TF模型中,把tf.int64位的数据改成tf.int32位的数据。

prediction = tf.argmax(self.logits,1,name='pre')self.predictions = tf.cast(prediction,tf.int32,name='predictions')

java.lang.UnsatisfiedLinkError:dalvik.system.PathClassLoader

原因分析

在我的项目中,是因为so文件的位置引起的。
在Android Studio中,默认的so文件路径是app/src/main/jniLibs/armeabi,根据平台的不同,so文件的路径还可能是app/src/main/jniLibs/armeabi-v7aapp/src/main/jniLibs/arm64-v8aapp/src/main/jniLibs/x86app/src/main/jniLibs/x86_64等。
在我的项目中,本来是用到了外部的so文件的,这些文件放在app/src/main/jniLibs/armeabi-v7a中。
然后我按照前一篇文章Android中运行Tensorflow程序2-编写自己的程序中的过程来配置自己的Tensorflow模型。把相关的so文件拷贝到了pp/libs/文件夹中。
然后修改app/build.gradle,增加如下内容,使系统知道这些libraries在什么位置。

sourceSets {        main {            jniLibs.srcDirs = ['libs']        }    }

那么问题出在这里,这样修改之后,系统可以找到我后来添加的tensorflow的那些so文件,但是原来在app/src/main/jniLibs/里面的那些so文件就找不到了,最终,app报出了java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader的错误。

解决办法

自己的那些tensorflow的so文件也放到app/src/main/jniLibs/里面来。然后把app/build.gradle中增加的内容删除。
但是这里需要注意一点,tensorflow的so文件后很多平台的版本,包括arm64-v8aarmeabi-v7a以及其他。我原来使用的so文件都只有armeabi-v7a版本的。当把tensorflow的arm64-v8a版本拷进来之后,系统对于所有的so文件都会去寻找arm64-v8a的版本,这个时候还是会有上述问题。这种情况下,应该只拷armeabi-v7a版本的so文件进来。

原创粉丝点击