keras模型导出到tensorflow,以及pb模型导出

1 keras模型导出成tf模型

https://github.com/amir-abdi/keras_to_tensorflow/blob/master/keras_to_tensorflow.ipynb

constant_graph = graph_util.convert_variables_to_constants(sess, sess.graph.as_graph_def(), pred_node_names)
pred_node_names 为keras模型输出的名字,可用model.output.name拿到
graph_io.write_graph(constant_graph, output_fld, output_graph_name, as_text=False)
函数定义:
write_graph(
graph_or_graph_def,
logdir,
name,
as_text=True
)
函数returns:the path of the output proto file
The graph is written as a binary proto unless as_text is True

注意:
调整keras的learning_phase为0,表示为测试模式
from keras import backend as K
K.set_learning_phase(0)  # all new operations will be in test mode from now on# serialize the model and get its weights, for quick re-buildingconfig = previous_model.get_config()weights = previous_model.get_weights()# re-build a model where the learning phase is now hard-coded to 0
from keras.models import model_from_config
new_model = model_from_config(config)
new_model.set_weights(weights)
由此发现write_graph中model是由输出决定的,即不同的输出对应不同的model
graph_def = g_2.as_graph_def()
tf.train.write_graph(graph_def, export_dir, 'expert-graph.pb', as_text=False)
猜测:此种只保留了图的结构
 
2 pb模型导出
with open(output_graph_path, "rb") as f:
        output_graph_def = tf.GraphDef()
        output_graph_def.ParseFromString(f.read())
        _ = tf.import_graph_def(output_graph_def, name="")

with tf.Session() as sess:
        tf.initialize_all_variables().run()
        input_x = sess.graph.get_tensor_by_name("input:0")
#和模型的输入名字有关,input是模型的输入tensor
        print input_x
        output = sess.graph.get_tensor_by_name("output:0")
        print output
#和模型的输出名字有关,output是模型的输出tensor
        y_conv_2 = sess.run(output,{input_x:mnist.test.images})
        print "y_conv_2", y_conv_2
       

 
 


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值