我正在尝试在 Android 应用程序中运行一个简单的鸢尾花分类器。我在 keras 中创建了一个 MLP,将其转换为 .pb 格式并将其放入 Assets 文件夹中。 keras模型:
data = sklearn.datasets.load_iris()
x=data.data
y=data.target
x=np.array(x)
y=np.array(y)
x_train, x_test, y_train, y_test= train_test_split(x, y, test_size = 0.25)
inputs=Input(shape=(4,))
x=Dense(10,activation="relu",name="input_layer")(inputs)
x=Dense(10,activation="relu")(x)
x=Dense(15,activation="relu")(x)
x=Dense(3,activation="softmax",name="output_layer")(x)
model=Model(inputs,x)
sgd = SGD(lr=0.05, momentum=0.9, decay=0.0001, nesterov=False)
model.compile(optimizer=sgd, loss="sparse_categorical_crossentropy", metrics=["accuracy"])
model.fit(x_train,y_train,batch_size=20, epochs=100, verbose=0)
AndroidStudio 中的代码(我有 4 个输入数字字段、1 个输出字段和 1 个按钮。单击按钮时会调用 predictClick 方法):
static{
System.loadLibrary("tensorflow_inference");
}
String model_name ="file:///android_asset/iris_model.pb";
String output_name = "output_layer";
String input_name = "input_data";
TensorFlowInferenceInterface tfinterface;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tfinterface = new TensorFlowInferenceInterface(getAssets(),model_name);
}
public void predictClick(View v){
TextView antwort = (TextView)findViewById(R.id.antwort);
EditText number1 = (EditText)findViewById(R.id.number1);
EditText number2 = (EditText)findViewById(R.id.number2);
EditText number3 = (EditText)findViewById(R.id.number3);
EditText number4 = (EditText)findViewById(R.id.number4);
Button predict = (Button)findViewById(R.id.button);
float[] result = {};
String zahl1 = number1.getText().toString();
String zahl2 = number2.getText().toString();
String zahl3 = number3.getText().toString();
String zahl4 = number4.getText().toString();
float n1 = Float.parseFloat(zahl1);
float n2 = Float.parseFloat(zahl2);
float n3 = Float.parseFloat(zahl3);
float n4 = Float.parseFloat(zahl4);
float[] inputs={n1,n2,n3,n4};
//im pretty sure these lines cause the error
tfinterface.feed(input_name,inputs,4,1);
tfinterface.run(new String[]{output_name});
tfinterface.fetch(output_name,result);
antwort.setText(Float.toString(result[0]));
}
构建运行没有错误,但当我点击预测按钮时,应用程序崩溃了。当我离开台词时
tfinterface.feed(input_name,inputs,4,1);
tfinterface.run(new String[]{output_name});
tfinterface.fetch(output_name,result);
应用程序运行正常,所以我认为这是错误的来源。
最佳答案
模型的输入层在 Python 代码中命名为“input_layer”,但在 Java 代码中命名为“input_data”。
同时检查您的 logcat 输出。您应该会收到一条错误消息,指出该模型没有您正在搜索的输入层。
关于android - 在 Android 中运行 tensorflow 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50078126/