Skip to content

ENH: add asymmetric kernels for kde and cdf, for unit interval and R+ - #7364

Merged
josef-pkt merged 7 commits into
statsmodels:masterfrom
josef-pkt:kde_asymmetric
Mar 12, 2021
Merged

josef-pkt merged 7 commits into
statsmodels:masterfrom
josef-pkt:kde_asymmetric

Conversation

@josef-pkt

@josef-pkt josef-pkt commented Mar 8, 2021 •

Copy link
Copy Markdown
Member

see #7346

nonparametric kernel estimation for density and cdf based on asymmetric kernels
kernels are based on the corresponding scipy distribution

for unit interval:

  • beta, beta2

for R+:

  • gamma, gamma2
  • invgamma
  • invgauss
  • recipinvgauss
  • bs (Birnbaum-Saunders)
  • log-normal
  • weibull (weibull_min for y>0 )

Status:
currently only checked visually using kde plots for gamma random sample (nobs=1000), plots look good,
(invgauss is not so good, also weak performance in some references)
update unit test check that average mean squared error AMSE is small.

I followed parameterization of original articles, but I might want to make them more consistent between them.

no extras, especially no bandwidth defaults or selection

@pep8speaks

pep8speaks commented Mar 8, 2021 •

Copy link
Copy Markdown

Hello @josef-pkt! Thanks for updating this PR. We checked the lines you've touched for PEP 8 issues, and found:

There are currently no PEP 8 issues detected in this Pull Request. Cheers! 🍻

Comment last updated at 2021-03-12 18:54:41 UTC

@josef-pkt

josef-pkt commented Mar 8, 2021 •

Copy link
Copy Markdown
Member Author

(pep-8, whitespace and line breaks)

currently these are just basic function do compute kernel pdf or kernel cdf, taking mean over sample points

instead of mean, we need also

  • weights: use weighted average so we can use it for binned data, i.e. histogram smoothing in analogue to bernstein-beta smoothing or kde
  • no aggregation, for multivariate product kernels we need to multiply kernels across components before averageing.
    MultivariateKDE kernels have a boolean option to turn of aggregation
  • rvs, either we need the distribution instance or a separate function for random sampling, rvs is based on components/sample points and not averaged/aggregated

update

compared to MultivariateKDE

  • kernels are only the kernel functions without mean or aggregation
  • gpke computes mv product and optionally sums tosum option
  • division by nobs is in KDEMultivariate.pdf directly based on return of gpke

my current functions have all three steps, for univariate case

@lgtm-com

lgtm-com Bot commented Mar 8, 2021

Copy link
Copy Markdown

This pull request introduces 1 alert when merging d707f4e into 5ce985f - view on LGTM.com

new alerts:

  • 1 for Variable defined multiple times

@josef-pkt

Copy link
Copy Markdown
Member Author

amended and force pushed, pep-8 cleaning and adding invgamma kernel

