Как найти входной и выходной узлы замороженной модели

Я хочу использовать tenorflow's optimize_for_inference.py Скрипт на замороженной модели из модельного зоопарка: ssd_mobilenet_v1_coco,

Как мне найти / определить имена входных и выходных названий модели?

Вот ссылка на график, созданный тензорной доской

Этот вопрос может помочь: учитывая тензорный граф модели потока, как найти имена входных и выходных узлов (для меня это не так)

4 ответа

Решение

Теперь мы добавили некоторую документацию по этому процессу, описанную здесь:

https://www.tensorflow.org/mobile/prepare_models

Если вы посмотрите на sumrize_graph, вы увидите пример того, как определить правильные входные и выходные узлы.

Я думаю, вы можете сделать, используя следующий код. Я загрузил ssd_mobilenet_v1_cocoзамороженная модель отсюда и смог получить входные и выходные имена, как показано ниже.

      !pip install tensorflow==1.15.5

import tensorflow as tf
tf.__version__ # TF1.15.5

gf = tf.GraphDef()  
m_file = open('/content/frozen_inference_graph.pb','rb')
gf.ParseFromString(m_file.read())
 
with open('somefile.txt', 'a') as the_file:
   for n in gf.node:
       the_file.write(n.name+'\n')
 
file = open('somefile.txt','r')
data = file.readlines()
print("output name = ")
print(data[len(data)-1])
 
print("Input name = ")
file.seek ( 0 )
print(file.readline())

Выход

      output name = 
detection_classes

Input name = 
image_tensor

Пожалуйста, проверьте суть здесь .

все модели, сохраненные с использованием API обнаружения объектов tensorflow, имеют image_tensor в качестве имени входного узла. Модель обнаружения объектов имеет 4 выхода:

  1. num_detections : прогнозирует количество обнаружений для данного изображения.
  2. discovery_classes: количество классов, на которых обучается модель.
  3. discovery_boxes : предсказывает (ymin, xmin, ymax, xmax) координаты
  4. discovery_scores : прогнозирует достоверность для каждого класса, следует выбрать класс с самым высоким прогнозом.

код для вывода save_model

      def load_image_into_numpy_array(path):
    'Converts Image into numpy array'
    img_data = tf.io.gfile.GFile(path, 'rb').read()
    image = Image.open(BytesIO(img_data))
    im_width, im_height = image.size
    return np.array(image.getdata()).reshape((im_height, im_width, 3)).astype(np.uint8)


# Load saved_model 
model = tf.saved_model.load_model('custom_mode/saved_model',tags=none)

# Convert image into numpy array
numpy_image = load_image_into_numpy_array('Image_path')

# Expand dimensions
input_tensor = np.expand_dims(numpy_image, 0)

# Send image to the model
model_output = model(input_tensor)
# Use output_nodes to predict the outputs 
num_detections = int(model_output.pop('num_detections'))
detections = {key: value[0, :num_detections].numpy()
              for key, value in detections.items()}

detections['num_detections'] = num_detections
detections['detection_classes'] = detections['detection_classes'].astype(np.int64)
boxes = detections['detection_boxes']
scores = detections['detection_scores']
pred_class = detections['detection_classes']

ты можешь просто сделатьmodel.summary()чтобы увидеть все имена слоев (а также их тип). Это первая колонка.

Другие вопросы по тегам