I'm trying to construct a single tensor using values from two different tensors and an array of two dimensional indices, in a manner compatible with TensorFlow autodiff.
In a first step I want to extract the elements of a tensor D
of shape (n,n)
whose values are the same as those in another tensor a
. In particular, I'm looking for a better way to implement the following loop:
a = []
for i in range(len(f)):
a.append(tf.where(tf.experimental.numpy.isclose(f[I], D, atol=1e-6))[0])
P_x = tf.gather(D,a)
In the append step, I'm just using the first instance where the values are equal because the function I'm interested in is independent of this choice. I need to use isclose because the two arrays are float32 arrays and are not exactly equal to one another.
Then in a second step I want to combine P_x
with P_y = tf.gather(g, indices)
to construct a tensor P
. Assume that P_x
and P_y
are both of shape (n, )
. Then,
P = [[P_x[0], P_y[0]],[P_x[1], P_y[1]], ..., [P_x[n], P_y[n]] ]
I'm pretty new to TensorFlow, so despite looking through the docs I don't see a way to do all of these operations using gather, scatter etc., which seems to be necessary to make autodiff work. When I use loops and other methods, I get gradients = none.
For the first step, you can reduce the loop into matrix operation by finding the closest match using
broadcasting
.Example:
numpy.is_close() operation
Gather D close to a: