Repository navigation
Description
Describe the bug
I'll start with this: I'm not a statistician, just an engineer with a reasonable understand of how things work. I apologise if I don't explain this problem well.
Currently it appears that the KDEMultivariate.cdf() is not functioning as expected given that for two variables, u and v, and an interval for u with moderate probability density in u and an interval in v with approximately no density in v; that the CDF evaluates this region to be non-zero. In other words, in the KDE space of u, v, p (where p is the probability density), that for a region with effectively no probability density, that the CDF is evaluating this region as though it had non-zero density.
Code Sample, a copy-pastable example if possible
I have written an example comparing outputs with scipy gaussian KDE and which produces a simple seaborn plot to sanity check with. Viewing the plot, I expect that on the interval u, v = [ 1±0.3, 20±0.3] that the integral would be ~0 (which I think is the output of the CDF on that interval).
# Third Party
import numpy
import seaborn as sns
from matplotlib import pyplot as plt
from scipy.stats import gaussian_kde
from statsmodels.nonparametric.kernel_density import KDEMultivariate
# Create data set
nobs = 300
numpy.random.seed(1234) # Seed random generator
u = numpy.random.normal(size=(nobs, 1)).ravel()
v = numpy.random.normal(size=(nobs, 1)).ravel()
uv = numpy.vstack([u.ravel(), v.ravel()])
# Initialise kernels
ku_sm = KDEMultivariate(data=u, var_type="c", bw="normal_reference")
kv_sm = KDEMultivariate(data=v, var_type="c", bw="normal_reference")
kuv_sm = KDEMultivariate(data=uv, var_type="cc", bw="normal_reference")
ku_sci = gaussian_kde(dataset=u)
kv_sci = gaussian_kde(dataset=v)
kuv_sci = gaussian_kde(dataset=uv)
# Choose values to test about
u_o = numpy.array(0).ravel()
v_o = numpy.array(20).ravel()
u_t = numpy.array(u_o)
v_t = numpy.array(v_o)
uv_t = numpy.vstack([u_t, v_t])
# Choose consistent bw for both u and v:
bw = numpy.array(0.3)
bw_uv = numpy.vstack([bw, bw])
# Evaluate cdf on bounds for statsmodels
pa = ku_sm.cdf(u_t - bw / 2)
pb = ku_sm.cdf(u_t + bw / 2)
p_u_t_sm = pb - pa
pa = kv_sm.cdf(v_t - bw / 2)
pb = kv_sm.cdf(v_t + bw / 2)
p_v_t_sm = pb - pa
pa = kuv_sm.cdf(uv_t - bw_uv / 2)
pb = kuv_sm.cdf(uv_t + bw_uv / 2)
p_uv_t_sm = pb - pa
# Evaluate cdf on bounds for scipy
lower = u_t - bw / 2
upper = u_t + bw / 2
p_u_t_sci = ku_sci.integrate_box_1d(lower, upper)
lower = v_t - bw / 2
upper = v_t + bw / 2
p_v_t_sci = kv_sci.integrate_box_1d(lower, upper)
lower = (uv_t - bw_uv / 2).ravel()
upper = (uv_t + bw_uv / 2).ravel()
p_uv_t_sci = kuv_sci.integrate_box(lower, upper)
# Spew results:
print(f"u,v interval lower: {uv_t - bw_uv / 2}")
print(f"u,v interval upper: {uv_t + bw_uv / 2}")
print(f"p_u_t_sm: {p_u_t_sm}")
print(f"p_u_t_sci: {p_u_t_sci}")
print(f"p_v_t_sm: {p_v_t_sm}")
print(f"p_v_t_sci: {p_v_t_sci}")
print(f"p_uv_t_sm: {p_uv_t_sm}")
print(f"p_uv_t_sci: {p_uv_t_sci}")
# Plot for convenience:
g = sns.kdeplot(x=uv[0], y=uv[1], data=uv, thresh=0, cut=80, fill=True, cmap="mako", levels=50)
g.set_xlim(-15, 15)
g.set_ylim(-5, 25)
plt.show()Expected Output
What was expected:
p_u_t_sm = 0
What was returned:
p_u_t_sm = 0.0802
Output of import statsmodels.api as sm; sm.show_versions()
Details
INSTALLED VERSIONS
Python: 3.7.3.final.0
statsmodels
Installed: 0.12.0 (C:\Users*redact*.virtualenvs*redact*lib\site-packages\statsmodels)
Required Dependencies
cython: Not installed
numpy: 1.19.2 (C:\Users*redact*.virtualenvs*redact*\lib\site-packages\numpy)
scipy: 1.5.2 (C:\Users*redact*\virtualenvs*redact*\lib\site-packages\scipy)
pandas: 1.1.3 (C:\Users*redact*\virtualenvs*redact*\lib\site-packages\pandas)
dateutil: 2.8.1 (C:\Users*redact*\virtualenvs*redact*\lib\site-packages\dateutil)
patsy: 0.5.1 (C:\Users*redact*\virtualenvs*redact*\lib\site-packages\patsy)
Optional Dependencies
matplotlib: 3.3.2 (C:\Users*redact*\virtualenvs*redact*\lib\site-packages\matplotlib)
backend: TkAgg
cvxopt: Not installed
joblib: Not installed
Developer Tools
IPython: 7.18.1 (C:\Users*redact*\virtualenvs*redact*\lib\site-packages\IPython)
jinja2: Not installed
sphinx: Not installed
pygments: 2.7.1 (C:\Users*redact*\virtualenvs*redact*\lib\site-packages\pygments)
pytest: 6.0.2 (C:\Users*redact*\virtualenvs*redact*\lib\site-packages\pytest)
virtualenv: Not installed
Activity
Afrozodiacc commentedon Oct 19, 2020
I have not tested whether this issue applies to
KDEMultivariateConditional.josef-pkt commentedon Oct 19, 2020
I get an exception in the sns.kdeplot, maybe I have an older version
I didn't try to fully understand however, AFAIU
The difference of two nested cdf values in 2-dim does not define a box. This is the area that has two stripes one going to -inf in u and the other going to -inf in v. (similar to cutting a smaller rectangle out of a larger rectangle both anchored at lower-left point)
Afrozodiacc commentedon Oct 20, 2020
@josef-pkt Thanks for explaining. I'll print the results of the script and attached the plot for your convenience. I'll draw on the intervals for that plot too.
Results print:
Note the region in u, v defined by the intervals.
Now inspecting the kde plot:

