简体   繁体   中英

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

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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM