h5->pb

    1. import tensorflow.compat.v1 as tf1
    2. tf1.reset_default_graph()
    3. tf1.keras.backend.set_learning_phase(0) # 调用模型前一定要执行该命令
    4. tf1.disable_v2_behavior() # 禁止tensorflow2.0的行为
    5. # 加载hdf5模型
    6. hdf5_pb_model = tf1.keras.models.load_model('mypilotkaggle_categorical_429.h5')
    7. def freeze_session(session, keep_var_names=None, output_names=None, clear_devices=True):
    8. graph = session.graph
    9. with graph.as_default():
    10. # freeze_var_names = list(set(v.op.name for v in tf1.global_variables()).difference(keep_var_names or []))
    11. output_names = output_names or []
    12. # output_names += [v.op.name for v in tf1.global_variables()]
    13. print("output_names", output_names)
    14. input_graph_def = graph.as_graph_def()
    15. # for node in input_graph_def.node:
    16. # print('node:', node.name)
    17. print("len node1", len(input_graph_def.node))
    18. if clear_devices:
    19. for node in input_graph_def.node:
    20. node.device = ""
    21. frozen_graph = tf1.graph_util.convert_variables_to_constants(session, input_graph_def,
    22. output_names)
    23. outgraph = tf1.graph_util.remove_training_nodes(frozen_graph) # 云掉与推理无关的内容
    24. print("##################################################################")
    25. for node in outgraph.node:
    26. print('node:', node.name)
    27. print("len node1", len(outgraph.node))
    28. return outgraph
    29. output_folder2 = 'keras_model'
    30. frozen_graph = freeze_session(tf1.compat.v1.keras.backend.get_session(),
    31. output_names=[out.op.name for out in hdf5_pb_model.outputs])
    32. tf1.train.write_graph(frozen_graph, output_folder2, "classify.pb", as_text=False)

    加载h5做预测:

    1. import tensorflow as tf
    2. from tensorflow import keras
    3. from PIL import Image
    4. from tensorflow.keras.layers import Input, Dense
    5. from tensorflow.keras.layers import Convolution2D, MaxPooling2D, \
    6. BatchNormalization
    7. from tensorflow.keras.layers import Activation, Dropout, Flatten
    8. from tensorflow.keras.layers import LSTM
    9. from tensorflow.keras.layers import TimeDistributed as TD
    10. from tensorflow.keras.layers import Conv3D, MaxPooling3D, Conv2DTranspose
    11. from tensorflow.keras.backend import concatenate
    12. from tensorflow.keras.models import Model, Sequential
    13. from tensorflow.python.keras.callbacks import EarlyStopping, ModelCheckpoint
    14. import numpy as np
    15. from typing import Dict, Any, Tuple, Optional, Union
    16. class KerasCategorical():
    17. def __init__(self, input_shape=(120, 160, 3), throttle_range=0.5):
    18. super().__init__()
    19. self.model = keras.models.load_model('mypilotkaggle_categorical_429.h5', compile=False)
    20. # self.model = default_categorical(input_shape)
    21. self.throttle_range = throttle_range
    22. # def compile(self):
    23. # self.model.compile(optimizer='adam', metrics=['accuracy'],
    24. # loss={'angle_out': 'categorical_crossentropy',
    25. # 'throttle_out': 'categorical_crossentropy'},
    26. # loss_weights={'angle_out': 0.5, 'throttle_out': 0.5})
    27. def inference(self, img_arr: np.ndarray):
    28. if img_arr is None:
    29. print('no image')
    30. return 0.0, 0.0
    31. img_arr = img_arr.reshape((1,) + img_arr.shape)
    32. angle_binned, throttle_binned = self.model.predict(img_arr)
    33. #print(angle_binned,throttle_binned)
    34. N = len(throttle_binned[0])
    35. throttle = linear_unbin(throttle_binned, N=N,
    36. offset=0.0, R=self.throttle_range)
    37. angle = linear_unbin(angle_binned)
    38. print(angle,throttle)
    39. return angle, throttle
    40. class KerasLinear():
    41. def __init__(self, num_outputs=2, input_shape=(120, 160, 3)):
    42. super().__init__()
    43. self.model = keras.models.load_model('mypilotkaggle429.h5', compile=False)
    44. #self.model = default_n_linear(num_outputs, input_shape)
    45. def inference(self, img_arr):
    46. img_arr = img_arr.reshape((1,) + img_arr.shape)
    47. outputs = self.model.predict(img_arr)
    48. steering = outputs[0]
    49. throttle = outputs[1]
    50. print(steering[0][0], throttle[0][0])
    51. return steering[0][0], throttle[0][0]
    52. def default_n_linear(num_outputs, input_shape=(120, 160, 3)):
    53. drop = 0.2
    54. img_in = Input(shape=input_shape, name='img_in')
    55. x = core_cnn_layers(img_in, drop)
    56. x = Dense(100, activation='relu', name='dense_1')(x)
    57. x = Dropout(drop)(x)
    58. x = Dense(50, activation='relu', name='dense_2')(x)
    59. x = Dropout(drop)(x)
    60. outputs = []
    61. for i in range(num_outputs):
    62. outputs.append(
    63. Dense(1, activation='linear', name='n_outputs' + str(i))(x))
    64. model = Model(inputs=[img_in], outputs=outputs)
    65. return model
    66. def linear_unbin(arr, N=15, offset=-1, R=2.0):
    67. '''
    68. preform inverse linear_bin, taking
    69. one hot encoded arr, and get max value
    70. rescale given R range and offset
    71. '''
    72. b = np.argmax(arr)
    73. a = b * (R / (N + offset)) + offset
    74. return a
    75. def conv2d(filters, kernel, strides, layer_num, activation='relu'):
    76. """
    77. Helper function to create a standard valid-padded convolutional layer
    78. with square kernel and strides and unified naming convention
    79. :param filters: channel dimension of the layer
    80. :param kernel: creates (kernel, kernel) kernel matrix dimension
    81. :param strides: creates (strides, strides) stride
    82. :param layer_num: used in labelling the layer
    83. :param activation: activation, defaults to relu
    84. :return: tf.keras Convolution2D layer
    85. """
    86. return Convolution2D(filters=filters,
    87. kernel_size=(kernel, kernel),
    88. strides=(strides, strides),
    89. activation=activation,
    90. name='conv2d_' + str(layer_num))
    91. def core_cnn_layers(img_in, drop, l4_stride=1):
    92. """
    93. Returns the core CNN layers that are shared among the different models,
    94. like linear, imu, behavioural
    95. :param img_in: input layer of network
    96. :param drop: dropout rate
    97. :param l4_stride: 4-th layer stride, default 1
    98. :return: stack of CNN layers
    99. """
    100. x = img_in
    101. x = conv2d(24, 5, 2, 1)(x)
    102. x = Dropout(drop)(x)
    103. x = conv2d(32, 5, 2, 2)(x)
    104. x = Dropout(drop)(x)
    105. x = conv2d(64, 5, 2, 3)(x)
    106. x = Dropout(drop)(x)
    107. x = conv2d(64, 3, l4_stride, 4)(x)
    108. x = Dropout(drop)(x)
    109. x = conv2d(64, 3, 1, 5)(x)
    110. x = Dropout(drop)(x)
    111. x = Flatten(name='flattened')(x)
    112. return x
    113. def default_categorical(input_shape=(120, 160, 3)):
    114. drop = 0
    115. img_in = Input(shape=input_shape, name='img_in')
    116. x = core_cnn_layers(img_in, drop, l4_stride=2)
    117. x = Dense(100, activation='relu', name="dense_1")(x)
    118. x = Dropout(drop)(x)
    119. x = Dense(50, activation='relu', name="dense_2")(x)
    120. x = Dropout(drop)(x)
    121. # Categorical output of the angle into 15 bins
    122. angle_out = Dense(15, activation='softmax', name='angle_out')(x)
    123. # categorical output of throttle into 20 bins
    124. throttle_out = Dense(20, activation='softmax', name='throttle_out')(x)
    125. model = Model(inputs=[img_in], outputs=[angle_out, throttle_out])
    126. return model
    127. cate = KerasCategorical()
    128. image = Image.open("2.jpg") # 用PIL中的Image.open打开图像
    129. image_arr = np.array(image) # 转化成numpy数组
    130. #print(image_arr)
    131. cate.inference(image_arr)

    加载pb做预测:

    1. # -*-coding:utf-8 -*- tf2
    2. import os
    3. import tensorflow as tf
    4. import numpy as np
    5. from PIL import Image
    6. from tensorflow import keras
    7. from tensorflow.keras import backend as K
    8. class FrozenPredict(object):
    9. """
    10. 读取固化模型进行预测
    11. """
    12. def __init__(self, frozen_graph_path):
    13. """
    14. 读取配置
    15. """
    16. self.frozen_graph_path = frozen_graph_path
    17. if not os.path.exists(frozen_graph_path):
    18. raise RuntimeError("模型文件不存在!")
    19. self.load_model()
    20. def load_model(self):
    21. """
    22. 加载模型
    23. """
    24. with open(self.frozen_graph_path, "rb") as f:
    25. graph_def = tf.GraphDef()
    26. graph_def.ParseFromString(f.read())
    27. # 导入计算图
    28. self.graph = tf.Graph()
    29. with self.graph.as_default():
    30. tf.import_graph_def(graph_def, name="")
    31. self.sess = tf.Session(graph=self.graph)
    32. def predict(self, input_x):
    33. """
    34. 预测
    35. """
    36. self.input_x = self.graph.get_tensor_by_name('img_in:0')
    37. #self.keep_prob = self.graph.get_tensor_by_name('keep_prob:0')
    38. logits = self.graph.get_operation_by_name('Softmax').outputs[0]
    39. pred = self.graph.get_tensor_by_name('pred:0')
    40. feed_dict = {
    41. self.input_x: input_x,
    42. #self.keep_prob: 1
    43. }
    44. # sess.run获得模型的预测输出
    45. prediction, logits = self.sess.run([pred, logits], feed_dict=feed_dict)
    46. #probs = np.max(logis, 1) # 取最大概率,结果为一维数组
    47. print(prediction)
    48. # #1、定义网络结构
    49. # model = ...
    50. #
    51. # #2、输出节点名称,用于查看output_node_names
    52. # for layer in model.layers:
    53. # print(layer.output.name)
    54. # model = keras.models.load_model('mypilotkaggle_categorical_429.h5', compile=False)
    55. # #3、生成pb格式的模型
    56. # #sess = K.get_session() #获得当前的sess
    57. # sess = tf.compat.v1.Session()
    58. #
    59. # #这个是将模型的结构和权重固化,注意第二步输出的节点名称形式为dense_1/Softmax:0,但是这里传入时需要将:0删除,不然会提示找不到tensor,不太清楚原因,之前用tensorflow时是需要写全的
    60. # frozen_def = tf.compat.v1.graph_util.convert_variables_to_constants(sess,sess.graph.as_graph_def(),output_node_names=['throttle_out/Softmax'])
    61. #
    62. # tf.compat.v1.train.write_graph(frozen_def, './', 'test_model.pb', as_text=False) #将网络的结构和权重写进pb文件中
    63. def linear_unbin(arr, N=15, offset=-1, R=2.0):
    64. '''
    65. preform inverse linear_bin, taking
    66. one hot encoded arr, and get max value
    67. rescale given R range and offset
    68. '''
    69. b = np.argmax(arr)
    70. a = b * (R / (N + offset)) + offset
    71. return a
    72. image = Image.open("2.jpg") # 用PIL中的Image.open打开图像
    73. img_arr = np.array(image) # 转化成numpy数组
    74. img_arr = img_arr.reshape((1,) + img_arr.shape) # 160,120,3变成1,160,120,3
    75. #4、在tensorflow中使用pb模型
    76. with tf.Graph().as_default():
    77. output_graph_def = tf.compat.v1.GraphDef()
    78. with open('keras_model/classify.pb', "rb") as f: #打开pb模型文件
    79. output_graph_def.ParseFromString(f.read()) #进行解析
    80. _ = tf.import_graph_def(output_graph_def, name="")
    81. with tf.compat.v1.Session() as sess: #下面就是使用模型
    82. sess.run(tf.compat.v1.global_variables_initializer())
    83. #下面的input_1:0和dense_1/Softmax:0都是通过步骤2查看的
    84. #然而这里节点名称却带了:0,我猜测是keras的graph中保存的节点名是不包含:0的,当你选择保存为pb格式时,此时注意我们是使用tensorflow的形式进行保存的,所以又都被加上了:0,当你读取的时候自然也要加上:0
    85. input_x = sess.graph.get_tensor_by_name("img_in:0")
    86. output1 = sess.graph.get_tensor_by_name("throttle_out/Softmax:0")
    87. output2 = sess.graph.get_tensor_by_name("angle_out/Softmax:0")
    88. throttle_binned, angle_binned = sess.run([output1, output2], feed_dict={input_x: img_arr})
    89. #angle_binned =
    90. N = len(throttle_binned[0])
    91. throttle = linear_unbin(throttle_binned, N=N,
    92. offset=0.0, R=0.5)
    93. angle = linear_unbin(angle_binned)
    94. print(angle,throttle)

    h5->pb>IR
    为了验证模型转化地没有问题,所以加载pb模型做了下预测,输出和h5是一样的。