Skip to content

WIP ENH: add nonparametric variance estimator based on differencing - #3380

Open
josef-pkt wants to merge 7 commits into
statsmodels:mainfrom
josef-pkt:var_nonparametric
Open

josef-pkt wants to merge 7 commits into
statsmodels:mainfrom
josef-pkt:var_nonparametric

Conversation

@josef-pkt

@josef-pkt josef-pkt commented Jan 20, 2017 •

Copy link
Copy Markdown
Member

This sounded useful when I stumbled on it, so I had to give it a try. It seems to work pretty well and the approach is becoming a bit more popular in recent years, although citation numbers are not very high.

y = f(x) + e where e ~ (0, \sigma^2)
f(x) is an unknown function.

If we estimate f(x) nonparametrically with a optimal bandwidth, then the bias is too high to get a good variance estimate in small samples. The alternative is to smooth in such a way that we get a good estimate for the variance. One such estimator is based on differencing the series (ordered with respect to x).

implementation is based on description in
Dette, H., A. Munk, and T. Wagner. 1998. “Estimating the Variance in Nonparametric Regression—what Is a Reasonable Choice?” Journal of the Royal Statistical Society: Series B (Statistical Methodology) 60 (4): 751–64. doi:10.1111/1467-9868.00152.

but I read or skimmed also a few more articles.
This PR also provides the residual for the smoothed variance estimation, so we could use another nonparametric or semi-parametric estimator for estimating a variance function depending on x.

right now it's mainly 3 ways to calculate the same variance, the simplest and should be fastest is using convolve which assumes equal spaced x or sufficient smoothness. Unequal spaced x can be handled with a sparse window filter, where I took part of the sparse matrix handling from the current hp_filter.

unit tests: just compare 3 different implementation to produce exactly the same number. Estimated variance looks close to true, data generating variance.

Usage Recommendation based on Dette, Munk and Wagner:

  • polynomial differencing with order 2 is pretty robust for different settings, i.e. use it if not much prior information about the shape of the underlying mean function
  • polynomial differencing with order 2 or larger has good performance if the underlying mean function fluctuates strongly
  • polynomial differencing might underestimate variance with low fluctuation models
  • Hall, Kay and Titterington (HKT) optimal differencing works well with small fluctuations
  • HKT has good large sample properties with increasing order
  • HKT is not very good if fluctuations are large

small sample in Dette, Munk and Wagner is 25 observations, other small sample behavior for nobs <=100.

I think what this implies is that

  • for an original data series with possibly considerable mean fluctuation, we want to default to ("poly", 2)
  • for residual series, e.g. residuals of a regression model, we want to use (HKT, 2) or increasing order with large nobs.

