Skip to content

ENH: add tools.transforms with several Transformation for distributions - #7246

Open
josef-pkt wants to merge 3 commits into
statsmodels:mainfrom
josef-pkt:distribution_transforms
Open

josef-pkt wants to merge 3 commits into
statsmodels:mainfrom
josef-pkt:distribution_transforms

Conversation

@josef-pkt

@josef-pkt josef-pkt commented Jan 7, 2021 •

Copy link
Copy Markdown
Member

see #7241
see #7244 SUMM issues about transformation and function collections

edit maybe look also at Box-Cox Cole Green distribution (BCCG) #4256

provides Transformation classes for creating flexible 3 or 4 parameter distributions based on transformation of variables.

Main part missing for generic usage in models are derivatives with respect to the params.
related to derivatives #7245

For some models we might get case specific derivative, e.g. articles for sinh-arcsinh-t regression with score and hessian.

This has comprehensive unit tests for checking internal consistency, but no outside verification

@lgtm-com

lgtm-com Bot commented Jan 7, 2021

Copy link
Copy Markdown

This pull request introduces 36 alerts when merging eb3da63 into 2c66afb - view on LGTM.com

new alerts:

  • 36 for Unused local variable

@josef-pkt

josef-pkt commented Jan 7, 2021 •

Copy link
Copy Markdown
Member Author

one unrelated failure in statsmodels\tsa\statespace\tests\test_exact_diffuse_filtering.py:1028: AssertionError on only one environment, WindowsTest python37_win_latest

this PR has some whitespace pep-8 and unused variables in LGTM, params unpacked but not used
test coverage missing for Inverted class, otherwise full coverage

mistake in comments
TMI has the added 1/2 compared to TMI_, TMI corresponds to Stephens
There are no params in TMI. Loc-scale of base distribution should be params in TMI as in Johnson-SU, but the Stephens' article didn't add them.

I might privatize TMI_ for now to _TMI1. I think I have seen something like this in another article, but don't remember. I don't want to throw it away yet.

@josef-pkt

Copy link
Copy Markdown
Member Author

I still need simple chaining to get equivalent classes that I can use for unit tests, e.g. log version of other transformations.

Another question is then how to get equivalent parameterization and the corresponding parameter transformation. I'm not sure how generically that will work or if it is distribution/transform dependent.

@josef-pkt
josef-pkt force-pushed the distribution_transforms branch from eb3da63 to d3864e0 Compare January 7, 2021 18:20
@josef-pkt

josef-pkt commented Jan 7, 2021 •

Copy link
Copy Markdown
Member Author

amended commit with pep-8 cleaning and rename TMI_ to _TMI1, and force pushed

I still left unused explicit params argument in method signatures

@josef-pkt

josef-pkt commented Jan 7, 2021 •

Copy link
Copy Markdown
Member Author

checking birnbaum-saunder-normal distribution against scipy.stats.fatiguelife (other common name of BS)

looks like the shape parameter is the same

params = (0.5, 1)
transf = BirnbaumSaunders()
zz = np.linspace(1e-5, bounds, 200)
pdf = np.abs(tr.deriv_inverse(zz, params)) * kls._pdf(tr.inverse(zz, params))
pdf_sps = stats.fatiguelife.pdf(zz, 0.5)

np.max(np.abs(pdf_sps - pdf)), np.max(np.abs((pdf_sps / pdf)[1:] - 1))
 
(4.440892098500626e-16, 7.549516567451064e-15)

I'm skipping first element for rtol because pdf is zero

agreement is higher than I expected, only floating point noise at limit of double precision.
(numerical problems usually show up only close to boundary points or extreme values)

update
random number generation works identical in BS and fatiguelife
Transf_gen is an adjusted class from sandbox.distributions.transformed
work in progress, args handling is messy with parameters in both transformation and distribution

bs = Transf_gen(stats.norm, transf, params)

np.random.seed(987145)
bs.rvs(size=5)
array([1.18156459, 2.07944594, 1.37845085, 1.22460191, 1.35943199])

np.random.seed(987145)
stats.fatiguelife.rvs(0.5, size=5)
array([1.18156459, 2.07944594, 1.37845085, 1.22460191, 1.35943199])

update 2
using expect for numerical integration to get central moments

bs.expect(lambda x:x, lb=0, ub=np.inf), bs.expect(lambda x:(x - 1.125)**2, lb=0, ub=np.inf)
(1.1249999999999976, 0.3281249999999996)

stats.fatiguelife.stats(0.5)
(array(1.125), array(0.328125))

@josef-pkt

Copy link
Copy Markdown
Member Author

extra: what do we need in the transformation for logpdf i.e. loglikelihood?

