def export_graph(self) -> None: """Export a frozen graph in .pb format to the specified path.""" anchors = parse_anchors(self._paths["anchors_file"]) classes = read_class_names(self._paths["classes_file"]) num_class = len(classes) with tf.Session() as sess: # build graph input_data = tf.placeholder(tf.float32, [None, None, None, 3], name='input') yolo_model = yolov3(num_class, anchors, use_static_shape=False) with tf.variable_scope('yolov3'): pred_feature_maps = yolo_model.forward(input_data, False) pred_boxes, pred_confs, pred_probs = yolo_model.predict( pred_feature_maps) pred_scores = pred_confs * pred_probs _, _, _ = gpu_nms(pred_boxes, pred_scores, num_class, max_boxes=20, score_thresh=0.5, nms_thresh=0.5) # restore weight saver = tf.train.Saver() saver.restore(sess, self.get_weights_path()) # save output_node_names = [ "output/boxes", "output/scores", "output/labels", "input", ] output_graph_def = tf.graph_util.convert_variables_to_constants( sess, tf.get_default_graph().as_graph_def(), output_node_names) with tf.gfile.GFile(self._paths['frozen_graph_file'], "wb") as new_file: new_file.write(output_graph_def.SerializeToString()) print("{} ops written to {}.".format( len(output_graph_def.node), self._paths['frozen_graph_file'])) # noqa
def __init__(self, weights_file: str, anchors_file: str, classes_file: str, settings: Optional[YoloSettings] = None) -> None: """Initialize a YOLOv3 model.""" if not settings: settings = YoloSettings() super().__init__(settings) args.restore_path = weights_file args.anchor_path = anchors_file args.class_name_path = classes_file for field, setting in dataclasses.asdict(settings).items(): setattr(args, field, setting) args.init_inference() self._is_training = tf.placeholder(dtype=tf.bool, name="phase_train") self._pred_boxes_flag = tf.placeholder(tf.float32, [1, None, None]) self._pred_scores_flag = tf.placeholder(tf.float32, [1, None, None]) self._image = tf.placeholder( tf.float32, [1, args.img_size[1], args.img_size[0], 3]) self._gpu_nms_op = gpu_nms(self._pred_boxes_flag, self._pred_scores_flag, args.class_num, args.nms_topk, args.score_threshold, args.nms_threshold) yolo_model = yolov3(args.class_num, args.anchors) with tf.variable_scope('yolov3'): pred_feature_maps = yolo_model.forward( self._image, is_training=self._is_training) self._y_pred = yolo_model.predict(pred_feature_maps) self._session = tf.Session() self._session.run([tf.global_variables_initializer()]) print(f"\n\n\nargs.restore_path: {args.restore_path}\n\n\n") tf.train.Saver().restore(self._session, args.restore_path)
image_ids, image, y_true_13, y_true_26, y_true_52 = iterator.get_next() y_true = [y_true_13, y_true_26, y_true_52] # tf.data pipeline will lose the data `static` shape, so we need to set it manually image_ids.set_shape([None]) image.set_shape([None, None, None, 3]) for y in y_true: y.set_shape([None, None, None, None, None]) ################## # Model definition ################## yolo_model = yolov3(args.class_num, args.anchors, args.use_label_smooth, args.use_focal_loss, args.batch_norm_decay, args.weight_decay, use_static_shape=False) with tf.variable_scope('yolov3'): pred_feature_maps = yolo_model.forward(image, is_training=is_training) loss = yolo_model.compute_loss(pred_feature_maps, y_true) y_pred = yolo_model.predict(pred_feature_maps) l2_loss = tf.losses.get_regularization_loss() # setting restore parts and vars to update # saver_to_restore = tf.train.Saver(var_list=tf.contrib.framework.get_variables_to_restore(include=args.restore_include, exclude=args.restore_exclude)) update_vars = tf.contrib.framework.get_variables_to_restore( include=args.update_part)
from __future__ import division, print_function import os import sys import tensorflow as tf import numpy as np from lns.yolo._lib.model import yolov3 from lns.yolo._lib.utils.misc_utils import parse_anchors, load_weights num_class = 80 img_size = 416 weight_path = './data/darknet_weights/yolov3.weights' save_path = './data/darknet_weights/yolov3.ckpt' anchors = parse_anchors('./data/yolo_anchors.txt') model = yolov3(80, anchors) with tf.Session() as sess: inputs = tf.placeholder(tf.float32, [1, img_size, img_size, 3]) with tf.variable_scope('yolov3'): feature_map = model.forward(inputs) saver = tf.train.Saver(var_list=tf.global_variables(scope='yolov3')) load_ops = load_weights(tf.global_variables(scope='yolov3'), weight_path) sess.run(load_ops) saver.save(sess, save_path=save_path) print('TensorFlow model checkpoint has been saved to {}'.format(save_path))
num_parallel_calls=args.num_threads ) val_dataset.prefetch(args.prefetech_buffer) iterator = val_dataset.make_one_shot_iterator() image_ids, image, y_true_13, y_true_26, y_true_52 = iterator.get_next() image_ids.set_shape([None]) y_true = [y_true_13, y_true_26, y_true_52] image.set_shape([None, args.img_size[1], args.img_size[0], 3]) for y in y_true: y.set_shape([None, None, None, None, None]) ################## # Model definition ################## yolo_model = yolov3(args.class_num, args.anchors) with tf.variable_scope('yolov3'): pred_feature_maps = yolo_model.forward(image, is_training=is_training) loss = yolo_model.compute_loss(pred_feature_maps, y_true) y_pred = yolo_model.predict(pred_feature_maps) saver_to_restore = tf.train.Saver() with tf.Session() as sess: sess.run([tf.global_variables_initializer()]) saver_to_restore.restore(sess, args.restore_path) print('\n----------- start to eval -----------\n') val_loss_total, val_loss_xy, val_loss_wh, val_loss_conf, val_loss_class = \ AverageMeter(), AverageMeter(), AverageMeter(), AverageMeter(), AverageMeter()