Tensorflow: how to restore a inception v3 pre trained network weights after having expanded the graph with new final layer

S. Ricci

I have this network model: an inception v3 pre trained. https://storage.googleapis.com/openimages/2016_08/model_2016_08.tar.gz

I want to extends it with new layer.

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import os.path

import tensorflow as tf
from tensorflow.contrib import layers
from tensorflow.contrib.slim.python.slim.nets import inception
from tensorflow.python.ops import array_ops
from tensorflow.python.training import saver as tf_saver

slim = tf.contrib.slim
FLAGS = None


def PreprocessImage(image, central_fraction=0.875):
    """Load and preprocess an image.

    Args:
      image: a tf.string tensor with an JPEG-encoded image.
      central_fraction: do a central crop with the specified
        fraction of image covered.
    Returns:
      An ops.Tensor that produces the preprocessed image.
    """

    # Decode Jpeg data and convert to float.
    image = tf.cast(tf.image.decode_jpeg(image, channels=3), tf.float32)

    image = tf.image.central_crop(image, central_fraction=central_fraction)
    # Make into a 4D tensor by setting a 'batch size' of 1.
    image = tf.expand_dims(image, [0])
    image = tf.image.resize_bilinear(image,
                                     [FLAGS.image_size, FLAGS.image_size],
                                     align_corners=False)

    # Center the image about 128.0 (which is done during training) and normalize.
    image = tf.multiply(image, 1.0 / 127.5)
    return tf.subtract(image, 1.0)


def main(args):
    if not os.path.exists(FLAGS.checkpoint):
        tf.logging.fatal(
            'Checkpoint %s does not exist. Have you download it? See tools/download_data.sh',
            FLAGS.checkpoint)
    g = tf.Graph()
    with g.as_default():
        input_image = tf.placeholder(tf.string)
        processed_image = PreprocessImage(input_image)

        with slim.arg_scope(inception.inception_v3_arg_scope()):
            logits, end_points = inception.inception_v3(
                processed_image, num_classes=FLAGS.num_classes, is_training=False)

        predictions = end_points['multi_predictions'] = tf.nn.sigmoid(
            logits, name='multi_predictions')

        sess = tf.Session()

        saver = tf_saver.Saver()

        saver.restore(sess, FLAGS.checkpoint)

        logits_2 = layers.conv2d(
            end_points['PreLogits'],
            FLAGS.num_classes, [1, 1],
            activation_fn=None,
            normalizer_fn=None,
            scope='Conv2d_final_1x1')

        logits_2 = array_ops.squeeze(logits_2, [1, 2], name='SpatialSqueeze_2')

        predictions_2 = end_points['multi_predictions_2'] = tf.nn.sigmoid(logits_2, name='multi_predictions_2')

        sess.run(tf.global_variables_initializer())


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--checkpoint', type=str, default='2016_08/model.ckpt',
                        help='Checkpoint to run inference on.')
    parser.add_argument('--dict', type=str, default='dict.csv',
                        help='Path to a dict.csv that translates from mid to a display name.')
    parser.add_argument('--image_size', type=int, default=299,
                        help='Image size to run inference on.')
    parser.add_argument('--num_classes', type=int, default=6012,
                        help='Number of output classes.')
    parser.add_argument('--image_path', default='test_set/0a9ed4def08fe6d1')
    FLAGS = parser.parse_args()
    tf.app.run()

how can i restore only the inception v3 pre-trained network weights saved in a model.ckpt file? how can i initialize the new conv2d layer?

S. Ricci

I solved the problem!!

You need to call saver.restore (sess, FLAGS.checkpoint) after initializing the network with sess.run (tf.global_variables_initializer ()).

Important: The saver = tf_saver.Saver () must be instantiated before adding new layers to the graph.

This way, when the saver.restore(sess, FLAGS.checkpoint) is performed, it only knows the computation graph prior to creating new layers.

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import os.path

import tensorflow as tf
from tensorflow.contrib import layers
from tensorflow.contrib.slim.python.slim.nets import inception
from tensorflow.python.ops import array_ops
from tensorflow.python.training import saver as tf_saver

slim = tf.contrib.slim
FLAGS = None


def PreprocessImage(image, central_fraction=0.875):
    """Load and preprocess an image.

    Args:
      image: a tf.string tensor with an JPEG-encoded image.
      central_fraction: do a central crop with the specified
        fraction of image covered.
    Returns:
      An ops.Tensor that produces the preprocessed image.
    """

    # Decode Jpeg data and convert to float.
    image = tf.cast(tf.image.decode_jpeg(image, channels=3), tf.float32)

    image = tf.image.central_crop(image, central_fraction=central_fraction)
    # Make into a 4D tensor by setting a 'batch size' of 1.
    image = tf.expand_dims(image, [0])
    image = tf.image.resize_bilinear(image,
                                     [FLAGS.image_size, FLAGS.image_size],
                                     align_corners=False)

    # Center the image about 128.0 (which is done during training) and normalize.
    image = tf.multiply(image, 1.0 / 127.5)
    return tf.subtract(image, 1.0)