log jacobian? i.e. log_deriv_inverse in case it has a simpler form than explicit log

@josef-pkt

Copy link
Copy Markdown
Member Author

different parameterization, standardizing coefficient.

sinh in log-birnbaum-saunders article has a multiplicative factor 2 / alpha in the transformation. This differs from johnson-su and my Sinh transformation. I guess alpha is parameter that I don't have yet or related to scale, but there is still the extra 2.
Similarly, TMI1 and TMI just differ in a multiplication by 2 in transform.

It's difficult to figure out how to match up parameterizations

the following matches visually, but parameters are just by trial-and-error

yy = np.linspace(-bounds, bounds, 200)
b = 0.125
plt.plot(yy, stats.johnsonsu.pdf(yy, 0, 1/b, scale=4))
r = plt.hist(np.log(stats.fatiguelife.rvs(0.5, size=10000)), bins=np.linspace(-bounds, bounds, 80), density=True)

another generalized BS and sinh article uses scaled log-transform y = 0.5 * log(x)

I'm not sure there are "standard" definitions for these distributions. Do I need to add extra params that are just normalizing or standardizing coefficients like the 2 above? Those are fixed definitional coefficients and not used as transform and distribution parameters.

Aside: IIRC, the wikipedia page for log-normal has a good list and descriptions for possible parameterization of the log-normal distribution, with clear distinction of where e.g. loc and scale refer to the original or transformed distribution.

@josef-pkt

josef-pkt commented Jan 8, 2021 •

Copy link
Copy Markdown
Member Author

parameterization (continued)

I think for the distribution we want to keep loc-scale of final, transformed variable out of the transformation, similar to scipy.
i.e. we define some standardized distribution, that can be linear or affine transformed with loc and scale.
In R+ only scale change makes sense in most applications, for when we have positive data.
In interval, we might use loc-scale for shifting and stretching the interval but that's an unusual case, and won't be easy to support with MLE anyway, i.e. support of the distribution cannot be in params for MLE for standard theory to apply.

A multiplicative factor on the transform changes the scale of the transformed variable.
A multiplicative factor on the inverse changes the scale of the original, base variable.

Tensorflow makes a scale adjustment to the transform to fix a quantile.


generalized BS or TMI transform, with different powers

choosing multiplicative factor 1/2 in transform similar to TMI versus TMI1 makes a "nicer" inverse function, e.g.

solve x = (1 / 2  * (z^(c) / b^(c) - z^(-c) / b^(-c))) for z
z = (sqrt(x^2 b^(2 c) + b^(2 c)) + x b^c)^(1/c)

formula looks better in latex processed math

The second article on power generalized BS Diaz-Cardia and Domingues-Molinea 2006 does not use 1/2 in inverse transform but adds scale parameter alpha
(1 / a * ( (z / b)^(c) - (z / b)^(-c))) where a is alpha, and c is their lambda

I'm getting confused again, a is scale for based r.v. because we are working with inverse transform. So I need alpha as transform param.

solve x = (1 / (2 *a)  * (z^(c) / b^(c) - z^(-c) / b^(-c))) for z
z = (sqrt(a^2 x^2 b^(2 c) + b^(2 c)) + a x b^c)^(1/c)

without the 1/2

solve x = (1 / (a)  * (z^(c) / b^(c) - z^(-c) / b^(-c))) for z
z = 2^(-1/c) (sqrt(a^2 x^2 + 4) b^c + a x b^c)^(1/c)

another version: using exponent c / 2 analogous to sqrt in BS, so that BS is special case c=1

solve x = (1 / (2 * a)  * (z^(c/2) / b^(c/2) - z^(-c/2) / b^(-c/2))) for z
z = (sqrt(a^2 x^2 b^c + b^c) + a x b^(c/2))^(2/c)

edit
power c > 1 will t**c convex, diaz-garcia only mention lambda > 0 as restriction
I guess c > 1 will not make much sense, there should be integration problems as x -> inf, but that depends on tail power behavior.
Maybe not a problem, we don't have problems with exp transformation e.g. log-normal. Distribution with power tails might just have heavier power tails with larger (?) rate than untransformed if c>1.
Maybe using c/2 is a better "interior" specification. using just c would have nicer interpretation for c = 1, i.e. linear minus inverse.
(I need to find some articles that use this generalization of BS.)

current code

Birnbaum Sounders inverse no 1/2: xrev = 1 / a * (np.sqrt(z / b) - np.sqrt(b / z))
_TMI1 inverse, no 1/2 in analogy to BS: xrev = (t - 1 / t)
TMI inverse, with 1/2 following Jones: xrev = 1/2 * (t - 1 / t)

