Невозможно правильно получить вывод пользовательской модели Tflite Model в приложении Android - PullRequest
0 голосов
/ 14 января 2020

Я обучил очень простую модель и преобразовал ее в модель Tflite .... Код python для модели выглядит следующим образом

# -*- coding: utf-8 -*-
"""
Created on Sat Sep 28 21:05:22 2019

@author: Aneshka Goyal
"""

import tensorflow as tf
def freeze_session(session, keep_var_names=None, output_names=None, clear_devices=True):
    """
    Freezes the state of a session into a pruned computation graph.

    Creates a new computation graph where variable nodes are replaced by
    constants taking their current value in the session. The new graph will be
    pruned so subgraphs that are not necessary to compute the requested
    outputs are removed.
    @param session The TensorFlow session to be frozen.
    @param keep_var_names A list of variable names that should not be frozen,
                          or None to freeze all the variables in the graph.
    @param output_names Names of the relevant graph outputs.
    @param clear_devices Remove the device directives from the graph for better portability.
    @return The frozen graph definition.
    """
    graph = session.graph
    with graph.as_default():
        freeze_var_names = list(set(v.op.name for v in tf.global_variables()).difference(keep_var_names or []))
        output_names = output_names or []
        output_names += [v.op.name for v in tf.global_variables()]
        input_graph_def = graph.as_graph_def()
        if clear_devices:
            for node in input_graph_def.node:
                node.device = ""
        frozen_graph = tf.graph_util.convert_variables_to_constants(
            session, input_graph_def, output_names, freeze_var_names)
        return frozen_graph

inp = tf.placeholder(name="inp", dtype=tf.float32, shape=(1, 1))

w = tf.Variable(tf.zeros([1, 1], tf.float32), dtype=tf.float32, name="w")



y = tf.matmul(w, inp)



out = tf.identity(y, name="out")



init_op = tf.global_variables_initializer()



with tf.Session() as sess:

    sess.run(init_op)



    # After Init var, change the value to 2

    assignment = w.assign([[2]])

    sess.run(assignment)



    output = sess.run(out, feed_dict={inp: [[1]]})

    print (output)



    frozen_graph = freeze_session(sess, output_names=[out.op.name])



    tflite_model = tf.contrib.lite.toco_convert(frozen_graph, [inp], [out])

    open("mat_mul.tflite", "wb").write(tflite_model)

Я могу получить правильную Размеры входных и выходных данных этой модели, чтобы поместить их в следующий android кодовый код для интеграции с моим приложением android, но я сомневаюсь, что вывод выводится из FirebaseInterpreter корректно ...., как указано в комментарии к попытке -catch block.

    package com.example.aneshkagoyal.samplecustom;

    import android.support.annotation.NonNull;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.widget.TextView;
    import android.widget.Toast;

    import com.google.android.gms.tasks.OnFailureListener;
    import com.google.android.gms.tasks.OnSuccessListener;
    import com.google.firebase.FirebaseApp;
    import com.google.firebase.ml.common.FirebaseMLException;
    import com.google.firebase.ml.custom.FirebaseModelDataType;
    import com.google.firebase.ml.custom.FirebaseModelInputOutputOptions;
    import com.google.firebase.ml.custom.FirebaseModelInputs;
    import com.google.firebase.ml.custom.FirebaseModelInterpreter;
    import com.google.firebase.ml.custom.FirebaseModelManager;
    import com.google.firebase.ml.custom.FirebaseModelOptions;
    import com.google.firebase.ml.custom.FirebaseModelOutputs;
    import com.google.firebase.ml.custom.model.FirebaseLocalModelSource;

    public class MainActivity extends AppCompatActivity {
        FirebaseModelInterpreter firebaseInterpreter;
        FirebaseModelInputs inputs;
        FirebaseModelInputOutputOptions inputOutputOptions;
        TextView t;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            t = findViewById(R.id.my_text);
            FirebaseLocalModelSource localSource =
                    new FirebaseLocalModelSource.Builder("mat_mul")  // Assign a name to this model
                            .setAssetFilePath("mat_mul.tflite")
                            .build();
            FirebaseModelManager.getInstance().registerLocalModelSource(localSource);
            FirebaseModelOptions options = new FirebaseModelOptions.Builder()
                    .setLocalModelName("asset")
                    .build();
            try {
                 firebaseInterpreter =
                        FirebaseModelInterpreter.getInstance(options);
            } catch (FirebaseMLException e) {
                e.printStackTrace();

            }




            // Define the Input and Output dimensions and types

            try {
                 inputOutputOptions = new FirebaseModelInputOutputOptions.Builder()

                        .setInputFormat(0, FirebaseModelDataType.FLOAT32, new int[]{1,1})//This line

                        .setOutputFormat(0, FirebaseModelDataType.FLOAT32, new int[]{1,1})//This line

                        .build();
            } catch (FirebaseMLException e) {
                e.printStackTrace();

            }
            float[][] input;
            input = new float[1][1];
            //output = new float[1][1];
            input[0][0]= 21.0f;
            try {
                 inputs = new FirebaseModelInputs.Builder()
                        .add(input)  // add() as many input arrays as your model requires
                        .build();
            } catch (FirebaseMLException e) {
                e.printStackTrace();
                Log.d("Failure","in InputBuilder");
            }
//Check if the output is being correctly taken as float[1][1]
            try {
                firebaseInterpreter.run(inputs, inputOutputOptions)
                        .addOnSuccessListener(
                                new OnSuccessListener<FirebaseModelOutputs>() {
                                    @Override
                                    public void onSuccess(FirebaseModelOutputs result) {
                                        Toast.makeText(MainActivity.this,"output"+result.<float[][]>getOutput(0).toString(),Toast.LENGTH_SHORT).show();
                                        Log.d("ANSWERIS", result.<float[][]>getOutput(0).toString());
                                        t.setText(result.<float[][]>getOutput(0).toString());
                                    }
                                })
                        .addOnFailureListener(
                                new OnFailureListener() {
                                    @Override
                                    public void onFailure(@NonNull Exception e) {
                                        // Task failed with an exception
                                        // ...
                                        Log.d("Failure","ho gyaa");
                                    }
                                });
            } catch (FirebaseMLException e) {
                e.printStackTrace();
            }

        }



    }

Вывод, который я получаю в приложении, является сортировкой значения мусора [[F@6061395, и значение меняется каждый раз, и вывод, который я получаю, когда запускаю сценарий python (только) это [[2.]], который должен быть правильным ответом. Пожалуйста, помогите, предложив возможные источники ошибок, согласно моему ощущению, что-то должно быть с размерностью, поскольку я не уверен, правильно ли я это сделал.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...