未验证 提交 39e8b023 编写于 作者: X Xavier ZXY 提交者: GitHub

[API Enhancement] No.1 support the any number of times in paddle.diff [used AI Studio] (#56681)

* Fix: The number of times to recursively compute the difference supports any number

* Fix: use pre-commit to format code
上级 d825e232
...@@ -5565,7 +5565,14 @@ def diff(x, n=1, axis=-1, prepend=None, append=None, name=None): ...@@ -5565,7 +5565,14 @@ def diff(x, n=1, axis=-1, prepend=None, append=None, name=None):
[[1, 1], [[1, 1],
[1, 1]]) [1, 1]])
""" """
if n < 1:
raise ValueError(
"Diff expects input to be at least one-dimensional but got {}".format(
n
)
)
def _diff_handler(x, n=1, axis=-1, prepend=None, append=None, name=None):
if axis < 0: if axis < 0:
axis = axis + len(x.shape) axis = axis + len(x.shape)
if axis > len(x.shape): if axis > len(x.shape):
...@@ -5685,6 +5692,16 @@ def diff(x, n=1, axis=-1, prepend=None, append=None, name=None): ...@@ -5685,6 +5692,16 @@ def diff(x, n=1, axis=-1, prepend=None, append=None, name=None):
out = paddle.tensor.math.subtract(input_back, input_front) out = paddle.tensor.math.subtract(input_back, input_front)
return out return out
out = _diff_handler(
x, n=1, axis=axis, prepend=prepend, append=append, name=name
)
if n > 1:
for _ in range(n - 1):
out = _diff_handler(
out, n=1, axis=axis, prepend=prepend, append=append, name=name
)
return out
def angle(x, name=None): def angle(x, name=None):
r""" r"""
......
...@@ -145,6 +145,15 @@ class TestDiffOp(unittest.TestCase): ...@@ -145,6 +145,15 @@ class TestDiffOp(unittest.TestCase):
self.func_grad() self.func_grad()
class TestDiffOpN(TestDiffOp):
def set_args(self):
self.input = np.array([1, 4, 5, 2]).astype('float32')
self.n = 2
self.axis = 0
self.prepend = None
self.append = None
class TestDiffOpAxis(TestDiffOp): class TestDiffOpAxis(TestDiffOp):
def set_args(self): def set_args(self):
self.input = np.array([[1, 4, 5, 2], [1, 5, 4, 2]]).astype('float32') self.input = np.array([[1, 4, 5, 2], [1, 5, 4, 2]]).astype('float32')
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册