3

I am trying to assign values to slice of a variable in tensorflow, but the following error is shown: 'ValueError: Sliced assignment is only supported for variables'. Why is this error showing even though I am trying to do slice assignment to a variable. My code is something like this:

var1 = var1[startx:endx,starty:endy].assign(tf.ones([endx-startx,endy-starty],dtype=tf.int32))

where var1 is a tensorflow variable.

E_net4
  • 27,810
  • 13
  • 101
  • 139
user5112616
  • 91
  • 1
  • 4
  • Can you show the code that created `var1`? Also please post the output of `print(var1); print(type(var1))`. – a_guest Oct 15 '18 at 21:04
  • Welcome to Stack Overflow! Can you show us how exactly `var1` is originally defined? Or at least something that reproduces the exact same error? By creating a proper [MCVE], it will be much easier to answer this question. – E_net4 Oct 15 '18 at 21:04
  • @a_guest It doesn't matter if `var1` was correctly instantiated by a variable node or not -- the slicing op already causes this error. (Of course there may be more problems outside of the snippet given, as well!) – zephyrus Oct 15 '18 at 21:14
  • Since you are assigning the `assign` op back to `var1` I suspect that you've done this before already and `var1` now holds an assign operation. Note that this assign happens in-place and does not return a new tensor object. So assigning back to the same name doesn't make sense actually. – a_guest Oct 15 '18 at 22:03

2 Answers2

2

The other answer is correct; doing any operation to a tf variable does not (always) return a tf variable. So if you're chaining assignments, use explicit control dependencies:

v = tf.Variable(...)
with tf.control_dependencies([v[...].assign(...)]):
  return v[...].assign(...)
Alexandre Passos
  • 5,186
  • 1
  • 14
  • 19
1

Once var1 is sliced it is no longer a variable.

The numpy style slicing notation (tensor[a:b]) is just shorthand for the longer tensorflow notation tf.slice(tensor, a, a+b) which outputs a new tensor operation on the graph (see https://www.tensorflow.org/api_docs/python/tf/slice).

The graph you are trying to make looks like (with tensor output types indicated in parentheses):

Var1 (tf.Variable) -> tf.slice (tf.Tensor) tensor -> tf.assign (tf.Variable).

Since assign only works on tf.Variable objects, it can't work on the output of the slice op.

zephyrus
  • 1,266
  • 1
  • 12
  • 29