Tensorflow相当于numpy.diff

Yuv*_*mon 10 python tensorflow

是否有一个等于numpy.diff的张量

计算沿给定轴的第n个离散差.

对于我的项目,我只需要n = 1

Yar*_*tov 11

试试这个:

def tf_diff_axis_0(a):
    return a[1:]-a[:-1]

def tf_diff_axis_1(a):
    return a[:,1:]-a[:,:-1]
Run Code Online (Sandbox Code Playgroud)

去检查:

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)))
Run Code Online (Sandbox Code Playgroud)


Fra*_*urt 6

我不认为 TensorFlow 有与 numpy.diff 等效的东西,所以你必须实现它,这应该不难,因为numpy.diff只是切片和减法:

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]
Run Code Online (Sandbox Code Playgroud)