Skip to content

Made Exponential Smoothing for Statsmodel handles Single, double, triple & variations. (Needs Checking and improvements) - #1287

Closed
ccsv wants to merge 4 commits into
statsmodels:masterfrom
ccsv:patch-1
Closed

ccsv wants to merge 4 commits into
statsmodels:masterfrom
ccsv:patch-1

Conversation

@ccsv

@ccsv ccsv commented Jan 4, 2014

Copy link
Copy Markdown

Started Exponential Model off of code from dfrusdn and heavily modified. Handles 15 different models. The code is also fully documented. It looked like this was in demand so I tried out my coding skills.

This handles ALL of the following models:
Simple Exponential Smoothing(SES)
Simple Seasonal models (both multiplicative and additive)
Brown's Linear Exponential Smoothing
Holt's Double Exponential Smoothing
Exponential trend method
Damped-Trend Linear Exponential Smoothing
Multiplicative damped trend (Taylor 2003)
Holt-Winters Exponential Smoothing: multiplicative trend, additive trend, multiplicative season, additive season and damped models for all four variations

The code is accurate just that the initial values are off so they have to be adjusted. All the equations match what is given by Exponential smoothing: The state of the Art II page 8.

I do not know what methods are used to backcast the function so I left two Nans in the beginning to align the data. There is also a todo list.

I am not a programmer and I just did python for about 3 months so I need a code check. I think this should be in a class but I have not dealt with them enough to know what I am doing.

Testing: Go to the line 308 to 320 and remove the double pound signs for debug

#-------Test-------
#Parameters list
#(y, alpha, gamma, delta = 0, cycle = None, damp = 1, initial = None,
#                     trend = 'additive', forecast=None, season = 'additive', output='data')
y=[152,176,160,192,220,272,256,280,300,280,312,328]

exp_smoothing(y,0.2, 0.3)

>>> 
sdata= [      nan       nan  152.      172.8     195.072   218.3053  247.3936
  268.9406  290.2018  310.5986  322.2802  335.4886]
bdata= [     nan      nan  24.      23.04    22.8096  22.9367  24.7822  23.8116
  23.0465  22.2516  19.0806  17.3189]
