Is there a tensorflow equivalent to numpy.diff?
Calculate the n-th discrete difference along given axis.
For my project I only need n=1
NumPy and TensorFlow are actually very similar in many respects. Both are, essentially, array manipulation libraries, built around the concept of tensors (or nd-arrays, in NumPy terms).
Tensorflow can't do much magic to be better (while guaranteeing same accuracy). Tensorflow is consistently much slower than Numpy in my tests.
diff() function calculates the difference between subsequent values in a NumPy array. For example, np. diff([1, 2, 4]) returns the difference array [1 2] .
numpy has a function called numpy. diff() that is similar to the one found in matlab. It calculates the differences between the elements in your list, and returns a list that is one element shorter, which makes it unsuitable for plotting the derivative of a function.
Try this:
def tf_diff_axis_0(a):
return a[1:]-a[:-1]
def tf_diff_axis_1(a):
return a[:,1:]-a[:,:-1]
To check:
import numpy as np
import tensorflow as tf
x0=np.arange(5)+np.zeros((5,5))
sess = tf.Session()
np.diff(x0, axis=0) == sess.run(tf_diff_axis_0(tf.constant(x0)))
np.diff(x0, axis=1) == sess.run(tf_diff_axis_1(tf.constant(x0)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With