我正在浏览这个网站,以了解有关指数平滑平均值的更多信息,但不确定代码的1个部分。
import pandas, numpy as np
ewma = pandas.stats.moments.ewma
# make a hat function, and add noise
x = np.linspace(0,1,100)
x = np.hstack((x,x[::-1]))
x += np.random.normal( loc=0, scale=0.1, size=200 )
plot( x, alpha=0.4, label='Raw' )
# take EWMA in both directions with a smaller span term
fwd = ewma( x, span=15 ) # take EWMA in fwd direction
bwd = ewma( x[::-1], span=15 ) # take EWMA in bwd direction
c = np.vstack(( fwd, bwd[::-1] )) # lump fwd and bwd together
c = np.mean( c, axis=0 ) # average
# regular EWMA, with bias against trend
plot( ewma( x, span=20 ), 'b', label='EWMA, span=20' )
# "corrected" (?) EWMA
plot( c, 'r', label='Reversed-Recombined' )
我不能得到的是本节
# take EWMA in both directions with a smaller span term
fwd = ewma( x, span=15 ) # take EWMA in fwd direction
bwd = ewma( x[::-1], span=15 ) # take EWMA in bwd direction
c = np.vstack(( fwd, bwd[::-1] )) # lump fwd and bwd together
c = np.mean( c, axis=0 ) # average
有人可以请解释这里发生了什么吗?
网站的完整来源是:http://connor-johnson.com/2014/02/01/smoothing-with-exponentially-weighted-moving-averages/
答案 0 :(得分:1)
我想这里的主要问题是bwd[::-1]
的含义是什么?请参阅其他评论。
# take EWMA in both directions with a smaller span term
fwd = ewma( x, span=15 ) # take EWMA in fwd direction
## This part should not be a problem, right?
bwd = ewma( x[::-1], span=15 ) # take EWMA in bwd direction
## x[::-1] means to go thr x, from end to beginning(!), with a step of -1
## (hence it is going from the back to the front)
c = np.vstack(( fwd, bwd[::-1] )) # lump fwd and bwd together
c = np.mean( c, axis=0 ) # average
## Then we reverse ewma into a beginning-to-end order
## and take the average of fwd and bwd
## IMO, better written just as:
#c = 0.5*(fwd + bwd[::-1])
这个想法是,在前向EWMA中,当前值受到影响,但越来越少,因为早期值。另一方面,向后的EWMA受到后来值的影响。最后,通过获取前向和后向EWMA的平均值,您可以创建受周围值影响的东西(如果我们这样称呼它们),但是当你离开当前位置时越来越少。