b in BS is scale of transformed variable, i.e. xrev = 1 / a * (sqrt(t) - sqrt(1 / t)) without scale

@josef-pkt

josef-pkt commented Jan 8, 2021 •

Copy link
Copy Markdown
Member Author

including loc-scale changes in transforms?

the general pattern is

standard base distribution -> affine, loc-scale transform -> nonlinear transform -> affine, loc-scale transform -> transformed distribution

Base distribution and all 3 transforms can have params, but, depending on the transform, some params will be redundant.
Also, we might not want to use some params in common use cases, e.g. changing loc of distribution on R+.

In the models we need just params, i.e. y ~ F(params), so we can use regression to model some of the params.

Alternatives:

required as scipy distribution: we need loc-scale family
standard base distribution -> affine, loc-scale transform -> nonlinear transform -> transformed loc-scale family of distributions

we can also merge the loc-scale transformation into the nonlinear transform
standard base distribution -> affine, loc-scale transform + nonlinear transform -> transformed loc-scale family of distributions

or we could use loc-scale family as base distribution
base loc-scale family of distributions -> nonlinear transform -> transformed loc-scale family of distributions

or we merge all transforms
standard base distribution -> affine, loc-scale + nonlinear + affine, loc-scale transform -> transformed loc-scale family of distributions

current code is a mix of the above

Sinh/johnson-su includes base loc-scale
BirnbaumSaunders include base and final scale but no loc. AFAICS. Initial loc could be changed, I guess, but I haven't it seen yet.
TMI and RtoInterval do not include any loc-scale transformation
SinhArcsinh transform does not include any (explicit ?) loc-scale transformation, but in articles loc-scale of base are never changed, loc-scale of transformed distribution needs to be added, i.e. SinhArcsinh creates loc-scale family on R,

update

I think we merge loc-scale of base distribution into the transform, if applicable, i.e. not in SinhArcsinh. Then we only have shape parameters of the base distribution as extra params layer. If there are no shape parameters as in normal distribution, then we don't need to chain the extra layer of params.
However, this does not work if we invert the distribution, i.e. go from transformed distribution back to base distribution like log the log-normal random variable.

If we merge both loc-scale transformation into the nonlinear transformation, then we don't get a scipy compatible loc-scale family, unless we fix loc-scale parameters in the transformed distribution before applying scipy's loc-scale treatment.
Note, my main idea for Inverse class was for simple cases like using exp instead of log and flipping transform and inverse.

I still don't have code that uses params in a non-trivial way. Adding loc-scale anywhere to transform or inverse is trivial in usage, but it will get more difficult for derivatives and estimation.

good case for checking: BS-t(df) versus TMI-t(df), and get fully parameterized log(pdf), loglike for an MLE model

@josef-pkt
josef-pkt force-pushed the distribution_transforms branch from d3864e0 to f91a598 Compare January 14, 2021 14:19
@josef-pkt

Copy link
Copy Markdown
Member Author

amended and force pushed again
some corrections to docstrings

@josef-pkt

Copy link
Copy Markdown
Member Author

added a change in docstring to check whether renaming of master branch works

@josef-pkt

Copy link
Copy Markdown
Member Author

more on parameterization, based on log-normal and log-logistic

We can parameterize distributions like log-normal in terms of the e.g. gaussian base distribution, e.g. loc-scale, or as parameters of the final distribution, shape-scale,
We have four parameters, but can choose from two possible subset. (or more possible combinations if I remember Wikipedia list correctly)
If we start with 4 parameters, then we can model both the "traditional" parameterization and the scipy parameterization as shape-loc-scale family. But we need to restrict the parameters to a subset to avoid overparameterization and non-identification.

In the final distribution we can only add loc-scale, shape parameters will be determined by original, base distribution and parameters of the transform. I think this limits us to still use some of the original parameters as final shape parameter, whether it's included in the base distribution or in the transform.

(I guess for log-normal: use scale of original gaussian as final shape parameter, and scale of the final distribution as substitute for mean of original gaussian.)

@josef-pkt

josef-pkt commented Sep 1, 2021 •

Copy link
Copy Markdown
Member Author

namings are a pain

Here I used deriv_inverse, genmod links use inverse_deriv, similar for deriv2
Copula depfuncs_ev for EV and transform for archimedean do not have derivatives of inverse function yet.

deriv_inverse would be better because it has qualifier as post-fix, but links are old established code, but not all have deriv2 inverse yet.
(I needed to reverse the name several times while working on cdf links in #7287 )

Either version of the names can be justified in terms of ordering methods.

@josef-pkt josef-pkt modified the milestones: 0.14, 0.15 Nov 30, 2022
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