Tensor flow is equivalent to numpy.diff

Is there a tensor flow equivalent to numpy.diff ?

Calculate the nth discrete difference along a given axis.

For my project, I only need n = 1

+6
source share
2 answers

Try the following:

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))) 
+6
source

I don't think TensorFlow has the equivalent of numpy.diff, so you have to implement it, which should not be difficult, since numpy. diff is just slicing and subtracting:

 def diff(a, n=1, axis=-1): '''(as implemented in NumPy v1.12.0)''' if n == 0: return a if n < 0: raise ValueError( "order must be non-negative but got " + repr(n)) a = asanyarray(a) nd = len(a.shape) slice1 = [slice(None)]*nd slice2 = [slice(None)]*nd slice1[axis] = slice(1, None) slice2[axis] = slice(None, -1) slice1 = tuple(slice1) slice2 = tuple(slice2) if n > 1: return diff(a[slice1]-a[slice2], n-1, axis=axis) else: return a[slice1]-a[slice2] 
+2
source

Source: https://habr.com/ru/post/1015495/


All Articles