3

Ok, so following scenario: I have a variable var whose rank is fixed but whose shape is not. For example, it could be a 1D-tensor of arbitrary length. I want to initialize var once at the beginning of a session with my graph. I use a placeholder that is attached to this variable to do this (see also in the code below). Then I do some computations in my graph and at some point I need to extract, say, all values greater than 0 from var, like so:

import tensorflow as tf    

init_var = tf.placeholder(dtype=tf.float64, shape=[None])
var = tf.Variable(init_var,dtype=tf.float64,validate_shape=False)
booled = tf.boolean_mask(var, var>0)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer(), { init_var: [1,-2,3] } )
    print sess.run([booled])

But this yields the ValueError-Exception:

ValueError: Number of mask dimensions must be specified, 
even if some dimensions are None. 
E.g. shape=[None] is ok, but shape=None is not.

Now, this exception goes away if I set validate_shape to True but then I'd need to fix the shape of var at graph construction time but I want it to be dynamic. Nevertheless, if anyone knows how to either evaluate boolean masks on variables of unvalidated shape OR how to reinitialize the shape of var each session (maybe without reconstructing the whole graph), I'd much appreciate it.

1 Answer 1

3

Ok I solved it meanwhile and it turns out that the solution is incredibly simple. While it seems to be impossible to specify a shape with 'None' entries when defining a variable (and thus to specify just its rank), it is possible to do it right after with var.set_shape() like so:

import tensorflow as tf    

init_var = tf.placeholder(dtype=tf.float64, shape=[None])
var = tf.Variable(init_var,dtype=tf.float64,validate_shape=False)
var.set_shape([None])
booled = tf.boolean_mask(var, var>0)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer(), { init_var: [1,-2,3] } )
    print sess.run([booled])

Now it runs fantastically right into the arms of my expectation!

1
  • var.set_shape([None]) sure did solve my problem with boolean_mask.
    – Ébe Isaac
    Mar 25, 2018 at 6:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.