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.
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.
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(...)