3

I ma trying to understand tf.rank function in tensorflow. From the documentation here, I understood that rank should return the number of distinct elements in the tensor.

Here x and weights are 2 distinct 2*2 tensors with 4 distinct elemnts in each of them. However, rank() function outputs are:

Tensor("Rank:0", shape=(), dtype=int32) Tensor("Rank_1:0", shape=(), dtype=int32)

Also, for the tensor x, I used tf.constant() with dtype = float to convert ndarray into float32 tensor but the rank() still outputs as int32.

g = tf.Graph()
with g.as_default():
    weights = tf.Variable(tf.truncated_normal([2,2]))
    x = np.asarray([[1 , 2], [3 , 4]])
    x = tf.constant(x, dtype = tf.float32)
    y = tf.matmul(weights, x)
    print (tf.rank(x), tf.rank(weights))


with tf.Session(graph = g) as s:
    tf.initialize_all_variables().run()
    print (s.run(weights), s.run(x))
    print (s.run(y))

How should I interpret the output.

Abhi
  • 1,153
  • 1
  • 23
  • 38

1 Answers1

4

Firstly, tf.rank returns the dimension of a tensor, not the number of elements. For instance, the output from tf.rank called for the 2x2 matrix would be 2.

To print the rank of a tensor, create an appropriate node, e.g. rank = tf.rank(x) and then evaluate this node using a Session.run(), as you've done for weights and x. Execution of print (tf.rank(x), tf.rank(weights)) expectedly prints out description of tensors, as tf.rank(x), tf.rank(weights) are nodes of the graph, not the variables with defined values.

Dmitriy Danevskiy
  • 3,119
  • 1
  • 11
  • 15
  • Thanks Danevskyi. That makes sense. I think I need to run it as part of session.run(). Getting used to tensorflow – Abhi Oct 23 '16 at 02:50