I put a pull request in for Statsmodel exponential smoothing on Github and would like to know if there is a good way to improve this loop. So far I have working code and want to work out the kinks. It handles a variation of Exponential smoothing models.
Is there a good way to make this loop more efficient?
for i in range(ylen):
s = sdata[i]
b = bdata[i]
#handles multiplicative seasons
if season == 'multiplicative':
if trend == 'multiplicative':
sdata[i + 1] = alpha * (y[i + 2] / cdata[i]) + (1 - alpha) * s * (b**damp)
bdata[i + 1] = gamma * (sdata[i + 1] / s) + (1 - gamma) * (b ** damp)
cdata[i + cycle] = delta * (y[i + 2] / sdata[i + 1]) + (1 - delta) * cdata[i]
#handles additive models
else:
sdata[i + 1] = alpha * (y[i + 2] / cdata[i]) + (1 - alpha) * (s + damp * b)
bdata[i + 1] = gamma * (sdata[i + 1] - s) + (1 - gamma) * damp * b
cdata[i + cycle] = delta * (y[i + 2] / sdata[i + 1]) + (1 - delta) * cdata[i]
else:
if trend == 'multiplicative':
sdata[i + 1] = alpha * (y[i + 2] - cdata[i]) + (1 - alpha) * s * (b**damp)
bdata[i + 1] = gamma * (sdata[i + 1] / s) + (1 - gamma) * (b ** damp)
cdata[i + cycle] = delta * (y[i + 2] - sdata[i + 1]) + (1 - delta) * cdata[i]
#handles additive models
else:
sdata[i + 1] = alpha * (y[i + 2] - cdata[i]) + (1 - alpha) * (s + damp * b)
bdata[i + 1] = gamma * (sdata[i + 1] - s) + (1 - gamma) * damp * b
cdata[i + cycle] = delta * (y[i + 2] - sdata[i + 1]) + (1 - delta) * cdata[i]
I also posted on Code Review if you want the to test the full code. Please help suggest improvements. I have been programming only for several months so any help would be appreciated. Documentation for the code is also on the pull request at Github with sources.
First, most of the code in each of the 4 cases is identical. It's actually difficult to pick out which parts are different. That's a recipe for hard-to-find bugs. Pull the identical parts out of the conditionals; the if/else should only handle the part that actually changes.
Second, you're working with NumPy. You shouldn't be looping at all; you should find a way to use vectorized operations to perform your task. The tutorial shows some of the basics of vectorized operations. Vectorized code is shorter and far more efficient than code that uses explicit loops.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With