Skip to content

ENH/TST: archimedean rvs for k_dim>2, test/gof tools - #8642

Merged
josef-pkt merged 5 commits into
statsmodels:mainfrom
josef-pkt:copula_archim_rvs_mv
Feb 2, 2023
Merged

josef-pkt merged 5 commits into
statsmodels:mainfrom
josef-pkt:copula_archim_rvs_mv

Conversation

@josef-pkt

@josef-pkt josef-pkt commented Feb 1, 2023 •

Copy link
Copy Markdown
Member

trying to extend archimedean rvs to general k_dim

It looks like the current formulas immediately extend to k_dim > 2.

However, I have problems creating unit tests for it. We need some gof statistics to check whether the generated data has distribution close to the data generating distribution (rvs).
2-dim marginals of k_dim = 3 look good, graphically and with approximate gof test.
But it doesn't work for full k_dim=3 copula.

Current helper function in test_copula was written for 2-d case and does not work for k_dim=3. When I fix it, it rejects the null for the archimedean. Limitation is that function uses approximation using pdf instead of cdf.
check_cop_rvs(cop, rvs=None, nobs=2000, k=10, use_pdf=True)

We need better helper tools for mv distribution approximation for k-dim>2.
eg. in statsmodels.distributions.tools, approx_copula_pdf, frequencies_fromdata, and helper functions
no approx_copula_cdf yet AFAICS.
nearest_matrix_margins is only for k_dim=2, #7444

I had used some of those parts with uncommitted extensions when checking BernsteinDistribution.
related: #7470 #7302

@josef-pkt

Copy link
Copy Markdown
Member Author

using cdf instead of averaged pdf in copula approximation solves the problem
Null for data comes from data generating distribution not rejected anymore

cop2, cop are Clayton copulas with k_dims 2 and 3
theta=1.5, nobs=5000

# check pairwise marginals
tres01, _ = check_cop_rvs(cop2, rvs=x[:, [0, 1]], nobs=x.shape[0])
tres02, _ = check_cop_rvs(cop2, rvs=x[:, [0, 2]], nobs=x.shape[0])
tres12, _ = check_cop_rvs(cop2, rvs=x[:, [1, 2]], nobs=x.shape[0])
tres01, tres02, tres12
(Power_divergenceResult(statistic=207.69468360449144, pvalue=1.0564130381294783e-09),
 Power_divergenceResult(statistic=194.4755483547901, pvalue=3.42041302460698e-08),
 Power_divergenceResult(statistic=189.1391006302774, pvalue=1.3130227718987082e-07))

tres01, _ = check_cop_rvs(cop2, rvs=x[:, [0, 1]], nobs=x.shape[0], use_pdf=False)
tres02, _ = check_cop_rvs(cop2, rvs=x[:, [0, 2]], nobs=x.shape[0], use_pdf=False)
tres12, _ = check_cop_rvs(cop2, rvs=x[:, [1, 2]], nobs=x.shape[0], use_pdf=False)
tres01, tres02, tres12
(Power_divergenceResult(statistic=107.05865761901903, pvalue=0.2726058355374828),
 Power_divergenceResult(statistic=102.57117186881077, pvalue=0.3828274001198413),
 Power_divergenceResult(statistic=116.51081256967058, pvalue=0.11037113005209513))

# check joint copula, first pdf approximation (reject), then cdf approximation for cell probabilities (not reject)
tres, _ = check_cop_rvs(cop, rvs=x, nobs=x.shape[0])
tres
Power_divergenceResult(statistic=1787.9216062511778, pvalue=2.0164422974270272e-47)

tres, _ = check_cop_rvs(cop, rvs=x, nobs=x.shape[0], use_pdf=False)
tres
Power_divergenceResult(statistic=957.5614322651743, pvalue=0.8225763917280389)

@josef-pkt

josef-pkt commented Feb 1, 2023 •

Copy link
Copy Markdown
Member Author

