如何在 scipy 中使用统一过滤器设置不同的步幅?
How to set different stride with uniform filter in scipy?
我正在使用以下代码运行对我的数据进行统一过滤:
from scipy.ndimage.filters import uniform_filter
a = np.arange(1000)
b = uniform_filter(a, size=10)
过滤器现在似乎可以像将步幅设置为大小 // 2 一样工作。
如何调整代码让filter的stride不是一半大小?
您似乎误解了 uniform_filter
在做什么。
在这种情况下,它创建一个数组 b
,用以 a[i]
为中心的大小为 10
的块的平均值替换每个 a[i]
。所以,像这样:
for i in range(0, len(a)): # for the 1D case
b[i] = mean(a[i-10//2:i+10//2]
请注意,这会尝试访问索引在 0..1000 范围之外的值。在默认情况下,uniform_filter
假设位置 0 之前的数据只是其后数据的反映。最后也是如此。
另请注意 b
使用与 a
相同的类型。在a
为整数类型的示例中,均值也会按整数计算,这会导致一些精度损失。
这里有一些代码和图表来说明正在发生的事情:
import matplotlib.pyplot as plt
import numpy as np
from scipy.ndimage.filters import uniform_filter
fig, axes = plt.subplots(ncols=2, figsize=(15,4))
for ax in axes:
if ax == axes[1]:
a = np.random.uniform(-1,1,50).cumsum()
ax.set_title('random curve')
else:
a = np.arange(50, dtype=float)
ax.set_title('values from 0 to 49')
b = uniform_filter(a, size=10)
ax.plot(a, 'b-')
ax.plot(-np.arange(0, 10)-1, a[:10], 'b:') # show the reflection at the start
ax.plot(50 + np.arange(0, 10), a[:-11:-1], 'b:') # show the reflection at the end
ax.plot(b, 'r-')
plt.show()
我正在使用以下代码运行对我的数据进行统一过滤:
from scipy.ndimage.filters import uniform_filter
a = np.arange(1000)
b = uniform_filter(a, size=10)
过滤器现在似乎可以像将步幅设置为大小 // 2 一样工作。 如何调整代码让filter的stride不是一半大小?
您似乎误解了 uniform_filter
在做什么。
在这种情况下,它创建一个数组 b
,用以 a[i]
为中心的大小为 10
的块的平均值替换每个 a[i]
。所以,像这样:
for i in range(0, len(a)): # for the 1D case
b[i] = mean(a[i-10//2:i+10//2]
请注意,这会尝试访问索引在 0..1000 范围之外的值。在默认情况下,uniform_filter
假设位置 0 之前的数据只是其后数据的反映。最后也是如此。
另请注意 b
使用与 a
相同的类型。在a
为整数类型的示例中,均值也会按整数计算,这会导致一些精度损失。
这里有一些代码和图表来说明正在发生的事情:
import matplotlib.pyplot as plt
import numpy as np
from scipy.ndimage.filters import uniform_filter
fig, axes = plt.subplots(ncols=2, figsize=(15,4))
for ax in axes:
if ax == axes[1]:
a = np.random.uniform(-1,1,50).cumsum()
ax.set_title('random curve')
else:
a = np.arange(50, dtype=float)
ax.set_title('values from 0 to 49')
b = uniform_filter(a, size=10)
ax.plot(a, 'b-')
ax.plot(-np.arange(0, 10)-1, a[:10], 'b:') # show the reflection at the start
ax.plot(50 + np.arange(0, 10), a[:-11:-1], 'b:') # show the reflection at the end
ax.plot(b, 'r-')
plt.show()