Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

324
Views
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

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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)))
over 4 years ago · Santiago Trujillo Report

0

I don't think TensorFlow has an equivalent to numpy.diff, so you'll have to implement it, which shouldn't difficult as numpy.diff simply slices and subtractes:

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]
over 4 years ago · Santiago Trujillo Report

0

Starting in Tensorflow 2.4, you may use tf.experimental.numpy.diff.

Note that there are unsupported arguments: prepend and append.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!