Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tf.rank function in Tensorflow

Tags:

tensorflow

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.

like image 689
Abhi Avatar asked Feb 06 '26 21:02

Abhi


1 Answers

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.

like image 172
Dmitriy Danevskiy Avatar answered Feb 08 '26 22:02

Dmitriy Danevskiy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!