student-t rvs test fails now,
some change in 1st commit messed up the gof check
The only relevant change is setting force_uniform to False in unit test
pdfg = approx_copula_pdf(cop, k_bins=k, force_uniform=False) #True)
I had changed that because force_uniform is not yet supported for k_dim > 2.

self = <test_copula.TestStudentTCopula object at 0x7f98cb94b760>

    def test_rvs(self):
        super().test_rvs()
    
        chi2t, rvs = check_cop_rvs(
            self.copula, rvs=self.rvs, nobs=2000, k=10, use_pdf=True
        )
>       assert chi2t.pvalue > 0.1
E       assert 4.7768361310647686e-08 > 0.1
E        +  where 4.7768361310647686e-08 = Power_divergenceResult(statistic=193.16344095875135, pvalue=4.7768361310647686e-08).pvalue

@josef-pkt

Copy link
Copy Markdown
Member Author

kendalltau

in exchangeable archimedean:
I guess we can use average kendalltau as estimate of tau.
any reference for this?

e.g. simulated 3d rvs
​

x.shape, theta
((5000, 3), 1.5)

from scipy import stats
k = x.shape[-1]
taus = [stats.kendalltau(x[..., i], x[..., j])[0] for i in range(k) for j in range(i+1, k)]
taus, np.mean(taus)
([0.4326974194838968, 0.41930658131626325, 0.43801656331266253],
 0.4300068547042742)

cop.tau(theta=theta)
0.42857142857142855

@josef-pkt

Copy link
Copy Markdown
Member Author

PR might be good enough to merge
docstrings still need to be adjusted

making chisquare gof test public is too early, it's still in unit test module,
We need boundary correction, e.g. if cdf is undefined at zeros.

@josef-pkt josef-pkt added this to the 0.14 milestone Feb 1, 2023
@josef-pkt

Copy link
Copy Markdown
Member Author

I forgot to add the changes to generalized nearest_matrix_margins to dim>2

@josef-pkt

Copy link
Copy Markdown
Member Author

still something strange: GaussianCopula with k_dim =3 fails the gof unit test, with both use_pdf True and False.
A version of the gof unit test example for a GaussianCopula worked this morning before I made the changes.
???

class TestGaussianCopula3d(CheckRvsDim):
    copula = GaussianCopula(corr=[[1.0, 0.5, 0.2], 
                                  [0.5, 1.0, 0.2],
                                  [0.2, 0.2, 1.0]], k_dim=3)
    dim = 3
    use_pdf = True

I'm changing fit_corr_param method to use average tau for k_dim>2 similar to unit test.

@josef-pkt

Copy link
Copy Markdown
Member Author

Gaussian copula rvs looks correct.

problem must be in some changes to check_cop_rvs

the following also checks new changes to gaussian copula.fit_corr_param(rvs)

nobs = 5000
rng = np.random.RandomState(None) #97651629) #27658622)
rvs = copula.rvs(nobs, random_state=rng)
for use_pdf in [True, False]:
    chi2t, rvs = check_cop_rvs(
        copula, rvs=rvs, nobs=nobs, k=10, use_pdf=use_pdf
        )
    print(chi2t)
Power_divergenceResult(statistic=3238.1495998800356, pvalue=6.104913591846298e-234)
Power_divergenceResult(statistic=3217.3785610779187, pvalue=8.018969862277639e-231)


k = copula.k_dim
assert k == rvs.shape[1]
taus = [stats.kendalltau(rvs[..., i], rvs[..., j])[0]
        for i in range(k) for j in range(i+1, k)]
