Skip to content

REF: change default derivative in CDFLink - #7287

Merged
josef-pkt merged 7 commits into
statsmodels:mainfrom
josef-pkt:improve_cdflink2
Sep 3, 2021
Merged

josef-pkt merged 7 commits into
statsmodels:mainfrom
josef-pkt:improve_cdflink2

Conversation

@josef-pkt

Copy link
Copy Markdown
Member

this is part of #7226 that is not included in #7286

related change that should be included here is numerical derivative #1783

@josef-pkt josef-pkt changed the title REF: change default numerical derivative in CDFLink REF: change default derivative in CDFLink Jan 26, 2021
@josef-pkt josef-pkt added this to the 0.13 milestone Jun 4, 2021
@josef-pkt

Copy link
Copy Markdown
Member Author

related issue #1878

I wanted to get this in the next release, needs checking again, maybe with some more cdflinks, or a generic cdf/scipy distribution link class.
temporarily prio-elev

@josef-pkt

josef-pkt commented Jul 20, 2021 •

Copy link
Copy Markdown
Member Author

student t link would be useful to add and a good test case, and can be compared with cauchy and probit link as verification.

It looks easy enough to get cdf, inverse_deriv = pdf and inverse_deriv2 = d pdf(x) / dx
derivatives of link might not be easy, except though the generic formulas used here.

parking derivative from wolfram alpha

d/dx c * (1 + x^2 / v )^{- (v+1)/ 2)
-(c (v + 1) x ((v + x^2)/v)^(1/2 (-v - 3)))/v
https://www.wolframalpha.com/input/?i=d%2Fdx+c+*+%281+%2B+x%5E2+%2F+v+%29%5E%7B-+%28v%2B1%29%2F+2%29

d^2/dx^2 (c (1 + x^2/v)^(-1/2 (v + 1)))
c v^((v + 1)/2) (v + 1) (v + x^2)^(1/2 (-v - 5)) ((v + 2) x^2 - v)

@josef-pkt

Copy link
Copy Markdown
Member Author

related: NegativeBinomial link does not specify inverse_deriv2

(from Wolfram alpha:)

d^2/dz^2 -1/(alpha * (1 - exp(-z))) =
-(e^z (e^z + 1))/(α (e^z - 1)^3)

CLogLog also does not have inverse_deriv2
d^2/dz^2(1 - exp(-exp(z))) = -e^(z - e^z) (e^z - 1)

deriv:
d/dz(1 - exp(-exp(z))) = e^(z - e^z)

loglog uses inverse_deriv2 = self.inverse_deriv(z) * (np.exp(-z) - 1)
the same pattern can be used of cloglog

log and logit are also missing inverse_deriv2

@josef-pkt

Copy link
Copy Markdown
Member Author

cdflink equivalent of other links

loglog is gumbel_r, cloglog is gumbel_l

gl_link = links.CDFLink(dbn=stats.gumbel_l)
gr_link = links.CDFLink(dbn=stats.gumbel_r)

gl_link(x) == links.cloglog()(x)
gr_link(x) == links.loglog()(x)

should be good for unit tests

@josef-pkt

josef-pkt commented Aug 31, 2021 •

Copy link
Copy Markdown
Member Author

something wrong with default deriv (the two cdflinks only specify the distribution)

link1 = gl_link
link2 = links.cloglog()
methods = ['__call__', 'deriv', 'deriv2', 'inverse', 'inverse_deriv', 'inverse_deriv2']
​
for m in methods:
    res1 = getattr(link1, m)(p)
    res2 = getattr(link2, m)(p)
    #print(m, res1 - res2)  # np.max(np.abs(
    print(m, np.max(np.abs(res1 - res2)))
 
__call__ 0.0
deriv 11.0
deriv2 2.0282409596214406e+31
inverse 0.0
inverse_deriv 0.0
inverse_deriv2 4.944424314423657e-10
link1 = gr_link
link2 = links.loglog()
methods = ['__call__', 'deriv', 'deriv2', 'inverse', 'inverse_deriv', 'inverse_deriv2']
​
for m in methods:
    res1 = getattr(link1, m)(p)
    res2 = getattr(link2, m)(p)
    #print(m, res1 - res2)  # np.max(np.abs(
    print(m, np.max(np.abs(res1 - res2)))
 
__call__ 0.0
deriv 11.0
deriv2 2.028240960290794e+31
inverse 0.0
inverse_deriv 5.551115123125783e-17
inverse_deriv2 5.913727840756167e-12

update

