移动平均
简单移动平均(sma)
def moving_average(f_t):
if type(f_t) is not np.ndarray:
raise TypeError\
('Expected one dimensional numpy array.')
if f_t.shape[1] != 1:
raise IndexError\
('Expected one dimensional numpy array, %d dimensions given.' % (f_t.shape[1]))
f_t = f_t.flatten()
window = 5
mode = 'same'
g_t = np.ones(int(window))/float(window) # array([0.2, 0.2, 0.2, 0.2, 0.2])
# Deal with boundaries with atleast lag/2 day window
# ma = np.convolve(f_t,g_t,mode)
# ma = np.convolve(f_t,g_t,mode)[window-1:-window+1]
ma = np.convolve(f_t,g_t)[window-1:-window+1] #numpy卷积实现
return ma
执行结果:

蓝色是原始数据,棕色是经过移动平均算法弱化后的数据。
也可以使用pandas的DataFrame的rolling函数实现:
# df[<metric>].rolling(5).mean()
# 使用移动平均平滑季节性成分
window_size = 12 # 比如使用一天的窗口大小
smoothed_ts = pd.Series(ts).rolling(window=window_size, center=True).mean()
plt.figure(figsize=(16, 6))
plt.plot(ts[:288*2], label='构造的毛刺数据')
plt.plot(smoothed_ts[:288*2], label='移动平均后的数据')
plt.title("两天数据对比", fontproperties=zhfont, fontsize=12)
plt.grid()
plt.legend()

指数加权移动平均(ewma)
指数加权(exponentially weighted)的权重通过指数函数计算得到,越近期的数据具有越小的衰减因子(decay factor),对应更大的权重。

# 根据质心指定衰减参数
ewma1 = pd.Series.ewm(series, ignore_na=False, min_periods=0, adjust=True, com=1).mean()
ewma2 = pd.Series.ewm(series, ignore_na=False, min_periods=0, adjust=True, com=2).mean()
ewma5 = pd.Series.ewm(series, ignore_na=False, min_periods=0, adjust=True, com=5).mean()
plt.figure(figsize=(20,8))
plt.plot(v,label='raw')
plt.plot(ewma1,label='ewma1')
plt.plot(ewma2,label='ewma2')
plt.plot(ewma5,label='ewma5')
plt.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
plt.legend()
# plt.gca().yaxis.set_major_formatter(mticker.FormatStrFormatter('%.2f mbps'))
plt.show()

rolling是简单移动平均;
可以看出com值越小,衰减因子α越大,相同位置的真实值对应权重越小,则最终加权移动平均效果越接近真实值。
卷积运算
2018-08-07 补充
import numpy as np
from matplotlib import pyplot as plt
def moving_average(array, window=3):
N = window
n=np.ones(N)
weights=n/N
sma=np.convolve(weights,array)[N-1:-N+1]
t=np.arange(N-1,len(array))
plt.plot(t,array[N-1:],lw=1)
plt.plot(t,sma,lw=2)
plt.show()
return sma
numpy.convolve(weights,array)[N-1:-N+1] weight = [a,b,c] array = [i,j,k,m,n] Result: [ai, bi+aj, ci+bj+ak, cj+bk+am, ck+bm+an, cm+bn, cn][N-1:-N+1]

参考:https://www.cnblogs.com/21207-iHome/p/6231607.html
参考:https://docs.scipy.org/doc/numpy/reference/generated/numpy.convolve.html
作者:Standby — 一生热爱名山大川、草原沙漠,还有我们小郭宝贝!
出处:http://www.cnblogs.com/standby/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处:http://www.cnblogs.com/standby/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

浙公网安备 33010602011771号