​
a = np.eye(3)
a[np.triu_indices(3, 1)] = taus
a.T[np.triu_indices(3, 1)] = taus
tau_mat = a
​
tau = np.mean(taus)
tau_cop = copula.tau()
theta_est = copula.fit_corr_param(rvs)
taus, tau_mat, tau_cop, "", theta_est, np.corrcoef(rvs.T), copula.corr
([0.3358351670334067, 0.12170450090018003, 0.11863316663332667],
 array([[1.        , 0.33583517, 0.1217045 ],
        [0.33583517, 1.        , 0.11863317],
        [0.1217045 , 0.11863317, 1.        ]]),
 array([[1.        , 0.33333333, 0.12818843],
        [0.33333333, 1.        , 0.12818843],
        [0.12818843, 0.12818843, 1.        ]]),
 '',
 array([[1.        , 0.5033995 , 0.19001064],
        [0.5033995 , 1.        , 0.1852719 ],
        [0.19001064, 0.1852719 , 1.        ]]),
 array([[1.        , 0.48586411, 0.18166338],
        [0.48586411, 1.        , 0.17800615],
        [0.18166338, 0.17800615, 1.        ]]),
 array([[1. , 0.5, 0.2],
        [0.5, 1. , 0.2],
        [0.2, 0.2, 1. ]]))

@josef-pkt

Copy link
Copy Markdown
Member Author

The bug in check_cop_rvs is because of different orientation of the grid matrix (k, k, ... k)
If I transpose one grid, then the gaussian copula gof unit tests does not fail.

This did not show up before because the previous cases were with exchangeable components, archimedean and I had used a gaussian example with equal correlation (all off diagonals of corr the same).

Another problem with current implementation:
I merge all cells with expected count < 5 with no lower limit on number of cells. If nobs is too small relative to number of cells k_bins * k_dim, the we merge everything into one cell (or two cells?) in the extreme. That will be unlikely to reject (no power).
Trying a few random cases right now, I get very large gof p-values (close to 1) for null gaussian case.

Also, check_cop_rvs seems to be a bit slow with 1000 or a few thousand nobs.

@josef-pkt

Copy link
Copy Markdown
Member Author

what a pain. confusing myself. I thought I had another bug and wasting a lot of time on it

copula = GaussianCopula(corr=[
[1.0, 0.5, 0.2],
[0.5, 1.0, 0.2],
[0.2, 0.2, 1.0]], k_dim=3)

the correlation matrix in the new test case is still partially exchangeable
relationship of component 3 with components 1 and 2 is the same, i.e. marginal distribution (0, 1) is the same as (0, 2) (using indices)
I thought I had made an indexing bug in one of my helper functions.

now I use
corr=[
[1.0, 0.8, 0.1],
[0.8, 1.0, 0.3],
[0.1, 0.3, 1.0]]
and bivariate margins differ.

@josef-pkt

Copy link
Copy Markdown
Member Author

now includes rvs gof unit test for gaussian and studentt with k_dim=3

aside: still problem with genericlikelihoodmodel df_xxx in CopulaModel
CopulaModel is only defined in the unit test modul, not public yet

statsmodels/distributions/copula/tests/test_model.py::TestGumbel::test
  ...\statsmodels\statsmodels\base\model.py:2745: UserWarning: df_resid differs from nobs - k_params
    warnings.warn("df_resid differs from nobs - k_params")

@josef-pkt

Copy link
Copy Markdown
Member Author

AFAICS, the transpose bug is in using reshape with order="F" in approx_copula_pdf
unit test pass if I drop the order keyword instead of transposing.

the unit tests for Bernstein, for example TestBernsteinBeta2d, use c order reshape
cdf_g = cdfv.reshape(grid.k_grid)
Bernstein tests use approx to archimedean and are only for k_dim=2.

test_tools.py test_grid_class has a k_dim=3 unit test, but does not test reshape
AFAICS, _Grid class never constructs or uses a k_dim array, only works with flat array and indices. this avoids the numpy max ndim limitation.
_Grid class could be enhanced with helper methods and generalization to non-constant x_marginal increments, i.e. user specified x_marginal.
not now

@josef-pkt
josef-pkt force-pushed the copula_archim_rvs_mv branch from cd41c2e to 70ddfb5 Compare February 2, 2023 18:05
@josef-pkt

Copy link
Copy Markdown
Member Author

unrelated problem with azure test environments
merging

@josef-pkt
josef-pkt merged commit 6d5f746 into statsmodels:main Feb 2, 2023
@josef-pkt josef-pkt mentioned this pull request Feb 3, 2023
16 of 20 tasks
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