numba np.diff 轴=0

numba np.diff with axis=0

在使用 numba 时,axis=0np.sum() 可接受的参数,但 np.diff() 不可接受。为什么会这样?我正在使用 2D,因此需要轴规范。

@jit(nopython=True)
def jitsum(y):
    np.sum(y, axis=0)

@jit(nopython=True)
def jitdiff(y): #this one will cause error
    np.diff(y, axis=0)

错误:np_diff_impl() got an unexpected keyword argument 'axis'

2D 中的解决方法是:

@jit(nopython=True)
def jitdiff(y):
    np.diff(y.T).T
def sum(y):
    a=np.sum(y, axis=0)
    b=np.sum(y,axis=1)
    print("Sum along the rows (axis=0):",a)
    print("Sum along the columns (axis=1):",b)

def diff_order1(y):
    a=np.diff(y,axis=0,n=1)
    b=np.diff(y,axis=1,n=1) ## n=1 indicates 1st order difference 
    print("1st order difference along the rows (axis=0):",a)
    print("1st order difference along the columns (axis=1):",b)

def diff_order2(y):
    a=np.diff(y,axis=0,n=2)
    b=np.diff(y,axis=1,n=2) ## n=2 indicates 2nd order difference 
    print("2nd order difference along the rows (axis=0):",a)
    print("2nd order difference along the columns (axis=1):",b)

此函数只是解决为 2 阶差异调用 .diff 函数两次的问题的另一个版本

def diff_order2_v2(y):
  a=np.diff(np.diff(y,axis=1),axis=1)
  b=np.diff(np.diff(y,axis=0),axis=0)
  print("2nd order difference along the rows (axis=0):",a)
  print("2nd order difference along the columns (axis=1):",b)

尝试 运行 这段代码,我尝试为一阶和二阶差分创建求和函数和差分函数。

np.diff 在具有 n=1 的二维数组上,axis=1 只是

a[:, 1:] - a[:, :-1]

对于axis=0

a[1:, :] - a[:-1, :]

我怀疑上面的行可以用 numba 编译得很好。