def main(args):
    if not os.path.exists(FLAGS.checkpoint):
        tf.logging.fatal(
            'Checkpoint %s does not exist. Have you download it? See tools/download_data.sh',
            FLAGS.checkpoint)
    g = tf.Graph()
    with g.as_default():
        input_image = tf.placeholder(tf.string)
        processed_image = PreprocessImage(input_image)

        with slim.arg_scope(inception.inception_v3_arg_scope()):
            logits, end_points = inception.inception_v3(
                processed_image, num_classes=FLAGS.num_classes, is_training=False)

        predictions = end_points['multi_predictions'] = tf.nn.sigmoid(
            logits, name='multi_predictions')

        sess = tf.Session()

        saver = tf_saver.Saver()

        logits_2 = layers.conv2d(
            end_points['PreLogits'],
            FLAGS.num_classes, [1, 1],
            activation_fn=None,
            normalizer_fn=None,
            scope='Conv2d_final_1x1')

        logits_2 = array_ops.squeeze(logits_2, [1, 2], name='SpatialSqueeze_2')

        predictions_2 = end_points['multi_predictions_2'] = tf.nn.sigmoid(logits_2, name='multi_predictions_2')

        sess.run(tf.global_variables_initializer())

        saver.restore(sess, FLAGS.checkpoint)


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--checkpoint', type=str, default='2016_08/model.ckpt',
                        help='Checkpoint to run inference on.')
    parser.add_argument('--dict', type=str, default='dict.csv',
                        help='Path to a dict.csv that translates from mid to a display name.')
    parser.add_argument('--image_size', type=int, default=299,
                        help='Image size to run inference on.')
    parser.add_argument('--num_classes', type=int, default=6012,
                        help='Number of output classes.')
    parser.add_argument('--image_path', default='test_set/0a9ed4def08fe6d1')
    FLAGS = parser.parse_args()
    tf.app.run()

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

How can I load the weights of some layer of a trained network in a new network in returnn?

分類Dev

How to access and visualize the weights in a pre-trained TensorFlow 2 model?

分類Dev

Using custom trained Yolov3 weights to label new images

分類Dev

Tensorflow returns same weights in hidden layer

分類Dev

How to implement pre-training in Tensorflow? How to partially use saved weights from checkpoint file?

分類Dev

How do I copy specific layer weights from pretrained models using Tensorflow Keras api?

分類Dev

Initialize single layer of a trained keras network and get predictions

分類Dev

How to Create a Trained Keras Model Through Setting the Weights

分類Dev

ImageNet(Inception v3)モデルがAnaconda Tensorflowにありませんか?

分類Dev

Return layer activations and weights from Tensorflow model in separate threads

分類Dev

How to use pre-trained BERT model for next sentence labeling?

分類Dev

How to Use Pre-Trained CNN models in Python

分類Dev

Extract the weights from a TensorFlow graph to use them in Keras

分類Dev

How to get position of edge weights in a networkx graph?

分類Dev

Tensorflow Inception Android

分類Dev

Does dropout layer go before or after dense layer in TensorFlow?

分類Dev

How to apply a trained neural network to write outputs into a csv file?

分類Dev

Pre Trained Models in R Shiny

分類Dev

How can I convert a trained Tensorflow model to Keras?

分類Dev

How to use a previously trained model to get labels of images - TensorFlow

分類Dev

tensorflowとinception-v3を使用した境界ボックス

分類Dev

How to restore libvirt network default configure file?

分類Dev

Restore clock after short powerdown for no-network, no-RTC system

分類Dev

How to load a pre-trained Word2vec MODEL File and reuse it?

分類Dev

How do I change the default download directory for pre-trained model in Keras?

分類Dev

How to apply keras image preprocessing in R when using a pre-trained model

分類Dev

Using pre-trained word embeddings - how to create vector for unknown / OOV Token?

分類Dev

How to find the number of layers from the saved h5 file of pre-trained model?

分類Dev

PyTorch: How to write a neural network that only returns the weights?

Related 関連記事

  1. 1

    How can I load the weights of some layer of a trained network in a new network in returnn?

  2. 2

    How to access and visualize the weights in a pre-trained TensorFlow 2 model?

  3. 3

    Using custom trained Yolov3 weights to label new images

  4. 4

    Tensorflow returns same weights in hidden layer

  5. 5

    How to implement pre-training in Tensorflow? How to partially use saved weights from checkpoint file?

  6. 6

    How do I copy specific layer weights from pretrained models using Tensorflow Keras api?

  7. 7

    Initialize single layer of a trained keras network and get predictions

  8. 8

    How to Create a Trained Keras Model Through Setting the Weights

  9. 9

    ImageNet(Inception v3)モデルがAnaconda Tensorflowにありませんか?

  10. 10

    Return layer activations and weights from Tensorflow model in separate threads

  11. 11

    How to use pre-trained BERT model for next sentence labeling?

  12. 12

    How to Use Pre-Trained CNN models in Python

  13. 13

    Extract the weights from a TensorFlow graph to use them in Keras

  14. 14

    How to get position of edge weights in a networkx graph?

  15. 15

    Tensorflow Inception Android

  16. 16

    Does dropout layer go before or after dense layer in TensorFlow?

  17. 17

    How to apply a trained neural network to write outputs into a csv file?

  18. 18

    Pre Trained Models in R Shiny

  19. 19

    How can I convert a trained Tensorflow model to Keras?

  20. 20

    How to use a previously trained model to get labels of images - TensorFlow

  21. 21

    tensorflowとinception-v3を使用した境界ボックス

  22. 22

    How to restore libvirt network default configure file?

  23. 23

    Restore clock after short powerdown for no-network, no-RTC system

  24. 24

    How to load a pre-trained Word2vec MODEL File and reuse it?

  25. 25

    How do I change the default download directory for pre-trained model in Keras?

  26. 26

    How to apply keras image preprocessing in R when using a pre-trained model

  27. 27

    Using pre-trained word embeddings - how to create vector for unknown / OOV Token?

  28. 28

    How to find the number of layers from the saved h5 file of pre-trained model?

  29. 29

    PyTorch: How to write a neural network that only returns the weights?

ホットタグ

アーカイブ