当前位置:   article > 正文

tensorflow2.x保存pb模型,用于opencv3.4.16 dnn模块调用_tensorflow.python.framework.convert_to_constants

tensorflow.python.framework.convert_to_constants
  1. # -------------------
  2. from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
  3. def save_model_to_cv_dnn(netmodel, frozen_out_path, frozen_graph_filename):
  4. full_model = tf.function(lambda x: netmodel(x)).get_concrete_function(tf.TensorSpec(netmodel.inputs[0].shape, netmodel.inputs[0].dtype))
  5. # Get frozen ConcreteFunction
  6. frozen_func = convert_variables_to_constants_v2(full_model)
  7. frozen_func.graph.as_graph_def()
  8. layers = [op.name for op in frozen_func.graph.get_operations()]
  9. print("-" * 60)
  10. print("Frozen model layers: ")
  11. for layer in layers:
  12. print(layer)
  13. print("-" * 60)
  14. print("Frozen model inputs: ")
  15. print(frozen_func.inputs) # 模型输入
  16. print("Frozen model outputs: ")
  17. print(frozen_func.outputs) # 模型输出
  18. # 存储PB模型
  19. # Save frozen graph to disk
  20. tf.io.write_graph(graph_or_graph_def=frozen_func.graph,
  21. logdir=frozen_out_path,
  22. name=f"{frozen_graph_filename}.pb",
  23. as_text=False)
  24. # Save its text representation
  25. tf.io.write_graph(graph_or_graph_def=frozen_func.graph,
  26. logdir=frozen_out_path,
  27. name=f"{frozen_graph_filename}.pbtxt",
  28. as_text=True)
  29. # path of the directory where you want to save your model
  30. model.save('./data/tf_model_savedmodel', save_format="tf") print('export saved model.') model_loaded = tf.keras.models.load_model('./data/tf_model_savedmodel') yout = model_loaded.predict(x_test) ylab = yout[:, 0] > 0.5 print(ylab.shape) print(y_test.shape) model_loaded.evaluate(x = x_test,y = y_test)
  31. frozen_out_path = './' # 存储模型的路径
  32. # name of the .pb file
  33. frozen_graph_filename = "frozen_graph1" # 模型名称
  34. save_model_to_cv_dnn(model,frozen_out_path,frozen_graph_filename)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/154349
推荐阅读
相关标签
  

闽ICP备14008679号