您似乎误解了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()