there are something wrong when changing keras .h5 model to tensorflow .pb model

Viewed 81

I want to change the keras .h5 file to tensorflow .pb file. It seems there are something wrong with the .pb file. My code is shown as follow:

network_eval = model.vggvox_resnet2d_icassp(input_dim=params['dim'],
                                        num_class=params['n_classes'],
                                        mode='eval', args=args)  
path = 'XXX'
name = 'XXX.pb'
network_eval.load_weights(os.path.join(args.resume), by_name=True)   # load model 

# I use parts of the keras_to_tensorflow util, see https://github.com/amir-abdi/keras_to_tensorflow 
orig_output_node_names = [node.op.name for node in network_eval.outputs]
# I do not change the output_nodes_prefix, so 
converted_output_node_names = orig_output_node_names

sess = K.get_session()
constant_graph = graph_util.convert_variables_to_constants(sess, sess.graph.as_graph_def(), converted_output_node_names)
graph_io.write_graph(constant_graph, path, name, as_text=False)

The .pb file was generated successfully, but the predicted outputs of the test file using .pb model are different from those using original .h5 keras model. The test code is shown as

# using .h5 model 
for spec in specs:  # specs is sliced magtitude spectrum of a .wav file for predicting
    spec = np.expand_dims(np.expand_dims(spec, 0), -1)
    v_1 = network_eval.predict(spec)
    print(v_1)

# using .pb model
sess = tf.Session()
with gfile.FastGFile('XXX.pb', 'rb') as f:
     graph_def = tf.GraphDef()
     graph_def.ParseFromString(f.read())
     sess.graph.as_default()
     tf.import_graph_def(graph_def, name='')

sess.run(tf.global_variables_initializer())

# 'lambda_1/l2_normalize' is the name of the last layer of the network
# I got this name by printing network_eval.output.name
op = sess.graph.get_tensor_by_name('lambda_1/l2_normalize:0') 
x = sess.graph.get_tensor_by_name('input:0')

for spec in specs:
    spec = np.expand_dims(np.expand_dims(spec, 0), -1)
    v_2 = sess.run(op, feed_dict={x: spec, K.learning_phase(): 0})
    print(v_2)

As I said above, the printed results v_1 and v_2 are quite different, but they have the same shape, which makes me confused and I don't know which step was wrong. Is there anyone can help me? I will be very grateful.

0 Answers
Related