How to get tensorflow tensor model wanted

When we want to transform or use a pre-training model to accomplish some other task, a common and necessary action is taken from the specified model to tensor we are interested in (tensor).

For example, I want to use an already trained a result of one intermediate good as CNN model feature vectors related tasks to complete another, we need such operations.

How to do it? Very simple, just two steps:

1. Get to interest tensor name.

2. Use the function to get get_tensor_by_name

Detailed below under

1. Get to interest tensor name

We know that the tensor tensor is obtained by the operation operation operation.

So in fact, you have to do is to get to be able to generate the tensor op name you want, no matter what method you use.

Typically, there are two ways to get to op_name.

1) If the model is to build your own, you can directly view the source code to build the network to confirm op_name.

Thus, for op critical meaning, when you create a custom for a suitable name, or create scope packet is a good coding habits.

2) If you get no idea of ​​the model, reference and modify the following code to print out all the information tensor

with tf.Graph().as_default():
    config = tf.ConfigProto()
    sess = tf.Session(config = config)
    with sess.as_default():
        meta_path = checkpoint_path + '.meta'
        saver = tf.train.import_meta_graph(meta_path)
        saver.restore(sess, checkpoint_path)

        op_list = sess.graph.get_operations()
        for op in op_list:
            print(op.name)
            print(op.values())

The above output code similar to the following results:

...
...
resnet_v1_50/pool5
(<tf.Tensor 'resnet_v1_50/pool5:0' shape=(?, 1, 1, 2048) dtype=float32>,)
Logits/Squeeze
(<tf.Tensor 'Logits/Squeeze:0' shape=(?, 2048) dtype=float32>,)
...
...

The rest have to do is based on your understanding of the model structure, find what you want tensor corresponding op_name.

For example, I want tensor is after the last pooling layer resnet50 model smoothing, corresponding op_name as 'Logits / Squeeze: 0'

2. Use get_tensor_by_name function to get the desired amount of sheets

Get to the op_name, the remaining thing is just to get it calls get_tensor_by_name function, for example:

embedding = tf.get_default_graph().get_tensor_by_name('Logits/Squeeze:0')
Published 87 original articles · won praise 325 · views 520 000 +

Guess you like

Origin blog.csdn.net/u011583927/article/details/90668687