Get Tensor Variable by Tensor Name – TensorFlow Tutorial

By | June 13, 2019

get tensor by tensor name

If you get a pretrained model, how to read tensor value from it?

You can do like this:

Step 1: Get tensor name from this model

You can read this two tutorials.

List All Trainable and Untrainable Variables in TensorFlow

List All Variables including Constant and Placeholder in TensorFlow

Step 2. Get this tensor value from this model

How to get tensor by its name?

graph.get_tensor_by_name can help you.

Here is an example snippet.

#-*- coding: utf-8 -*-
import numpy as np
import tensorflow as tf

graph = tf.Graph()
with graph.as_default():
    sess = tf.Session()
    with sess.as_default():
        #load graph
        saver = tf.train.import_meta_graph("{}.meta".format(checkpoint_file))
        saver.restore(sess, checkpoint_file)
        
		#read lstm kernel
        lstm_w = graph.get_tensor_by_name("u_sentence/bw/lstm_cell/kernel:0")
        print lstm_w

The output is:

Tensor(“u_sentence/bw/lstm_cell/kernel:0”, shape=(300, 400), dtype=float32_ref)

Leave a Reply