无法 运行 android studio 中 Interpreter 上的 tflite 模型
Can not run the the tflite model on Interpreter in android studio
我正在尝试 运行 在我的智能手机应用程序上构建 TensorFlow-lite 模型。首先,我使用 LSTM 用数值数据训练模型,并使用 TensorFlow.Keras 构建模型层。我使用了 TensorFlow V2.x 并将经过训练的模型保存在服务器上。之后,模型通过 App 下载到智能手机的内部存储器,并使用“MappedByteBuffer”加载到解释器。到这里为止一切正常。
问题在于解释器无法读取 运行 模型。
我还在 build.gradle.
上添加了所需的依赖项
python中tflite模型的转换代码:
from tensorflow import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, LSTM
from tensorflow.keras import regularizers
#Create the network
model = Sequential()
model.add(LSTM(...... name = 'First_layer'))
model.add(Dropout(rate=Drop_out))
model.add(LSTM(...... name = 'Second_layer'))
model.add(Dropout(rate=Drop_out))
# compile model
model.compile(loss=keras.losses.mae,
optimizer=keras.optimizers.Adam(learning_rate=learning_rate), metrics=["mae"])
# fit model
model.fit(.......)
#save the model
tf.saved_model.save(model,'saved_model')
print("Model type", model1.dtype)# Model type is float32 and size around 2MB
#Convert saved model into TFlite
converter = tf.lite.TFLiteConverter.from_saved_model('saved_model')
tflite_model = converter.convert()
with open("Model.tflite, "wb") as f:
f.write(tflite_model)
f.close()
我也尝试了使用 Keras 的其他转换方式
# converter = tf.lite.TFLiteConverter.from_keras_model(keras_model)
# tflite_model = converter.convert()
完成此步骤后,“Model.tflite”将被转换并下载到智能手机的内存中。
Android工作室代码:
try {
private Interpreter tflite = new Interpreter(loadModelFile());
Log.d("Load_model", "Created a Tensorflow Lite of AutoAuth.");
} catch (IOException e) {
Log.e("Load_model", "IOException loading the tflite file");
}
private MappedByteBuffer loadModelFile() throws IOException {
String model_path = model_directory + model_name + ".tflite";
Log.d(TAG, model_path);
File file = new File(model_path);
if(file!=null){
FileInputStream inputStream = new FileInputStream(file);
FileChannel fileChannel = inputStream.getChannel();
return fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
}else{
return null;
}
}
“loadModelFile()”函数工作正常,因为我使用另一个使用 MNIST 数据集进行图像分类的 tflite 模型对其进行了检查。问题只是解释器。
这也是build.gradle的内容:
android {
aaptOptions {
noCompress "tflite"
}
}
android {
defaultConfig {
ndk {
abiFilters 'armeabi-v7a', 'arm64-v8a'
}
}
}
dependencies {
implementation 'com.jakewharton:butterknife:8.8.1'
implementation 'org.tensorflow:tensorflow-lite:0.1.2-nightly'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
implementation fileTree(dir: 'libs', include: ['*.jar'])
//noinspection GradleCompatible
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:2.0.4'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
每当我 运行 Android 工作室时,我都会遇到以下错误之一:
1-
或
2-
我查阅了许多资源和线程,并阅读了有关保存训练模型、TFlite 转换和解释器的内容。
我在 5 天前尝试解决这个问题,但没有希望。任何人都可以为此提供解决方案吗?
参考最新的 TfLite android 应用示例之一可能会有所帮助:Model Personalization App。此演示应用程序使用迁移学习模型而不是 LSTM,但整体工作流程应该相似。
正如 Farmaker 在评论中提到的,尝试在 gradle 依赖项中使用 SNAPSHOT:
implementation 'org.tensorflow:tensorflow-lite:0.0.0-nightly-SNAPSHOT'
要正确加载模型,您可以尝试:
protected MappedByteBuffer loadMappedFile(String filePath) throws IOException {
AssetFileDescriptor fileDescriptor = assetManager.openFd(this.directoryName + "/" + filePath);
FileInputStream inputStream = new FileInputStream(fileDescriptor.getFileDescriptor());
FileChannel fileChannel = inputStream.getChannel();
long startOffset = fileDescriptor.getStartOffset();
long declaredLength = fileDescriptor.getDeclaredLength();
return fileChannel.map(MapMode.READ_ONLY, startOffset, declaredLength);
}
此代码段也可以在我上面发布的 GitHub 示例 link 中找到。
loadMappedFile 在 tensorflow lite utils 中有 impl
import org.tensorflow.lite.support.common.FileUtil;
MappedByteBuffer tfliteModel = FileUtil.loadMappedFile(activity, getModelPath());
我正在尝试 运行 在我的智能手机应用程序上构建 TensorFlow-lite 模型。首先,我使用 LSTM 用数值数据训练模型,并使用 TensorFlow.Keras 构建模型层。我使用了 TensorFlow V2.x 并将经过训练的模型保存在服务器上。之后,模型通过 App 下载到智能手机的内部存储器,并使用“MappedByteBuffer”加载到解释器。到这里为止一切正常。
问题在于解释器无法读取 运行 模型。 我还在 build.gradle.
上添加了所需的依赖项python中tflite模型的转换代码:
from tensorflow import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, LSTM
from tensorflow.keras import regularizers
#Create the network
model = Sequential()
model.add(LSTM(...... name = 'First_layer'))
model.add(Dropout(rate=Drop_out))
model.add(LSTM(...... name = 'Second_layer'))
model.add(Dropout(rate=Drop_out))
# compile model
model.compile(loss=keras.losses.mae,
optimizer=keras.optimizers.Adam(learning_rate=learning_rate), metrics=["mae"])
# fit model
model.fit(.......)
#save the model
tf.saved_model.save(model,'saved_model')
print("Model type", model1.dtype)# Model type is float32 and size around 2MB
#Convert saved model into TFlite
converter = tf.lite.TFLiteConverter.from_saved_model('saved_model')
tflite_model = converter.convert()
with open("Model.tflite, "wb") as f:
f.write(tflite_model)
f.close()
我也尝试了使用 Keras 的其他转换方式
# converter = tf.lite.TFLiteConverter.from_keras_model(keras_model)
# tflite_model = converter.convert()
完成此步骤后,“Model.tflite”将被转换并下载到智能手机的内存中。
Android工作室代码:
try {
private Interpreter tflite = new Interpreter(loadModelFile());
Log.d("Load_model", "Created a Tensorflow Lite of AutoAuth.");
} catch (IOException e) {
Log.e("Load_model", "IOException loading the tflite file");
}
private MappedByteBuffer loadModelFile() throws IOException {
String model_path = model_directory + model_name + ".tflite";
Log.d(TAG, model_path);
File file = new File(model_path);
if(file!=null){
FileInputStream inputStream = new FileInputStream(file);
FileChannel fileChannel = inputStream.getChannel();
return fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
}else{
return null;
}
}
“loadModelFile()”函数工作正常,因为我使用另一个使用 MNIST 数据集进行图像分类的 tflite 模型对其进行了检查。问题只是解释器。
这也是build.gradle的内容:
android {
aaptOptions {
noCompress "tflite"
}
}
android {
defaultConfig {
ndk {
abiFilters 'armeabi-v7a', 'arm64-v8a'
}
}
}
dependencies {
implementation 'com.jakewharton:butterknife:8.8.1'
implementation 'org.tensorflow:tensorflow-lite:0.1.2-nightly'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
implementation fileTree(dir: 'libs', include: ['*.jar'])
//noinspection GradleCompatible
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:2.0.4'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
每当我 运行 Android 工作室时,我都会遇到以下错误之一:
1-
或
2-
我查阅了许多资源和线程,并阅读了有关保存训练模型、TFlite 转换和解释器的内容。 我在 5 天前尝试解决这个问题,但没有希望。任何人都可以为此提供解决方案吗?
参考最新的 TfLite android 应用示例之一可能会有所帮助:Model Personalization App。此演示应用程序使用迁移学习模型而不是 LSTM,但整体工作流程应该相似。
正如 Farmaker 在评论中提到的,尝试在 gradle 依赖项中使用 SNAPSHOT:
implementation 'org.tensorflow:tensorflow-lite:0.0.0-nightly-SNAPSHOT'
要正确加载模型,您可以尝试:
protected MappedByteBuffer loadMappedFile(String filePath) throws IOException {
AssetFileDescriptor fileDescriptor = assetManager.openFd(this.directoryName + "/" + filePath);
FileInputStream inputStream = new FileInputStream(fileDescriptor.getFileDescriptor());
FileChannel fileChannel = inputStream.getChannel();
long startOffset = fileDescriptor.getStartOffset();
long declaredLength = fileDescriptor.getDeclaredLength();
return fileChannel.map(MapMode.READ_ONLY, startOffset, declaredLength);
}
此代码段也可以在我上面发布的 GitHub 示例 link 中找到。
loadMappedFile 在 tensorflow lite utils 中有 impl
import org.tensorflow.lite.support.common.FileUtil;
MappedByteBuffer tfliteModel = FileUtil.loadMappedFile(activity, getModelPath());