Greetings, I am relatively new to pytorch (also not very familiar with manipulating tensors) and I am trying to implement a function with the same behavior as numpy.diff
(https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.diff.html). I would like that this function works only with torch Tensors. After looking at the documentation, it doesn’t seems like pytorch as a function that have the same behavior… Is there an equivalent function that I missed ? if None exist, how would your implement such function ?
Ultimately, I am trying to implement a loss function weighted by Mean Directional Accuracy (MDA)(https://en.wikipedia.org/wiki/Mean_Directional_Accuracy).
For example, the numpy version of it is as follows:
def diff(a, n=1, axis=-1):
if n == 0:
return a
if n < 0:
raise ValueError(
"order must be non-negative but got " + repr(n))
a = asanyarray(a)
nd = a.ndim
axis = normalize_axis_index(axis, nd)
slice1 = [slice(None)] * nd
slice2 = [slice(None)] * nd
slice1[axis] = slice(1, None)
slice2[axis] = slice(None, -1)
slice1 = tuple(slice1)
slice2 = tuple(slice2)
op = not_equal if a.dtype == np.bool_ else subtract
for _ in range(n):
a = op(a[slice1], a[slice2])
return a
>>> x = np.array([1, 2, 4, 7, 0])
>>> np.diff(x)
#array([ 1, 2, 3, -7])