not yet checked: references on using this for nonparametric test of the mean function. (might be just like an f_test comparing ssr with var based on differencing estimator.
Dette, Munk 1998?

@josef-pkt

Copy link
Copy Markdown
Member Author

fails locally for older scipy because of sparse which seems to have no elementwise power

======================================================================
ERROR: statsmodels.nonparametric.tests.test_variance.test_var_nonparametric
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\programs\WinPython-64bit-3.4.3.1\python-3.4.3.amd64\lib\site-packages
\nose\case.py", line 198, in runTest
    self.test(*self.arg)
  File "M:\josef_new\eclipse_ws\statsmodels\statsmodels_py34_pr\statsmodels\nonp
arametric\tests\test_variance.py", line 85, in test_var_nonparametric
    norm = np.sqrt(D.power(2).sum(1).A.ravel())
  File "C:\programs\WinPython-64bit-3.4.3.1\python-3.4.3.amd64\lib\site-packages
\scipy\sparse\base.py", line 499, in __getattr__
    raise AttributeError(attr + " not found")
AttributeError: power not found

----------------------------------------------------------------------
Ran 1 test in 0.143s

FAILED (errors=1)

M:\josef_new\testing>python
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) [MSC v.1600 64 bit (AM
D64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import scipy
>>> scipy.__version__
'0.15.1'

@josef-pkt

Copy link
Copy Markdown
Member Author

Do we still support old python? like 2.7?

>>> nobs = 30
>>> 2 / (3 * (nobs - 2))
0

where's my future?

Hoorah, one out of six is green.

@josef-pkt josef-pkt added this to the 0.9 milestone Jan 20, 2017
@josef-pkt

Copy link
Copy Markdown
Member Author

The latest commit allows endog to be 2-D. only exog is required to be 1-D in the sparse linear algebra version. (I haven't checked the other ones.)

vectorized univariate or multivariate?

currently the filter is designed as univariate, but because of the dot product, the .var() returns a covariance.
i.e. we are computing the residual covariance of independently smoothed series.

alternatives:

  • return only variances, i.e. independent computation just vectorized for axis=0, (replace dot product by sum of squares.)
  • multivariate filtering: There are some articles that use in this case multivariate nonparametric smoothing/filtering based on differencing but I didn't look at those. They don't look "trivial", mainly because we need to find the neighbors, I guess.

@josef-pkt

Copy link
Copy Markdown
Member Author

some notes so I don't forget

playing a bit with polynomial filters it looks like we can construct Dette, Munk and Wagner type filters directly from a polynomial fit. This also means we can extend DMK type filters to use longer windows than implied by order, i.e. separate order from window length. This would be closer to HKT.

There are some strange features of even length windows, because they don't center on an observation. In HKT the spike point is even at the end of the window for even length windows > 3. (window length = order + 1 always?)

@josef-pkt

Copy link
Copy Markdown
Member Author

Last commit adds also direct pinv computation for polynomial filter.
DMK _diff_kernel does not have consistent sign, sign is irrelevant for variance computation, but it is for interpreting residuals. Plotting implied fittedvalues was confusing because yhat = y - resid for some and y + resid for other orders. poly_window uses sign consistent with a residual interpretation.

@josef-pkt

Copy link
Copy Markdown
Member Author

another follow-up idea:
The sparse projector for unequal spaced grid (exog) might also be a pattern that is more generally useful for local polynomial fitting. Building the sparse projector matrix might be a bit expensive in some cases (if we use brute force construction) but applying it for different endog with the same 1-D exog will be cheap.
This is a related idea to the implementation of the hp_filter.
aside: the projection can also be vectorized for all obs and looping through the window. (see for example some of scikit-learn neighborhood/nearest neighbor regression.)
(there is also a stackoverflow answer for moving regression in finance that is vectorized. memory consumption also looks like nobs * window-length.)

terminology: I'm currently using kernel and windows as two words with the same meaning. pick one

@josef-pkt

Copy link
Copy Markdown
Member Author

related see scipy's savitzky_golay for a more complete implementation of polynomial filter with equal spaced data https://github.com/scipy/scipy/blob/master/scipy/signal/_savitzky_golay.py

This means using the residuals of savitzky_golay should also produce the same variance estimate as DMK except for the treatment of edge effects and the possibility of window_length > order + 1.
correction: we need to square norm our filter to get unbiased variance estimation, so savitzky_golay uses a different filter even if we used the same un-normed window.

possible bug or other problem: my poly coefficients when not normed are different from savitzky_golay signal.savgol_coeffs (I checked them against diff_kernel in the unit tests only for the standard window_length)

@josef-pkt

Copy link
Copy Markdown
Member Author

another indexing bug in my code (I'm not writing enough code anymore)

Note: poly_order is defined one-off: my order=3 corresponds to scipy poly_order=2, which is a quadratic function (I think, highest power=2, number of terms in poly=3)
(order in DMW differencing corresponds to the number of differencings (1-L)**k for lag polynomials)

>>> from scipy import signal
>>> signal.savgol_coeffs(5, 2)
array([-0.08571429,  0.34285714,  0.48571429,  0.34285714, -0.08571429])
>>> smv._poly_window(3, 5, normed=False, residual=False)
array([-0.08571429,  0.34285714,  0.48571429,  0.34285714, -0.08571429])

>>> signal.savgol_coeffs(5, 1)
array([ 0.2,  0.2,  0.2,  0.2,  0.2])
>>> smv._poly_window(2, 5, normed=False, residual=False)
array([ 0.2,  0.2,  0.2,  0.2,  0.2])

@josef-pkt

Copy link
Copy Markdown
Member Author

another agreement

HKT spike window is a special case of poly_window with order=2, i.e. linear trend (not constant as I argued above)

>>> smv._poly_window(2, 5)
array([-0.2236068 , -0.2236068 ,  0.89442719, -0.2236068 , -0.2236068 ])
>>> smv._spike_window(5)
array([-0.2236068 , -0.2236068 ,  0.89442719, -0.2236068 , -0.2236068 ])

>>> smv._poly_window(2, 7)
array([-0.15430335, -0.15430335, -0.15430335,  0.9258201 , -0.15430335,
       -0.15430335, -0.15430335])
>>> smv._spike_window(7)
array([-0.15430335, -0.15430335, -0.15430335,  0.9258201 , -0.15430335,
       -0.15430335, -0.15430335])

and

>>> smv._diff_kernel(2)  #Note different sign
array([ 0.40824829, -0.81649658,  0.40824829])
>>> smv._poly_window(2, 3)
array([-0.40824829,  0.81649658, -0.40824829])
>>> smv._spike_window(3)
array([-0.40824829,  0.81649658, -0.40824829])

So this looks good, and all we would need is poly_window/savitsky_golay plus the optimial (tabulated) HKT.
aside: scipy savgol requires "window_length must be odd" while all our windows are defined also for even window lenght with spike at the lower center index.

@josef-pkt

Copy link
Copy Markdown
Member Author

a "strange" feature, odd and even poly_order have the same coefficients.
I assume it's not a bug given that it is both in scipy and in my code.

>>> for order_ in range(1, 7): order_, signal.savgol_coeffs(7, order_ - 1)
(1, array([ 0.14285714,  0.14285714,  0.14285714,  0.14285714,  0.14285714,
        0.14285714,  0.14285714]))
(2, array([ 0.14285714,  0.14285714,  0.14285714,  0.14285714,  0.14285714,
        0.14285714,  0.14285714]))

(3, array([-0.0952381 ,  0.14285714,  0.28571429,  0.33333333,  0.28571429,
        0.14285714, -0.0952381 ]))
(4, array([-0.0952381 ,  0.14285714,  0.28571429,  0.33333333,  0.28571429,
        0.14285714, -0.0952381 ]))

(5, array([ 0.02164502, -0.12987013,  0.32467532,  0.56709957,  0.32467532,
       -0.12987013,  0.02164502]))
(6, array([ 0.02164502, -0.12987013,  0.32467532,  0.56709957,  0.32467532,
       -0.12987013,  0.02164502]))


>>> for order_ in range(1, 7): order_, smv._poly_window(order_, 7, normed=False, residual=False)
(1, array([ 0.14285714,  0.14285714,  0.14285714,  0.14285714,  0.14285714,
        0.14285714,  0.14285714]))
(2, array([ 0.14285714,  0.14285714,  0.14285714,  0.14285714,  0.14285714,
        0.14285714,  0.14285714]))

(3, array([-0.0952381 ,  0.14285714,  0.28571429,  0.33333333,  0.28571429,
        0.14285714, -0.0952381 ]))
(4, array([-0.0952381 ,  0.14285714,  0.28571429,  0.33333333,  0.28571429,
        0.14285714, -0.0952381 ]))

(5, array([ 0.02164502, -0.12987013,  0.32467532,  0.56709957,  0.32467532,
       -0.12987013,  0.02164502]))
(6, array([ 0.02164502, -0.12987013,  0.32467532,  0.56709957,  0.32467532,
       -0.12987013,  0.02164502]))

but it's not the case for even window length (no verification for this, so bug is possible)

>>> for order_ in range(1, 7): order_, smv._poly_window(order_, 8, normed=False, residual=False)
(1, array([ 0.125,  0.125,  0.125,  0.125,  0.125,  0.125,  0.125,  0.125]))
(2, array([ 0.16666667,  0.1547619 ,  0.14285714,  0.13095238,  0.11904762,
        0.10714286,  0.0952381 ,  0.08333333]))
(3, array([-0.04166667,  0.125     ,  0.23214286,  0.2797619 ,  0.26785714,
        0.19642857,  0.06547619, -0.125     ]))
(4, array([-0.12121212,  0.18181818,  0.31168831,  0.31385281,  0.23376623,
        0.11688312,  0.00865801, -0.04545455]))
(5, array([-0.01893939, -0.00811688,  0.26785714,  0.44534632,  0.36525974,
        0.07305195, -0.18127706,  0.05681818]))
(6, array([ 0.02913753, -0.16608392,  0.38461538,  0.5483683 ,  0.26223776,
       -0.04370629, -0.02331002,  0.00874126]))

@josef-pkt

Copy link
Copy Markdown
Member Author

another puzzle

shouldn't fitting a polynomial if the data is a polynomial have residual = 0?

>>> y2 = np.linspace(0, 5, 15)**2
>>> d = smv._poly_window(2, 4, normed=False, residual=True)
>>> s2, resid = smv.var_differencing(y2, kind=d)
>>> s2
0.016269262807163853
>>> resid
array([-0.12755102, -0.12755102, -0.12755102, ..., -0.12755102,
       -0.12755102, -0.12755102])


>>> d = smv._poly_window(1, 3, normed=False, residual=True)
>>> s2, resid = smv.var_differencing(y2, kind=d)
>>> s2
0.0072307834698506343
>>> resid
array([-0.08503401, -0.08503401, -0.08503401, ..., -0.08503401,
       -0.08503401, -0.08503401])

>>> d = smv._poly_window(2, 5, normed=False, residual=True)
>>> s2, resid = smv.var_differencing(y2, kind=d)
>>> s2
0.06507705122865394
>>> resid
array([-0.25510204, -0.25510204, -0.25510204, ..., -0.25510204,
       -0.25510204, -0.25510204])

and with normed=True:

>>> d = smv._poly_window(2, 5, normed=True, residual=True)
>>> s2, resid = smv.var_differencing(y2, kind=d)
>>> s2
0.081346314035817574
>>> resid
array([-0.28521275, -0.28521275, -0.28521275, ..., -0.28521275,
       -0.28521275, -0.28521275])>> >

@josef-pkt

Copy link
Copy Markdown
Member Author

it does, with the right order

everything matches the theory (as I understand it),
meaning of order in polynomials is always a bit confusing, and whether we want differencing in this case up to having a constant or up to having zeros.

(The only thing not verified is when we have unequal spaced exog. And checking API. I haven't seen a reference package for this for the unit tests, except for the savitzky_golay part.)

>>> s2, resid = smv.var_differencing(y2, order=3)
>>> s2
3.7568473448513683e-30
>>> resid
array([ -5.55111512e-17,   5.55111512e-17,  -1.11022302e-16, ...,
        -1.77635684e-15,   3.55271368e-15,  -5.32907052e-15])

>>> d = smv._poly_window(3, 5, normed=False, residual=True)
>>> s2, resid = smv.var_differencing(y2, kind=d)
>>> s2
3.8300793719488562e-30
>>> resid
array([  1.94289029e-16,   1.11022302e-16,   4.44089210e-16, ...,
         1.33226763e-15,   5.10702591e-15,  -8.88178420e-16])>> >


>>> d = smv._poly_window(3, 5, normed=False, residual=False)
>>> s2, y_hat = smv.var_differencing(y2, kind=d)
>>> s2
89.790061432736337
>>> y_hat
array([  0.51020408,   1.14795918,   2.04081633, ...,  12.75510204,
        15.43367347,  18.36734694])
>>> y2[2:-2]
array([  0.51020408,   1.14795918,   2.04081633, ...,  12.75510204,
        15.43367347,  18.36734694])

>>> y2.var()
63.99821833495303
>>> (y2[2:-2]**2).mean()
89.790061432736366

@josef-pkt

Copy link
Copy Markdown
Member Author

http://www.stata-journal.com/article.html?article=st0109
Lokshin, M. 2006. “Difference-Based Semiparametric Estimation of Partial Linear Regression Models.” Stata Journal 6 (3): 377–83.
Removes nonparametrically the effect of the nonlinear part to estimate the coefficients of the linear part.
Used unequal spaced x points based on higher order differencing, so it might be similar to my implementation of DMW. (unit tests?)

about sample size: footnote 1
"The Monte Carlo simulations using the plreg command demonstrate that the noticeable gains in
efficiency from the higher-order differencing occur on samples with 30,000 or more observations. On the
smaller samples (1,000–3,000 observations), using the higher-order differencing might result in biased
estimates."

looks like we need many observations.

@josef-pkt

Copy link
Copy Markdown
Member Author

Yatchew, Andrew. n.d. “Differencing Methods in Nonparametric Regression: Simple Techniques for the Applied Econometrician.” http://homes.chass.utoronto.ca/~yatchew/DifferencingPaper.pdf. 96 pages

p. 18 He mentions that HKT table of coefficients has minor errors, and has a table that looks pretty different from HKT to me, e.g. spike is always in first position.
looks interesting, but I only looked at the table.

@josef-pkt

josef-pkt commented Jan 25, 2017 •

Copy link
Copy Markdown
Member Author

close to stopping here: It has all the basic features that I wanted, more refinements and applications can wait.

The last commit added a RollingRegressionProjector: Slow brute force construction of the projection matrix, but fast in repeated application for different endog. Construction uses pinv, i.e. svd, in a loop for each window. Projection on an endog is either with sparse matrix dot product or loop over lags in window.
Focus is still on variance estimation, and I don't know yet how widely applicable the local regression is.

memory for storing windows is nobs * window_length which is currently stored several times.

theoretically unclear: degrees of freedom correction for variance calculation with local regression. I'm mixing several things between local polynomial fitting and the estimating variance literature.

If variance estimation is the target, then normed=True and project_residual=True is (should be) close to DMW except for arbitrary window length. In nice case, true model is polynomial of same order as used in filtering, mean squared error for variance estimate with nobs=200 is very small (in a Monte Carlo).

Not checked yet: Is behavior of basic k-th order differencing really good with unequal spaced x on compact support? All articles that I looked at so far, only use equal spaced x in the simulations.
In the test case var_differencing also has less than 5% error in variance (nobs=200, "nice" or typical seed).

(edit: commit amended and force pushed to remove print statements and add var_differencing unit test)

@josef-pkt

josef-pkt commented Jan 25, 2017 •

Copy link
Copy Markdown
Member Author

It seems large parts of what I have "discovered" here in extending window_length beyond order+1 is (based on partial reading) already in
Seifert, Burkhardt, Theo Gasser, and Andreas Wolf. 1993. “Nonparametric Estimation of Residual Variance Revisited.” Biometrika 80 (2): 373–83. doi:10.2307/2337207.

Instead of local polynomial regression, they use the iterative dot product construction of the differencing filter for equal spaced similar exog similar to VarianceDiffProjector. That means we should be able to extend that to unqual spaced. Essentially we just need to put a averaging filter inf front of the VarianceDiffProjector filter.
Correction They use unequal spaced observations for the recursive construction. It's the same as VarianceDiffProjector plus and averaging filter in front.

(another thought: using Lag-polynomials in analogy to a k times integrated moving average filter might also work conveniently for creating the convolution or filter coefficients, at least in the equal spaced case.)

@lgtm-com

lgtm-com Bot commented Dec 2, 2022

Copy link
Copy Markdown

This pull request introduces 1 alert when merging 2e8aae8 into 8962c7f - view on LGTM.com

new alerts:

  • 1 for Illegal raise

Heads-up: LGTM.com's PR analysis will be disabled on the 5th of December, and LGTM.com will be shut down ⏻ completely on the 16th of December 2022. It looks like GitHub code scanning with CodeQL is already set up for this repo, so no further action is needed 🚀. For more information, please check out our post on the GitHub blog.

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.

1 participant