Here's what I came up with for 3d arrays thanks to @Bernat Gene
def tf_gradient_3d(a):
#*axis = 1
left = tf.concat([a[:,1:], tf.expand_dims(a[:,-1],1)], axis = 1)
right = tf.concat([tf.expand_dims(a[:,0],1), a[:,:-1]], axis = 1)
ones = tf.ones_like(right[:, 2:], tf.float64)
one = tf.expand_dims(ones[:,0], 1)
dx = tf.concat((one, ones*2, one), 1)
gx = (left - right )/dx
#* axis = 0
left = tf.concat([a[1:,:], tf.expand_dims(a[-1,:],0)], axis = 0)
right = tf.concat([tf.expand_dims(a[0,:],0), a[:-1,:]], axis = 0)
ones = tf.ones_like(right[2:], tf.float64)
one = tf.expand_dims(ones[0], 0)
dx = tf.concat((one, ones*2, one), 0)
gy = (left - right )/dx
# *axis = 2
left = tf.concat([a[:,:,1:], tf.expand_dims(a[:,:,-1],2)], axis = 2)
right = tf.concat([tf.expand_dims(a[:,:,0],2), a[:,:,:-1]], axis = 2)
ones = tf.ones_like(right[:, :, 2:], tf.float64)
one = tf.expand_dims(ones[:,:,0], 2)
dx = tf.concat((one, ones*2, one), 2)
gz = (left - right )/dx
return gx, gy, gz
hope it helps :)
p.s: what actually happens is something like this:
grad[0] = (vals[1] - vals[0]) / dx;
grad[i] = (vals[i+1] - vals[i-1]) / (2*dx); // for i in [1,N-2]
grad[N-1] = (vals[N-1] - vals[N-2]) / dx;
but you need to convert this formula suitable for Tensorflow.