rd11 February 2016

How can we replace a single element in an n-D Tensor in TensorFlow?

If we have a 1-D Tensor, we can replace a single element with a 0-D Tensor by using tf.scatter_update or by unpacking, replacing, packing.

Example:

# Pretend x came from somewhere useful.
x = tf.Variable(0)
A = tf.Variable([1, 2, 3])
# Replace the 2 with whatever's in x
A = tf.scatter_update(A, 1, x)

A will now produce [1, 0, 3].

Is it possible to do this with n-D arrays?

Example:

# Pretend x came from somewhere useful.
x = tf.Variable(0, dtype=tf.float32)
A = tf.Variable(np.random.rand(3, 3, 3, 3))
# What's the equivalent of A[1, 1, 1, 1] = x ?

I think I could get the desired result with a mixture of tf.unpack, tf.scatter_update, and tf.pack, but it'd be verbose, and we'd be replacing a (potentially large) 3-D Tensor instead of just replacing a tiny 0-D Tensor. Is there a better way?

Answers


Paul Tucker February 2016

If you want to do this efficiently, I believe you will need to write a new Op or generalize scatter_update.

Post Status

Asked in February 2016
Viewed 3,684 times
Voted 12
Answered 1 times

Search




Leave an answer