简体   繁体   中英

vgg16 keras save model for exporting c++

I recently working on the vgg16 to reuse its models.

in the python: (Keras)

model = applications.VGG16(include_top=False, weights='imagenet')

and its all good .

I need to export THiS model with compile and fit to export c++ json file. How can I export ThiS model properly a h5 file to utilize for exporting model?

One approach would be to convert your Keras model to a TensorFlow model in Python and then export a frozen graph to .pb file. Then load that in C++. I have used this piece of code to export a frozen .pb file from Keras.

import tensorflow as tf

from keras import backend as K
from tensorflow.python.framework import graph_util

K.set_learning_phase(0)
model = function_that_returns_your_keras_model()
sess = K.get_session()

output_node_name = "my_output_node" # Name of your output node

with sess as sess:
    init_op = tf.global_variables_initializer()
    sess.run(init_op)
    graph_def = sess.graph.as_graph_def()
    output_graph_def = graph_util.convert_variables_to_constants(
                                                                 sess,
                                                                 sess.graph.as_graph_def(),
                                                                 output_node_name.split(","))
    tf.train.write_graph(output_graph_def,
                         logdir="my_dir",
                         name="my_model.pb",
                         as_text=False)

You can then follow any tutorial on how to load the .pb file in C++. For an example this one: https://medium.com/jim-fleming/loading-a-tensorflow-graph-with-the-c-api-4caaff88463f

Keras injects the learning_phase variable in the TensorFlow graph and possibly also other Keras-only variables - if I remember correctly, you should make sure to remove these from the graph.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM