Skip to content

ENH: Copula and joint distribution - #7254

Closed
tupui wants to merge 23 commits into
statsmodels:mainfrom
tupui:enh_joint_distribution
Closed

tupui wants to merge 23 commits into
statsmodels:mainfrom
tupui:enh_joint_distribution

Conversation

@tupui

@tupui tupui commented Jan 13, 2021 •

Copy link
Copy Markdown
Contributor

This PR's intent is to allow the construction of correlated multivariate distributions.

@pep8speaks

pep8speaks commented Jan 13, 2021 •

Copy link
Copy Markdown

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

Line 243:60: E131 continuation line unaligned for hanging indent

Line 84:30: W292 no newline at end of file
Line 84:30: W292 no newline at end of file
Line 84:30: W292 no newline at end of file

Line 39:70: W292 no newline at end of file

Line 384:73: W292 no newline at end of file

Comment last updated at 2021-04-07 18:23:37 UTC

@tupui
tupui force-pushed the enh_joint_distribution branch from bdfad23 to b03a4b2 Compare January 13, 2021 10:18
@tupui
tupui force-pushed the enh_joint_distribution branch from b03a4b2 to 6e65144 Compare January 13, 2021 10:55
@bashtage

Copy link
Copy Markdown
Member

pdf, logpdf, cdf, and plot would all be valuable methods for any copula.

self.rng = np.random.default_rng(seed)

@abstractmethod
def random(self, n):

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.

Needs to accept an argument random_state that can handle a random_state or BitGenerator object.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

ok sure. I was not sure about the architecture here. If you think something else would be better in general let me know.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

For the accepted values, I propose to not talk about RandomState as we do in stats.qmc to strive people to not use it. Let me know if I should do otherwise.

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 seems fine to me to prefer Generator objects. The problem is that a RandomState has to be default until statsmodels requires NumPy 1.17.

@tupui tupui Jan 13, 2021 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Is there somewhere a function to check the random state? Something like scipy._lib._util.check_random_state. I could not find anything like this. I will use this for now.



class StudentCopula(Copula):
"""Student copula."""

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.

docstrings should have a reasonable amount of mathematicaal detail similar to what scipy does.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

ok I will see to add at least the definition of C. But I am not a mathematician and I would just copy paste. So if you know better, it's better if you do it.

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.

ok I will see to add at least the definition of C. But I am not a mathematician and I would just copy paste. So if you know better, it's better if you do it.

Copy-paste from Wiki is a good start.

@tupui

tupui commented Jan 13, 2021 •

Copy link
Copy Markdown
Contributor Author

pdf, logpdf, cdf, and plot would all be valuable methods for any copula.

  • I added a plot function to the base class. For now it's just doing a scatter plot, not sure what you want more. Of course the best thing would be to have a something like in seaborn.jointplot, but then maybe it's better just to use seaborn if we want that.

  • And the structure for the pdf, logpdf, cdf. But I am really not sure about these. I see some existing work in sandbox/distributions/copula. Can I use this? @josef-pkt is this correct, or you want to do things differently?

@lgtm-com

lgtm-com Bot commented Jan 13, 2021

Copy link
Copy Markdown

This pull request introduces 2 alerts when merging 7dba6ff into 56838f2 - view on LGTM.com

new alerts:

  • 2 for NotImplemented is not an Exception

@tupui

tupui commented Jan 14, 2021

Copy link
Copy Markdown
Contributor Author

@bashtage I added pdf, cdf to all copulas. Also I added a plot_pdf helper (I will overwrite the one for IndependentCopula as constant).

return self.density.cdf(x)

def pdf(self, x):
return self.mv_density.pdf(x)

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.

This is not correct, we need the copula pdf and not the pdf of the multivariate t distribution.
I guess we can implement logpdf (loglike) and get pdf through exp(logpdf)

@josef-pkt

Copy link
Copy Markdown
Member

@tupui you need to add references about from where you took the formulas for individual copula pdf, cdf

@tupui

tupui commented Jan 16, 2021

Copy link
Copy Markdown
Contributor Author

@tupui you need to add references about from where you took the formulas for individual copula pdf, cdf

Of course sure, I will do this next time. I will soon push a fit function for theta. Still thinking a bit more about the interface before proposing you something.

@josef-pkt

Copy link
Copy Markdown
Member

I just found your references in the Copula class.

I will start with the Copula hierarchy, see #7257 now that I have the generator functions fixed and verified.
I will move things out of the sandbox to distributions.copulas and distributions.transforms_copulas, but not today.

The archimedean copulas will subclass the sandbox CopulaArchimedean, but the subclasses can override cdf and pdf with specific implementation, and other things like tau that will come later. Several of the extras can be computed generically using the generator transform.
CopulaArchimedean can subclass top level Copula class that might only have generic or general methods.

your plot functions for 2-dim.
some methods and copulas will have restrictions to work only for bivariate cases.
Extreme value copulas are currently all bivariate and I haven't looked at multivariate extensions.
pdf for multivariate (d>2) EV copulas look difficult in general.

archimedean and elliptical can be multivariate, but I haven't looked at explicit, non-generated cdf and pdf for those.

@tupui

tupui commented Jan 17, 2021

Copy link
Copy Markdown
Contributor Author

I added more ref about dev-copulas in the docstring of the file. Also I adapted the theta from tau functions.

Seeing all your work on sandbox in the other issue, I guess I will wait for you to merge this and I will rebase onto that. If you want me to proceed differently let me know.

return fig

@property
def tau(self):

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.

tau should be analytical or numerical integration

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I will have to do some research here. TBH my knowledge about all this is all here.

@josef-pkt

Copy link
Copy Markdown
Member

@tupui

did you look at how to use quasi-random numbers for copula sampling?
e.g. https://cran.r-project.org/web/packages/copula/vignettes/qrng.html

I think in the past I only looked at univariate and multivariate normal quasi-random numbers based on halton sequences, where we only need univariate ppf.

@tupui

tupui commented Jan 28, 2021

Copy link
Copy Markdown
Contributor Author

@tupui

did you look at how to use quasi-random numbers for copula sampling?
e.g. https://cran.r-project.org/web/packages/copula/vignettes/qrng.html

I think in the past I only looked at univariate and multivariate normal quasi-random numbers based on halton sequences, where we only need univariate ppf.

The only thing I've ever used is the ppf as what I have in the code here. Do we need to add something else?

Pinging some experts from OpenTURNS who might be interested to help/give a hand: @regislebrun @mbaudin47

@regislebrun

Copy link
Copy Markdown

What you need is the conditional quantile function (quantile=ppf). It means, the inverse of the following function:

t->P(X_k<=t|X_1=x_1,...,X_{k-1}=x_{k-1})

You should have a look here for a possible implementation. It is very easy to implement QMC sampling once you have the conditional quantile, which is not so easy to implement efficiently in a generic way. IMO you should consider to rely on OpenTURNS for this kind of computation, but in democracy everybody is free to reinvent the wheel, as we also did in many parts of OpenTURNS ;-)!

@tupui

tupui commented Jan 28, 2021

Copy link
Copy Markdown
Contributor Author

you should consider to rely on OpenTURNS for this kind of computation, but in democracy everybody is free to reinvent the wheel, as we also did in many parts of OpenTURNS ;-)!

You know I like the way it's done in OpenTURNS 😉 But the license is not compatible with statsmodels. So if we want to propose something here, it has to be done here (or from an OK license).

@josef-pkt

Copy link
Copy Markdown
Member

it's mainly the last commit, that changed things too much from my pattern
I need to look more closely to what we still want.

@josef-pkt

Copy link
Copy Markdown
Member

@tupui from where did you get the default values for archimedean theta, e.g. theta=2?

I think there shouldn't be any default values.
We might want to use theta=None in __init__ as sentinel for not having a fixed parameter.
In archimedean we could take specifying theta in init as fixing the parameter. In EV copulas we have several parameters and we would need a different pattern to fix just some of those parameters, e.g. fixing asymmetry parameters.

The removal of args in archimedean and in unit tests can be reversed by amending last commit.

@josef-pkt

josef-pkt commented Apr 5, 2021 •

Copy link
Copy Markdown
Member

still open question: args tuple versus single args, consistency versus convenience ?
current archimedean only have theta argument, but if we add transformations like copula_power_mv_archimedean, then we get more parameters

specific archimedean classes don't have uniy test coverage, and according to codecov, test coverage for pdf, logpdf in Frank copula would be removed.

@tupui

tupui commented Apr 6, 2021

Copy link
Copy Markdown
Contributor Author

@josef-pkt I can add back *args but IMO we should not. It's an anti-pattern and obfuscate code inspection. I am always dying when I have to do some matplotlib for this reason. Using unknown parameters is a famous complain about APIs on StackOverflow, famous python podcasts, etc. We should try to design an interface which does not require the use of *args, at least not on the public API used by final users. Plus, for now we just have theta. Even if we would need to add 2 or even 3 other parameters it would be cleaner than *args.

For the default I took an arbitrary default value. So you want the code to raise if we don't specify theta? I am not a fan of being able to instantiate a class which is in a "broken" state if you don't do some specific actions before. I would propose instead to make theta mandatory and for the case of theta fitted by MLE (or anything else) we can use a classmethod. So something like Copula.from_mle(...).

@josef-pkt

Copy link
Copy Markdown
Member

We need arguments in the functions, otherwise it's messy to create a model that use copulas where the copula parameters are estimated.
My initial pattern was like the scipy stats distribution with (almost) stateless classes, i.e. each method needs all arguments. We can add args in __init__ so we have a combination of frozen/semi-frozen and no-parameter instances.

My guess is that copulas are in many cases not the relevant class for user. Copula distributions and copula (regression) models.

Named parameters are not generic enough for library use. We need a simple common pattern for args/params, so we can build additional features that do not rely on the parameterization of specific copulas.
(I never ever used the named shape parameters in scipy.stats distributions)

The details are still open, we don't have enough models to have much experience with many different parameters, except for packing them in params which only works if we have one parameter value and not vectorized.

E.g. it's more important that we are able to write a multivariate extreme value model based on generic copula interface, than having a userfriendly but inconsistent interface to copulas.

We can allow scalar args in the case of copulas with only a single parameter, but the problem if we go away from tuples is unpacking if there are too many options for how to specify the parameters, and interpretation of broadcasting/shape if we have array parameters.

@tupui

tupui commented Apr 6, 2021

Copy link
Copy Markdown
Contributor Author

OK then your call. I will re-introduce the *args parameter.

TBH I am not a fan of how scipy.stats.distribution works in general because of its two ways of working. It is confusing for the user. I mean, the whole pattern here is breaking 2 "recommendations" from the zen of python: Explicit is better than implicit. and There should be one-- and preferably only one --obvious way to do it.

@josef-pkt

Copy link
Copy Markdown
Member

There should be one-- and preferably only one --obvious way to do it

statsmodels is built on dual use, library and interactive, so we have two obvious ways, one for each use case :)
api, formula, pandas are alternatives to plain numpy and direct imports.

(Pandas was for a long time focused on interactive use and a pain in library use. Most complaints about tidy verse are that it's a pain for code development/maintenance and long term use. The basic structure of statsmodels has lasted for over 10 year and still works well.)

@josef-pkt

josef-pkt commented Apr 6, 2021 •

Copy link
Copy Markdown
Member

possible interface for args:

if args is None and self.args is not None:
    args = self.args
elif not isinsatance(args, tuple):
    args = (args,)

The first part will need to be made more general when only some, but not all parameters of copula are fixed, needed for EV copulas

For elliptical copulas we have two possible cases

  • cov/corr is specified/unrestricted d * (d - 1) parameters, but usually given as cov matrix
  • patterned cov/corr: e.g. banded, equal correlation, ... as in GEE options, and we have only a smaller set of parameters, that could be estimated by MLE.

Using full MLE for elliptical cov will not be coming soon, because there are too many tools missing to estimate patterned cov matrices outside of GEE.

@tupui

tupui commented Apr 6, 2021

Copy link
Copy Markdown
Contributor Author

if args is None and self.args is not None:

args = self.args

elif not isinsatance(args, tuple):

args = (args,)

You mean this is to be used for the methods right? If so I propose to have a common validation function for it so we avoid duplication.

The first part will need to be made more general when only some, but not all parameters of copula are fixed, needed for EV copulas

No sure what this means but I will implement the validation part and you can add stuff there.

  • patterned cov/corr: e.g. banded, equal correlation, ... as in GEE options, and we have only a smaller set of parameters, that could be estimated by MLE.

I don't have this I guess as for now I coded something which needs the matrix. Or I misunderstand what you mean.

@josef-pkt

Copy link
Copy Markdown
Member

to the last point for elliptical cov:
With bivariate we only have one correlation, with many components in the multivariate case, cov will be large and have many parameters. If there is some structure like autocorrelation or equal correlation, then we can estimate a smaller set of parameters and construct the full cov based on those.
We don't have this yet for MLE models, but when we have it, then it will be useful to add the option to copula based models.

about partially fixed params:

The asymmetric EV copulas can have two asymmetry and one correlation parameter. When used for the standard symmetric/exchangable case, then the asymmetry parameters can be fixed to some values or restricted so that both asymmetry parameters are the same. So, partial fixing becomes necessary in fitting when we have a smaller number of free parameters.
If parameters are already given, then it doesn't matter (all params are fixed).

@tupui

tupui commented Apr 7, 2021

Copy link
Copy Markdown
Contributor Author

@josef-pkt I put back args. There is just one test failing now. Not sure.

We still need to decide what to do about CopulaDistribution, Copula and CopulaDistributionBivariate (not used).
Most copulas subclass Copula (the general class I added). We could merge CopulaDistribution and Copula if needed. For the other class, not sure we need it.

Let me know what you think about all that.

@tupui

tupui commented Apr 16, 2021

Copy link
Copy Markdown
Contributor Author

@josef-pkt friendly reminder. Let me know how you want to proceed 😃

@tupui tupui mentioned this pull request Apr 23, 2021
@tupui

tupui commented May 11, 2021 •

Copy link
Copy Markdown
Contributor Author

@josef-pkt Shall I close this one in favour of the new PR?

@josef-pkt

Copy link
Copy Markdown
Member

Leave it open for now, we close it if and when the new PR gets merged.
I still need to compare some things.

I'm trying to write an introductory overview notebook to see how well things work.

@tupui

tupui commented May 11, 2021 •

Copy link
Copy Markdown
Contributor Author

I'm trying to write an introductory overview notebook to see how well things work.

If that can help, I had things like these in a notebook.

import seaborn as sns

from statsmodels.sandbox.distributions.copula import *
from statsmodels.distributions.joint_distribution import *

copula = GumbelCopula(2)
sample = copula.random(10000)

# some plot
h = sns.jointplot(sample[:, 0], sample[:, 1], kind='hex')
h.set_axis_labels('X1', 'X2', fontsize=16)


# another one
copula = ClaytonCopula(0.3)
_ = copula.plot_pdf(10)

# and this
dists = [stats.gamma(2), stats.norm]
copula = GaussianCopula(mean=[0, 0], cov=[[1., 0.5], 
                                          [0.5, 1.]])
sample = copula.random(10000)
h = sns.jointplot(sample[:, 0], sample[:, 1], kind='hex')
h.set_axis_labels('X1', 'X2', fontsize=16)

joint_dist = JointDistribution(dists, copula)
sample = joint_dist.random(512)
h = sns.jointplot(sample[:, 0], sample[:, 1], kind='scatter')
h.set_axis_labels('X1', 'X2', fontsize=16)

@josef-pkt

Copy link
Copy Markdown
Member

do you have your notebook in a gist or somewhere online?

@tupui

tupui commented May 11, 2021

Copy link
Copy Markdown
Contributor Author

do you have your notebook in a gist or somewhere online?

I just had this one online: https://gist.github.com/tupui/d1f2aa721b3994e59283059233a50962
But I did not plot much more than that locally.

@josef-pkt

Copy link
Copy Markdown
Member

I have mostly notebooks for extreme value copulas from when I was working on those, and bernstein copula.

@tupui

tupui commented May 11, 2021

Copy link
Copy Markdown
Contributor Author

copula_sandbox.ipynb.zip

@tupui

tupui commented Jul 25, 2021

Copy link
Copy Markdown
Contributor Author

I will close my PR in favor of #7408 as its now merged.

@tupui tupui closed this Jul 25, 2021
@bashtage bashtage added the rejected Used for PRs with changes that are not acceptable label Apr 14, 2023
@josef-pkt josef-pkt added comp-distributions superseded Used for PRs with content that is superseded by a newer PR and removed rejected Used for PRs with changes that are not acceptable labels Feb 10, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-distributions superseded Used for PRs with content that is superseded by a newer PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SUMM/ENH: resurrecting copulas

6 participants