Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tensorflow equivalent to numpy.diff

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

like image 410
Yuval Atzmon Avatar asked Mar 05 '17 14:03

Yuval Atzmon


People also ask

Is TensorFlow similar to NumPy?

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).

Is NumPy faster than TensorFlow?

Tensorflow can't do much magic to be better (while guaranteeing same accuracy). Tensorflow is consistently much slower than Numpy in my tests.

What is diff () in NumPy give example?

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] .

Is NumPy diff the derivative?

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.


1 Answers

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)))
like image 179
Yaroslav Bulatov Avatar answered Sep 21 '22 21:09

Yaroslav Bulatov