0%

通过加权平均来平滑(smooth)一维数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import matplotlib.pyplot as plt
import numpy as np
import copy

def average_smooth(arr, weights=[1, 2, 3, 5, 3, 2, 1]):
result = copy.copy(arr)

#
# 开始索引:len(weights) // 2
# 结束索引:len(arr) - len(weights)
# 其实就是掐头去尾进行加权平均
#

for i in range(len(weights) // 2, len(arr) - len(weights)):
result[i] = np.average(result[i:i+len(weights)], axis=0, weights=weights)

#
# np.average(result[i:i+len(weights)], axis=0, weights=weights)
# 以上调用的展开其实就是:
# total_weight = np.sum(weights)
# np.sum([arr[i + wi] * weights[wi] for wi in range(len(weights))]) / total_weight
#

return result

if __name__ == '__main__':

# 原始数据
original_data = np.random.random(100)

# 加权平均来平滑数据,消除锯齿
smoothed_data = average_smooth(original_data)

plt.figure()
plt.grid()
plt.plot(original_data)
plt.plot(smoothed_data, 'g')
plt.show()

蓝色为原始数据,绿色是平滑过后的数据
请我喝瓶肥仔快乐水?

欢迎关注我的其它发布渠道