python - 使用 numpy 提高阶跃函数的分辨率

标签 python arrays numpy interpolation

我有一个由 delta 函数(0 或 1)组成的数组。我使用此函数通过应用前向填充算法来生成阶跃函数数组。这个数组是我进行某项操作所需的数组。

此图显示增量和阶跃数组:

enter image description here

但是,我需要增加该数组的分辨率才能执行该操作。但是,我不能直接应用像 numpy.interp 这样的东西

enter image description here

这扭曲了原来的功能。

因此我的问题是哪种是提高阶跃函数分辨率的有效(和Pythonic方式)?

这是一个示例脚本:

import matplotlib.pyplot as plt
import numpy as np

def forward_filling(arr):
    idx=np.where(arr==0,0,np.arange(len(arr)))    
    idx=np.maximum.accumulate(idx)    
    return arr[idx]

fig, axis = plt.subplots(1, 1)  

x_array = np.arange(0, 15)
y_delta = np.zeros(len(x_array))
y_delta[3], y_delta[7], y_delta[13] = 1, 2, 3
step_function = forward_filling(y_delta)

axis.plot(x_array, y_delta, label='delta function', marker='o')
axis.plot(x_array, step_function, label='step function')

x_high_resolution = np.linspace(0, 15, 30)

delta_interpolated  = np.interp(x_high_resolution, x_array, y_delta)
step_interpolated   = np.interp(x_high_resolution, x_array, step_function)

axis.plot(x_high_resolution, delta_interpolated, label='delta function high resolution', marker='o')
axis.plot(x_high_resolution, step_interpolated, label='step function high resolution')

axis.legend()

axis.set_xlabel('x')
axis.set_ylabel('y')

plt.show()

最佳答案

正如我想的那样,您希望将 y 值保留在每个给定 y 值的邻域中,您可以使用列表理解“替换”每个 y 值,例如 3 个相同值:

step_function_hi_res = np.array([np.repeat(step,3) for step in step_function]).flatten()

然后像您已经做的那样对 x 值进行更改:

x_high_resolution = np.linspace(0, len(step_function),len(step_function)*3)

关于python - 使用 numpy 提高阶跃函数的分辨率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44639883/

相关文章:

python - 了解subprocess.TimeoutExpired,想在超时发生后杀死一个子进程

php - 双 tr 数组

python - 在python中打印出数组中的模式

python - 如何从列表中查找和删除图像的重叠切片?

python - Django:如何在模板的 if 语句中使用变量?

python - 使用 imagekit 和 opencv 创建视频缩略图

c - uint8_t数组的可变大小

python - python 中用于 nd 数组的逻辑索引

python - 识别 pandas 中具有稀疏 nan 的时间序列中的数据组

python - 将元组列表转换为 numpy 数组