.

因为我希望在 Android 上使用这个模型,所以我(.pb)使用keras_to_tensorflow 将模型重新冻结为二进制 protobuf

在移动设备上使用该模型进行推理时,我注意到该模型给出了非常错误和随机的预测。我已经尝试探索其他原因,为什么会出现这种情况,就像我在这里发现的那样,似乎很明显问题不在于加载图像。

此外,在 Tensorflow Python 上使用转换后的模型进行推理仍然会给出相同的错误/随机预测。这是我在 Python 中执行推理的代码。

def model_predict( model_path, image_path, model_input, model_output, class_names ):

    with tf.Graph().as_default() as graph: # Set default graph as graph

        with tf.Session() as sess:
            # Load the graph in graph_def
            print("load graph")

            # We load the protobuf file from the disk and parse it to retrive the unserialized graph_drf
            with gfile.FastGFile(model_path,'rb') as f:

                print("Load Image...")
                # Read the image & get statstics
                np_image = Image.open(image_path)
                np_image = np.array(np_image).astype('float32')/255
                np_image = np.resize(np_image, (224, 224, 3))
                np_image = np.expand_dims(np_image, axis=0)


                # Set FCN graph to the default graph
                graph_def = tf.GraphDef()
                graph_def.ParseFromString(f.read())
                sess.graph.as_default()

                # Import a graph_def into the current default Graph (In this case, the weights are (typically) embedded in the graph)

                tf.import_graph_def(
                graph_def,
                input_map=None,
                return_elements=None,
                name="",
                op_dict=None,
                producer_op_list=None
                )

                # INFERENCE Here
                m_input = graph.get_tensor_by_name(model_input) # Input Tensor
                m_output = graph.get_tensor_by_name(model_output) # Output Tensor

                print ("Shape of input : ", tf.shape(m_input))
                #initialize_all_variables
                tf.global_variables_initializer()

                # Run model on single image
                Session_out = sess.run( m_output, feed_dict = {m_input : np_image} )

                print("Predicted class:", class_names[Session_out[0].argmax()] )

如何使用带有保存.pb模型的 Tensorflow Python/Android 执行推理?

其他人建议我保存用于训练的会话,并在执行推理时将它们加载到 Tensorflow。如果是这种情况,我如何在 Tensorflow android 中加载保存的会话?

我确信该模型没有过度拟合,它在使用 Keras 时表现得非常好。

2个回答

我相信您用于推理的样本属于训练和测试集的不同数据分布。因此,我建议您验证上述情况是否属实,如果是,那么您应该针对您尝试进行推理的示例微调您的模型。

看到模型必须过拟合,因为预测代码看起来是正确的。请检查其他指标,而不是仅使用准确性。打印置信矩阵并查看结果。

其它你可能感兴趣的问题
上一篇终端中的数据可视化? 下一篇TFIDF 用于非常短的句子