np.滚动与scipy.interpolation.shiftDispreparency对于整数移位值

2024-04-25 09:56:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一些代码来移动数组,并试图使用scipy.ndimage中的“shift”函数将其泛化以处理非整数移位。数据是循环的,因此结果应该是环绕的,就像np.roll命令所做的那样。在

但是,scipy.ndimage.shift似乎没有正确地包装整数移位。以下代码片段显示了差异:

import numpy as np
import scipy.ndimage as sciim
import matplotlib.pyplot as plt 

def shiftfunc(data, amt):
    return sciim.interpolation.shift(data, amt, mode='wrap', order = 3)

if __name__ == "__main__":
    xvals = np.arange(100)*1.0

    yvals = np.sin(xvals*0.1)

    rollshift   = np.roll(yvals, 2)

    interpshift = shiftfunc(yvals, 2)

    plt.plot(xvals, rollshift, label = 'np.roll', alpha = 0.5)
    plt.plot(xvals, interpshift, label = 'interpolation.shift', alpha = 0.5)
    plt.legend()
    plt.show()

roll vs shift

可以看出,前两个值差异很大,而其他值都很好。我怀疑这是使用wrap选项时预滤波和插值操作的实现错误。一种解决方法是修改shiftfunc以恢复到np.滚动当shift值是一个整数,但这不令人满意。在

我是不是遗漏了一些明显的东西?在

有没有办法使ndimage.shiftnp.roll一致?在


Tags: 代码importshiftasnpplt整数scipy
1条回答
网友
1楼 · 发布于 2024-04-25 09:56:06

我不认为换档功能有什么问题。当你使用roll时,你需要切掉一个额外的元素来进行公平的比较。请参阅下面的代码。在

import numpy as np
import scipy.ndimage as sciim
import matplotlib.pyplot as plt 


def shiftfunc(data, amt):
    return sciim.interpolation.shift(data, amt, mode='wrap', order = 3)

def rollfunc(data,amt):
    rollshift   = np.roll(yvals, amt)
    # Here I remove one element (first one before rollshift) from the array 
    return np.concatenate((rollshift[:amt], rollshift[amt+1:]))

if __name__ == "__main__":
    shift_by = 5
    xvals = np.linspace(0,2*np.pi,20)
    yvals = np.sin(xvals)
    rollshift   = rollfunc(yvals, shift_by)
    interpshift = shiftfunc(yvals,shift_by)
    plt.plot(xvals, yvals, label = 'original', alpha = 0.5)
    plt.plot(xvals[1:], rollshift, label = 'np.roll', alpha = 0.5,marker='s')
    plt.plot(xvals, interpshift, label = 'interpolation.shift', alpha = 0.5,marker='o') 
    plt.legend()
    plt.show()

结果

enter image description here

相关问题 更多 >