(beta2 had flake/lint problems, I didn't run it yet.)

@josef-pkt

josef-pkt commented Mar 8, 2021 •

Copy link
Copy Markdown
Member Author

aside: it looks to me like matplotlib hist for cumulative histogram uses the wrong step type
steps are above cdf, i.e. it's not a step at the given end point of an interval, the step is at beginning of interval.
(IIRC, then we change the step type for our ECDF at some point.)

plt.hist(rvs, bins=20, density=True, alpha=0.3, cumulative=True, histtype='step')

alternative for plotting would be to use some plotting position to get better agreement, i.e. theoretical cdf is somewhere in the middle of the steps of the ecdf, i.e. intersecting instead of touching at jump points.

another alternative: plot cdf with linear interpolated of edge points, which would correspond to piecewise constant histogram distribution.

example with kernel_cdf_beta2 (not yet in this PR, I wasn't sure boundary corrected kernels can be directly used for cdf)

image

update
there is an align option also in hist to change step type (in that case steps intersect cdf plot in my example)
plt.hist(rvs, bins=20, density=True, alpha=0.3, cumulative=True, histtype='step', align="right")

@josef-pkt

Copy link
Copy Markdown
Member Author

notebook checking all kernels for R+:
https://nbviewer.jupyter.org/gist/josef-pkt/ea3cccb4e2daf83f4311cc55fe9da32e

(current branch needs bug fixes for cdf, and missing cdf)

@josef-pkt

Copy link
Copy Markdown
Member Author

vectorized evaluation for different new x points is still unverified. I only checked initially a gamma example.
mean is missing axis argument for most functions. two functions use scalar if.

@josef-pkt

josef-pkt commented Mar 9, 2021 •

Copy link
Copy Markdown
Member Author

adding rvs based on kernel estimate

  • I didn't find a reference
  • using analogy to beta-kernel (beta copula and bernstein density
  • I don't understand why it works, x and sample points are reversed (I don't know why that also works with asymmetric kernels)
  • only proof by one example
n = len(rvs)
nobs = 2000
krvs = []
for _ in range(nobs):
    xi = rvs[np.random.randint(0, n)]
    krvs.append(stats.gamma.rvs(xi / bw + 1, scale=bw))
    
krvs = np.asarray(krvs)

dgp pdf of original gamma distribution
kde_dgp : gamma kde based original gamma generated sample
kde is the gamma kde from the random sample generated based on kde_dgp

sample size of original data: 1000
sample size drawn from kde: 2000
so estimates should match pretty well

image

another one after creating more random numbers so seed changes
match is better, no dip on peak

image

@josef-pkt

Copy link
Copy Markdown
Member Author

one more variation: binned data, just using np.histogram for binning

continued example, original gamma rvs with nobs=1000. converted to histogram with 50 bins
At 100 bins there was no visible difference between kde on full data versus kde on binned data.

center are bin centers based on np.hist edges
probs are counts / nobs

kpdfw = np.asarray([kern.kernel_pdf_gamma(xi, center, bw, weights=probs) for xi in x_plot])

image

@josef-pkt

Copy link
Copy Markdown
Member Author

Ok, I will strip averaging code out of the functions, so that they have only the kernel definitions (similar to kernels for MultivariateKDE).

If I want averaging options, then I would have to add them to each function with a lot of code duplication. This way access is through wrapper function that computes weighted average based on a kernel function.

Also I want to add a batch loop, for evaluating vector x (prediction points), inside the wrapper function, so looping doesn't use more function calls than in the current version.

@josef-pkt

Copy link
Copy Markdown
Member Author

That's about as far as I want to get here, for now. (batch loop and doc strings are still missing)

open question:

  • Do we add clipping? Some kernels cannot evaluate at new point x=0 without runtime warning.
    In unit test 1 stay away from zero to avoid warnings. (and possible nans)
    beta2 kernel doesn't seem to have problem at upper bound 1.
  • rvs ? would be important, but needs more checking because I'm not sure it's supposed to work.
  • binning functions: weights for histogram smoothing are available, but no additional binning function added here.

There is no input validation, e.g. no check that points are in support of distributions/kernels

@josef-pkt

Copy link
Copy Markdown
Member Author

now includes batch loop

I refactored unit tests:
I had unit interval test class subclassing R+ test class. I got confusing results from inheritance when I didn't properly override a method.
Now I use a separate superclass. test methods require a pytest.mark.parametrize. If a method is not implemented in the subclass, then pytest will error with unknown argument for inherited test method.

@josef-pkt

Copy link
Copy Markdown
Member Author

should be finished now, except I haven't copied references to each docstring yet.

@josef-pkt

Copy link
Copy Markdown
Member Author

I had a quick look at
Igarashi, Gaku, and Yoshihide Kakizawa. 2014. “Re-Formulation of Inverse Gaussian, Reciprocal Inverse Gaussian, and Birnbaum–Saunders Kernel Estimators.” Statistics & Probability Letters 84 (January): 235–46. https://doi.org/10.1016/j.spl.2013.10.013.

It looks like Birnbaum–Saunders, inverse Gaussian, and reciprocal inverse Gaussian kernel require that f(0) = 0 and goes fast enough to zero as x -> 0.
otherwise there is a boundary bias.

(related to exponential versus power tails if I interpret Stephens on transformation of random variables correctly)

AFAIR, f(0) = 0 is assumed by most/all kernels except gamma.
gamma kernel can have lim f(x) = inf as x-> 0 (theorem in Bouezmarni, Taoufik, and Olivier Scaillet. 2005 )

I'm not sure which kernels can have f(0) = c with c > 0 and finite.

@josef-pkt
josef-pkt force-pushed the kde_asymmetric branch 3 times, most recently from 1c0fb4a to 8e79ba1 Compare March 12, 2021 17:14
@josef-pkt

Copy link
Copy Markdown
Member Author

I cleaned up docstrings, amended and force pushed

should be finished and ready to merge

@josef-pkt

Copy link
Copy Markdown
Member Author

aside: I don't like the order of arguments in the kernels for MultivariateKDE, so the signature here is not compatible with those.

Otherwise, it should be possible to plug the asymmetric kernels into MultivariateKDE

@josef-pkt
josef-pkt merged commit 48bb953 into statsmodels:master Mar 12, 2021
@josef-pkt josef-pkt changed the title WIP ENH: add asymmetric kernels for kde and cdf, for unit interval and R+ ENH: add asymmetric kernels for kde and cdf, for unit interval and R+ Mar 12, 2021
@josef-pkt

Copy link
Copy Markdown
Member Author

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.

2 participants