Now using some rad paint skills to approximate the region which would be integrated as a yellow box (the result of differencing the cdf on upper and lower bounds).

From Cumulative distribution function and Continuous probability distribution

Meaning that the integration used on the scipy gaussian_kde is mathematically returning the same result as differencing the KDEMultivariate.cdf() on the intervals.
Interestingly, we can see that on those same intervals, the scipy gaussian_kde agrees with statsmodels KDEMultivariate for the univariate cases (p_u_t_sm, p_u_t_sci, p_v_t_sm, p_v_t_sci). However, when it reaches the multivariate case, they do not agree (p_uv_t_sm, p_uv_t_sci). Viewing the KDE plot, it is clear that the integral of the region defined by the intervals should be ~0.0 as there is no density in this u,v region.
Intuitively, in a univariate case, if there is a high probability of u on an interval about 0, and in a univariate case, a zero probability of v on an interval about 20; the probability on a multivariate interval about u=0 and v=20 should be 0 as 20 cannot be an outcome.
josef-pkt commentedon Oct 20, 2020
Those computation are only correct in the univariate case.
look at your second plot
The cdf at the upper right point of the yellow rectangle comprises everything below and to the left of it.
The cdf at the lower left point of the yellow rectangle is the prob for the area below and left of it.
The difference are the segments between the two green lines and the segment between the two red lines. up to the upper right corner of the yellow rectangle. These slices include the center of the high density region.
if you have a rectangular region with corner points
then Prob(rectangle) = cdf(b) - cdf(a) - cdf(d) + cdf(c).
There is a formula for a box in higher dimensions that I saw once, but didn't find again when I wanted to write code for it.
josef-pkt commentedon Oct 20, 2020
There are two unit tests for multivariate cdf against R. So, most likely the results are correct. I don't think there is anything specific to a low density region that would cause a bug.
Also two unit test for cdf in conditional kde (according to a code comment, the conditional mixed data case seems to agree only at 1.5 decimals)
Afrozodiacc commentedon Oct 20, 2020
Thanks @josef-pkt, I realise now that this is what you were trying to explain to me in your previous comment. I've given this a try and the outputs match what I had originally expected. I had made an incorrect assumption about how the .cdf() should be used. Do you think this is an opportunity to improve the documentation on KDEMultivariate.cdf() and similar? Sorry for the inconvenience and thanks for your patience and explanation.
josef-pkt commentedon Oct 20, 2020
doc improvements are always welcome.
If you find a good place to put it, then it would be helpful.
It could also be as an example. We don't have many docstrings with Examples section because we lack the manpower.
I also don't see a notebook for MultivariateKde, otherwise that might have been also a good location.