cdata= [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
pdata= [      nan       nan  176.      195.84    217.8816  241.242   272.1758
  292.7523  313.2483  332.8503  341.3608  352.8076]

it matches the data in blue from http://analysights.wordpress.com/2010/05/20/forecast-friday-topic-double-exponential-smoothing/

For forecasting 3 periods ahead

exp_smoothing(y,0.2, 0.3,0,None,1, None, 'additive', 3)

Output:
pdata= [      nan       nan  176.      195.84    217.8816  241.242   272.1758
  292.7523  313.2483  332.8503  341.3608  352.8076  363.6765  360.4414
  379.522 ]

Started Exponential Model off of code from dfrusdn and heavily modified. Handles 15 different models.
@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage remained the same when pulling 81f99f5 on ccsv:patch-1 into 946021a on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member

Thanks @ccsv and thanks @dfrusdn for getting this started.

I'm not very familiar with the details of exponential smoothing and how it is used.

For the user interface, we will need to look at some other packages, for example Hyndman's, to see what would be a good design and required results. We should also get much of the data and date handling from the current tsa classes.

It's still missing unittests, some of the examples could be converted into unit tests.

I don't know what is usually done to estimate the smoothing parameters.

However, what I think is very good about the current PR is that it isolates the smoothing filter. I think we should keep it that way and it should be and can be easily converted to a cython module, after the initial open question have been resolved. (It will be slow as python loop for any longer time series.)
My suggestion would be to move it to a _expsmoothing.py file and import it from there, with the target that that module will be converted to a cython pyx file. (similar to the kalman filter used in ARMA)

great work on docstrings.

@TomAugspurger

Copy link
Copy Markdown
Contributor

For the initial values with single exponential smoothing, Minitab uses the simple average of the first n values (default is 6). Let me know if you have a dataset you want me to run it on so that you can compare.

Comment thread statsmodels/tsa/Expsmoothing Outdated

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you remove these blank lines between the different parameters in the docs? I think it'll make it easier to read at the console.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jseabold like line 97& 83?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You just don't need the blank lines in the parameter section between the parameters. E.g.,

y : array
    Time series data
alpha : float
    Smoothing factor for data.

@ccsv

ccsv commented Jan 4, 2014

Copy link
Copy Markdown
Author

@TomAugspurger initializing data starts around 157 to 200 or search for the comment #Setting b1 value there is also an initial=None if you want to add modifications. Right now I have the first 3 average values under a section 3avg Back filling the data with Nans starts where the comment #Temporary fix:

@josef-pkt is there a specific way to do the summary? I know there are summary formats in other models. I found mostly what I need in statsmodels.tools.eval_measures as em

remove lines some style
@ccsv

ccsv commented Jan 4, 2014

Copy link
Copy Markdown
Author

@jseabold Done. But it is not all Pep8 because I am not familiar. Also if anyone can vectorize the for loop it would be very helpful for efficiency.

@jseabold

jseabold commented Jan 4, 2014

Copy link
Copy Markdown
Member

Yeah, that doesn't look good. Especially with the if/else statements within the for loop.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage remained the same when pulling 052824b on ccsv:patch-1 into 946021a on statsmodels:master.

@ccsv

ccsv commented Jan 4, 2014

Copy link
Copy Markdown
Author

@jseabold I have not been programming very long so I am having a hard time fixing that problem

@jseabold

jseabold commented Jan 4, 2014

Copy link
Copy Markdown
Member

Sure, no problem. Will see if we can have a look at it and work through it.

@ccsv

ccsv commented Jan 4, 2014

Copy link
Copy Markdown
Author

Just added everyone as collaborators. So you can make minor edits (grammar/syntax) or whatever helps

@dfrusdn

dfrusdn commented Jan 4, 2014

Copy link
Copy Markdown

@ccsv I agree with Tom the 3avg feature should be changed to averaging by n values

Changed title for cython move recommended by josef
@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage remained the same when pulling 151bba2 on ccsv:patch-1 into 946021a on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member

Also if anyone can vectorize the for loop it would be very helpful for efficiency.

I don't think there is any way to vectorize this type of iterative/recursive loops, and scipy.signal doesn't have any precompiled code for this case. That's why I think we have to go to cython for it.
I'm suspicious about the if branching inside the loop, but I didn't look closely enough to see whether it's worth to take the conditioning outside.

@josef-pkt

Copy link
Copy Markdown
Member

Stata doesn't seem to provide much http://www.stata.com/manuals13/tstssmoothexponential.pdf
only simple exponential smoothing and just a few additional summary statistics.
possibly minimize MSE to find smoothing parameters.
choice of initializing conditions (uses mean of half of the sample if not specified), applies to panel data

@josef-pkt

Copy link
Copy Markdown
Member

http://cran.ms.unimelb.edu.au/web/packages/forecast/forecast.pdf description of ets
several methods (objective functions) to estimate smoothing parameters, fully automatic. Default is maximum likelihood.
I don't see what results they have based on the descriptions there.

Comment thread statsmodels/tsa/_expsmoothing Outdated

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

need full references, authors, ...

@dfrusdn

dfrusdn commented Jan 5, 2014

Copy link
Copy Markdown

@josef-pkt I looked at most of the equations and they seem to match the dampened season models from Exponential smoothing: The state of the art Part II. on p. 8 http://www.bauer.uh.edu/gardner/Exponential-Smoothing.pdf From what I saw I am pretty sure they are just the different dampened models with season and trend components.

Minimizing MSE usually how the methods are chosen. But I read that some articles using MMSE as a better alternative because MSE does not do a good job on seasons.

In literature there are multiple books and articles that give different initial values such as mean of first 3 numbers (NIST.gov) or an average of all the data.

added authors per josef
@dfrusdn

dfrusdn commented Jan 5, 2014

Copy link
Copy Markdown

Went ahead and made josef's edits

@josef-pkt Found a place to run exponential smoothing R code but I don't know if it is accurate or what is used for the start values
http://www.wessa.net/rwasp_exponentialsmoothing.wasp#output

From those loops I saw notice that parts such as (1 - alpha), (1 - gamma), (1 - delta) can probably be calculated out of loop and put in as a constant since it is what you initially put in and there is not updating to them when the for loop goes around. I am not familiar enough to know if this will make it faster.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage remained the same when pulling 85b6421 on ccsv:patch-1 into 946021a on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member

The way I see it after browsing a bit some references and Hyndman's blog.

The main parts besides adding unit tests for the smoother is to start a Model and Results classes to get fit the estimation of the parameters. To make it easier at the beginning, I would just inherit from LikelihoodModel and LikelihoodModel results (or inherit initially from GenericLikelihoodModel to get most things to work out of the box). Later I guess we will need similar classes like the ones for ARMA.
The main methods for estimation are loglike (and score/derivatives if possible) and the method to get the "innovations", residuals. Other methods to define different objective functions mse, mmse, ...

Hyndman mentions that the parameters should be constraint to [0.1, 0.9] to impose stability on the system. He also mentions the possibility of local minima, which we could try to work around by scipy's basinhoppin which is already connected to LikelihoodModel.fit and will come for "free".

Since this is mainly used for forecasting and not for analysing effects and parameter estimates, we will need to got forecast method. I don't know how that will look like in details, similar to ARMA, but that one still has several limitations.

My impression is that we should target Hyndman's ets in the forecast package, although we won't have all the options available since we are just getting started.

We will need a reasonably long seasonal dataset for the unit tests (a few hundred observations) to reduce the effect of differences in initial conditions on the results.

http://robjhyndman.com/hyndsight/estimation/
http://robjhyndman.com/hyndsight/estimation2/

(That's how I see it, but I need to go back to other work and won't have time to read the 5 or 10 articles that I downloaded to understand the details.
I can help in general especially with the statsmodels parts that are more difficult to understand.

It will be great to get more contributors and reviewers for statsmodels.tsa, since this is one of our popular parts and relies currently mainly on Skipper's work.)

@jseabold

jseabold commented Jan 5, 2014

Copy link
Copy Markdown
Member

On Sun, Jan 5, 2014 at 9:03 AM, Josef Perktold [email protected]:

We will need a reasonably long seasonal dataset for the unit tests (a few
hundred observations) to reduce the effect of differences in initial
conditions on the results.

The seasonal plotting PR I just made includes (in the main script) the co2
emission dataset, which is ~470 observations. It's available as
sm.datasets.get_rdataset('co2'), though the dates need a little tweaking in
the rdataset package.

I think we can also include it, but I haven't checked for license yet.

@josef-pkt josef-pkt added the PR label Feb 19, 2014
@jseabold

Copy link
Copy Markdown
Member

Is this still being worked on? If so, it needs some tests. If tests aren't forthcoming, at the least it would be great to see some comparisons to working code in another package for a comparison. R or Stata preferred but really whatever.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why does this use future values of y. Every reference I think this should be y[i] unless this is doing something I haven't seen.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I see the alignment intentions here, but this doesn't work as is AFAICT.

@jseabold

Copy link
Copy Markdown
Member

Ok, I'm cleaning this up and correcting and writing tests (fun!). Will submit a PR soon I hope. Pushing parts to Cython might have to wait, though I've abstracted it so that it will be trivial to do so.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ccsv It's unclear to me what you're doing here. Do you have an exact reference for this, or can you explain in words?

It looks like you normalize the data in one period by the mean of each period. E.g., for monthly data year one is normalized by the mean for that whole year (axis 1 mean). Then you take the period averages (axis 0) mean. I'm curious about this. Division vs. subtraction corrections for the assumed type of cycle.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like this might be from wikipedia via NIST. I find many different recommendations for this in the literature, so we'll see what looks 'best.'

http://www.itl.nist.gov/div898/handbook/pmc/section4/pmc435.htm

@jseabold

Copy link
Copy Markdown
Member

I'm closing this in favor of #1489. If you come back to work on this, please just push any changes here. I'm not even sure how to replicate some of these models in R. E.g., holt_des with no seasonality, so as I mentioned before, even an example script that produces values these functions should match would make this go much faster. Days/weeks instead of likely months or longer what it looks like for me now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants