List All Variables including Constant and Placeholder in TensorFlow – TensorFlow Tutorial

By | June 12, 2019

In tutorial ‘List All Trainable and Untrainable Variables in TensorFlow‘, we learn how to list trainable and untrainable variables in tensorflow, however, we can not display constant and placeholder type variable, how to list?

In this tutorial, we write an example to show how to list constant and placehoder variable.

Step 1: Define varaibles.

w_untrain = tf.Variable(tf.random_uniform([2,3], -1, 1), trainable=False, name='w_untrain')

w_train = tf.Variable(tf.random_uniform([2,3], -1, 1), name='w_train')

c_train = tf.constant(np.random.uniform(-1,1,[2,3]), dtype=tf.float32, name='c_train')

input_x = tf.placeholder(tf.int32, [None, 40, 50], name="input_x")

Here c_train is constant, input_x is a placeholder.

Step 2. List all tensorflow nodes

v = [n.name for n in tf.get_default_graph().as_graph_def().node]

Then we can list constant and placeholder.

Here is full example code:

import tensorflow as tf
import numpy as np

w_untrain = tf.Variable(tf.random_uniform([2,3], -1, 1), trainable=False, name='w_untrain')

w_train = tf.Variable(tf.random_uniform([2,3], -1, 1), name='w_train')

c_train = tf.constant(np.random.uniform(-1,1,[2,3]), dtype=tf.float32, name='c_train')

input_x = tf.placeholder(tf.int32, [None, 40, 50], name="input_x")

init = tf.global_variables_initializer() 
init_local = tf.local_variables_initializer()
with tf.Session() as sess:
    sess.run([init, init_local])
    #get all trainable variables
    print 'all node in tensorflow graph'
 
    v = [n.name for n in tf.get_default_graph().as_graph_def().node]
    for vv in v:
        print vv

The result is:

The variables in read rectangle is what we want to list.

Leave a Reply