the problem is at the boundaries which I had included p = np.linspace(0, 1, 5)
deriv and deriv2 are not accurate at around 0 and 1 in terms of diff/atol (derivatives are huge)

also p in link is clipped

links.logit().inverse_deriv([-300, 300])
array([5.14820022e-131, 5.14820022e-131])

pl = links.logit().inverse([-300, 300])
pl
array([5.14820022e-131, 1.00000000e+000])

links.logit().deriv(pl)
array([4.50359963e+15, 4.50359963e+15])
links.logit().deriv([0, 1])   # link clips p
array([4.50359963e+15, 4.50359963e+15])

cdflink (link.inverse is cdf)
deriv and deriv2 go to inf (or -inf) at boundaries
inverse_deriv (pdf) goes to zero

looks like using derivatives of inverse would be more stable as multiplicative factors (-> 0, instead of -> inf).

for unit tests: If I want to pass current tests for probit at atol/rtol at around 1e-5, then I need to clip at 1e-3, e.g.

p = np.linspace(0, 1, 6)
p = np.clip(p, 1e-3, 1-1e-3)

aside: using even number of points avoids p = 0.5 at which deriv2 is zero (error ratio become nan/inf)

@josef-pkt

Copy link
Copy Markdown
Member Author

This includes now some refactoring and enhancements for numdiff scalar parameter case, enough for what I need in links and transforms with vectorized scalar derivative.
#1783 (comment)

@josef-pkt

Copy link
Copy Markdown
Member Author

error/exception in unit tests for Markovswitching.

type problem not wrong numbers or shape, there is no asarray in approx_fprime_cs, also not in approx_fprime

>       n = x.shape[-1]
E       AttributeError: 'list' object has no attribute 'shape'

@josef-pkt

Copy link
Copy Markdown
Member Author

no the error looks more serious, problem with shape and dim handling (I don't see an obvious reason for the error)

>   partials = [f(x+ih, *args, **kwargs).imag / epsilon[i]
                for i, ih in enumerate(increments)]
E   IndexError: index 1 is out of bounds for axis 0 with size 1

I will also move the vectorized scalar case for cs to a new function. Less risky and simpler.

@josef-pkt

Copy link
Copy Markdown
Member Author

still same error

parameter x in test case is 2-d row vector case = [[0, 1.]]

I have to revert also the change len(x) -> asarray(x).shape[-1]
The unit test statsmodels/tsa/regime_switching/tests/test_markov_switching.py:305 relies on the current unspecified behavior for a 2-dim row.
The strange thing with the unit test is that the number and shape of returns of f and of derivatives changes with the extra dimension in the x.

It's only a test case, no non-test code breaks (as far as code is run in unit tests)

@josef-pkt

Copy link
Copy Markdown
Member Author

I'm avoiding 2-d refactoring changes to current approx_fprime function in this PR.
That case needs more clarification before making changes. new issue #7680 for that

@josef-pkt

josef-pkt commented Sep 2, 2021 •

Copy link
Copy Markdown
Member Author

bad design: binary links subclass Logit and might inherit the wrong methods.

I was testing inherited behavior with a minimal class, but it produces wrong numbers instead of raising NotImplementedError

class MyCLogLog(links.Logit):
    def __call__(self, p):
        p = self._clean(p)
        return np.log(-np.log(1 - p))

According to code comments, the only reason to inherit from Logit is the _clean method.

naming:
IntervalLink the domain is the unit interval, that's more general than calling it a binary link. The main application are for proportions and fractions.

It might be useful to allow link users to change default for epsilon in _clean

@josef-pkt

Copy link
Copy Markdown
Member Author

current base class Link requires __call__, inverse and deriv

e.g. this works as minimal class (aside requires complex numbers, approx_fprime_cs before this PR and the cs_scalar version in my next change

class MyCLogLog(links.Link):

    def __call__(self, p):
        # p = self._clean(p)
        return np.log(-np.log(1 - p))

    def inverse(self, z):
        return 1 - np.exp(-np.exp(z))

    def deriv(self, p):
        # p = self._clean(p)
        return 1. / ((p - 1) * (np.log(1 - p)))

I add it as unit test case but will not change it here.

@josef-pkt

Copy link
Copy Markdown
Member Author

PR should be about ready for merge.

file search doesn't find other cases of np.diag(approx_fprime

@josef-pkt
josef-pkt merged commit b0ce269 into statsmodels:main Sep 3, 2021
@josef-pkt
josef-pkt deleted the improve_cdflink2 branch October 19, 2022 19:55
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