0

I am new in tensorflow and have a question about tf.rank method.

In the doc https://www.tensorflow.org/api_docs/python/tf/rank there is a simple example about the tf.rank:

# shape of tensor 't' is [2, 2, 3]
t = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]])
tf.rank(t)  # 3

But when I run the code below:

t = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]])
print(tf.rank(t))  # 3

I get output like:

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

Why can I get the output of "3"?

niu yi
  • 327
  • 1
  • 2
  • 6
  • 2
    Possible duplicate of [tf.rank function in Tensorflow](https://stackoverflow.com/questions/40195549/tf-rank-function-in-tensorflow) – Venki WAR May 08 '18 at 05:18
  • `tf.rank(t)` creates a tensor that evaluates the rank. Using the python `print` function does not tell you the value of this tensor. You have to `sess.run()` to evaluate its value. – Ferran Parés May 08 '18 at 06:32
  • I would suggest to create a TF node `rank = tf.rank(t)` and evaluate this node by running a Session. – picnix_ May 08 '18 at 06:32

1 Answers1

0

As I said in the comments of this question, tf.rank(t) creates a tensor in charge of evaluating the rank of tensor t. If you use the python print() function, it just prints information about the tensor itself.

Let's assign the tf.rank(t) tensor to a variable rank (as suggested by @Picnix_) and evaluate its value under a tf.Session():

import tensorflow as tf

t = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]])
rank = tf.rank(t)

with tf.Session() as sess:
    rank_value = sess.run(rank)
    print(rank_value)  # Outputs --> 3

So, rank_value is the variable containing the value of tensor rank, and as documentation suggest its value is 3. Hope this puts some light on how tensorflow works.

Ferran Parés
  • 636
  • 3
  • 11