Skip to content

ENH: Relative tolerance for GLM convergence - #2803

Merged
josef-pkt merged 1 commit into
statsmodels:masterfrom
thequackdaddy:iteration
Jun 1, 2016
Merged

josef-pkt merged 1 commit into
statsmodels:masterfrom
thequackdaddy:iteration

Conversation

@thequackdaddy

Copy link
Copy Markdown
Member

Hello,

I'd like to propose changing how you do convergence checking for GLM IRLS fits.

A few notes:

  1. Currently, I think the iteration check for IRLS has an off-by-1 error. The 1st run check's the 0th iteration vs. the -1st iteration. The 2nd iteration will check the 1st and 0th. The 3rd with check the 1st and the 2nd, and so on.
  2. I've been playing with statsmodels on some insurance datasets. I typically get really large datasets (hundreds of thousands of observations). I'm having difficulty getting convergence in reasonable times because the convergence tolerance is an absolute 1e-8. I think this makes more sense because deviance increases as you add more observations. On a large dataset, waiting for deviance changes as small as 1e-8 requires many (essentially useless) iterations.
  3. As a result of 2., a few of the tests break. I think my tolerance is a little more lenient so you lose a few significant digits. I'll work through that, but I want to know if this is a PR that you'd consider before I invest the time in fixing that.

Thanks for your consideration.

@josef-pkt

Copy link
Copy Markdown
Member

Thanks for pointing this out

some unsorted thoughts

  • in general I don't like replacing absolute tol with relative tol. I think we could add rtol similar to np.allclose
  • using only rtol for deviance might run into problems when deviance is zero or goes to zero. Deviance is zero in saturated log-linear model for example.
  • I didn't realize that the convergence criterion is in terms of deviance and not parameters. I thought we usually check convergence in parameters. (Problem in the case of complete separation is that deviance or loglike can converge but not params).
  • deviance scales with nobs, so maybe there the deviance criterion should divide by nobs (average per unit)

a tip

  • (requires master but not recent, IIRC): Did you try fit(... method='bfgs') or method='newton'.
    We have now the main scipy optimizers also available in GLM. In some cases it converges faster.

scipy optimizers all have tolerance absolute and in terms of parameters, IIRC

as a workaround:
does it help in your case if you set tol=1e-8 * nobs. I guess it might need another factor for full scaling with nobs.

We need to do something, but I'm not quite sure what.

(I haven't looked at off-by-1 yet.)

@josef-pkt

Copy link
Copy Markdown
Member

@kshedden Any opinion on this?

def _check_convergence(criterion, iteration, tol):
return not (np.fabs(criterion[iteration] - criterion[iteration-1]) > tol)
if iteration == 0:
return False

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.

Why did you need to special case iteration 0?
We could have converged after one iteration.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Maybe I'm confused, but the 0th element of criterion[iteration] is set to be np.inf. The first iteration will compare np.inf vs. the deviance after the first IRLS iteration. So, it shouldn't converge ever.

So I think you are right, we don't need the iteration == 0 case as np.inf - x should always be > tol.

No?

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.

I think you are right in general. We need one extra iteration to check convergence even with gaussian and OLS, because we don't know yet that we already converged. (I had forgotten about this.)

However, following your off-by-1 argument, I think the initial np.inf is redundant, since we initialized with the starting estimate. If the starting values (e.g. user provided start_params) are already optimal, then we only need the iteration=0 round to verify that we are converged.

@josef-pkt

Copy link
Copy Markdown
Member

GLM is a core model and it has been this way for a long time, most likely since the beginning.
So we want to switch only once and not experiment. We should have a general policy for this.

@josef-pkt

Copy link
Copy Markdown
Member

RLM is similar and the convergence criterion is on the value of the objective function, but it has an option for choosing it conv='dev'.
(RLM was largely modeled the same way as GLM)

GLSAR uses max rtol for params

MixedLM uses max atol for fe params

Quantile regression uses max atol for params

those are the only ones with our model specific estimators

(GLSHet uses fixed number of iterations, open issue IIRC)

our newton method: docstring says relative, but code is absolute max atol for params

scipy optimizers are mixed according to our docstrings rtol or tol on gradient

@josef-pkt

Copy link
Copy Markdown
Member

I added prio-high label for some solution to the convergence criterion.
Absolute tolerance for deviance or objective function doesn't make sense if the objective is proportional to nobs.

@josef-pkt

Copy link
Copy Markdown
Member

I opened an issue #2825 for the record
According to julia GLM issues, R uses abs(dev - devold)/(abs(dev) + 0.1) < convTol
which looks like allclose with fixed ratio of atol / rtol

@thequackdaddy

Copy link
Copy Markdown
Member Author

Yes, that's the impetus for my original pull request. I was under the
impression the +0.1 was just to avoid a divide by zero error, but I could
see how it acts as a fixed atol as well.

On Thursday, February 18, 2016, Josef Perktold [email protected]
wrote:

I opened an issue #2825
#2825 for the record
According to julia GLM issues, R uses abs(dev - devold)/(abs(dev) + 0.1)
< convTol
which looks like allclose with fixed ratio of atol / rtol

—
Reply to this email directly or view it on GitHub
#2803 (comment)
.

@thequackdaddy

Copy link
Copy Markdown
Member Author

As another aside, when I was fitting GLM's with R, I would get convergence in 5-10 iterations. statsmodels was taking 25 or so for the same data.

@josef-pkt

Copy link
Copy Markdown
Member

About the number of iterations it takes:
I think an improvement can only come from better starting values. R uses QR and we use SVD by default but I don't think that should make a difference for convergence. The algorithm should be the same standard IRLS.
But it will depend a lot on the convergence criterion.

Do you know what the speed difference is between statsmodels and R?

@josef-pkt

Copy link
Copy Markdown
Member

I think this PR looks good now. I think we can go the direction of RLM and add another option to choose what is used for convergence, e.g. so users or we, if or when we want to change the default, can switch to convergence in params.

I think convergence in params, and score, are a lot more important than convergence in deviance, sum of squares or loglike.

@josef-pkt

Copy link
Copy Markdown
Member

I haven't looked at the test results yet, and didn't check what the default tolerances should be.

@thequackdaddy

Copy link
Copy Markdown
Member Author

Ok. I'm going to go radio silent on this PR then and leave it up to your discretion how you want to implement. I think the failing tests are due to...

  1. Before we had an off-by-one error. (Actually, I'm thinking it was really 2 off-by-one errors, so off-by-2) This caused IRLS iterations to continue beyond when they should have stopped because of the convergence criterion
  2. Log - Binomial is unstable in the gradient vs. IRLS test

If you wish for me to add stuff let me know.

I hadn't thought about using other metrics for the tolerance calculation. Off the top of my head, parameters, log-likelihood, and scores sound simple enough. But I'd want a list before I invest any time programming it.

@thequackdaddy

Copy link
Copy Markdown
Member Author

One other thought... log-likelihood seems especially compelling considering the basis for the calculus underlying this is MLE. I'd be interested if we could find a use case where an iteration causes likelihood to fall. If MLE falls, that might be enough to make us want to break the algorithm as the fit is probably garbage.

@josef-pkt

Copy link
Copy Markdown
Member

loglikelihood and deviance are essentially the same, up to constant factors.

The only two options right now would be deviance or params, loglikelihood (llf) could be added for consistency but will be essentially the same as deviance in the GLM case.

Our IRLS is plain vanilla and doesn't do backtracking nor checking for no improvement.
Julia again: They have one issue where deviance goes down, most likely because floating point precision or rounding problems, and then the backtracking fails.
I haven't heard of many problems with our IRLS, and since we have the scipy optimizers now as alternative, with some robust slow, or less robust fancy optimizers, I didn't consider improving our IRLS as high priority.

There are some substantial differences between IRLS and scipy optimizers for non-canonical links. In that case the Hessian and the Fisher information matrix are not the same and they don't solve exactly the same problem. (I haven't investigated that in details.)

@josef-pkt

Copy link
Copy Markdown
Member

I'm starting to look a bit at the test failures (edited while adding cases)

statsmodels.discrete.tests.test_constrained.TestGLMLogitConstrained2.test_basic_method
uses spector data which has only 32 observations.
difference in 5th decimal in bse, reference result are from Stata

statsmodels.discrete.tests.test_constrained.TestGLMPoissonConstrained1b.test_compare_glm_poisson
compares Poisson and GLM: uses GLM estimated parameters as start_params in Poisson.
I think this means that GLM doesn't converge well enough and Poisson with newton refines at rtol=12 which corresponds roughly to atol=13 in the failing test for bse

test_glm test_gradient_irls
not sure which test case fails, params differ at rtol=1e-6, which might be much higher than (visual inspection) difference is at 6th decimal in 0.004189 which would be only rtol around 1e-4
I also get a failing test when changing the start_params calculation for fit_gradient in
#2835 (comment)

statsmodels.stats.tests.test_mediation.test_framing_example
not clear from test result report, not close enough to zero at atol=1e-6

@thequackdaddy

Copy link
Copy Markdown
Member Author

I loosened some of the tests to show it now passes. Like I said, I'm fairly confident that before IRLS would continue to run well after the convergence criterion was met. That made some results too good.

The tests seem to be passing here. The fails are the other one's we've had sitting around.

@josef-pkt

Copy link
Copy Markdown
Member

The problem is that the old setting affects convergence very differently depending on the deviance, and indirectly the sample size. Even though we loosen for large sample sizes, we shouldn't loosen (too much) for small sample sizes.

I still don't have a good overview how this affects different cases. The increase in the tolerance in here might be too large. Furthermore, I think I'd like to move to using params as default convergence target.

There are two things in this PR:

  • adding atol and rtol as separate keywords, which could be added/merged in a backwards compatible way
  • changing the default tolerance. This impacts what numbers we get back, as in the unit tests, and I think requires more investigation into different criteria and how they affect various cases.

correction
there is also

  • fix the off-by-one or off-by-two bug

One extra check to verify how good the convergence is, is to look at the resulting score

@thequackdaddy

Copy link
Copy Markdown
Member Author

Ok. Well, I'll leave this into your hands. You have a better understanding on the fancy-shmancy math anyways.

Let me know if you want me to try something. I'm happy to experiment with using param convergence as the standard, but a little concerned that will break even more tests. If you don't mind me taking a whirl at it, let me know. In that event I'd probably revert the last change I made and then change the _check_convrgence function to allow it to check for other values in fit_history.

@josef-pkt

Copy link
Copy Markdown
Member

I think the easiest way forward is to add the option that lets user choose the convergence target, i.e. add params. And then experiment in a script or notebook with different cases.

This PR and issue have convinced me that we need to change the default criterion, which will always have the affect on some numbers. However, I would prefer that we have to do this only once, so I would like to understand better what we are switching to.
Given that GLM is an established core model, I would rather not experiment across releases, that's why I'm a bit more conservative in this.

@thequackdaddy thequackdaddy mentioned this pull request May 30, 2016
@josef-pkt josef-pkt added this to the 0.8 milestone May 30, 2016
@thequackdaddy
thequackdaddy force-pushed the iteration branch 2 times, most recently from f61d27d to 9949006 Compare May 31, 2016 16:46
@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.01%) to 85.506% when pulling 71a936b on thequackdaddy:iteration into a985b90 on statsmodels:master.

@thequackdaddy

thequackdaddy commented May 31, 2016 •

Copy link
Copy Markdown
Member Author

Ok, I lied. I was able to find some time to work on this today.

I'm probably a little better with python than I was previously, so I sort of started from scratch here.

3 real changes behavioral changes:

  • If you specify atol or rtol, those will override, for IRLS fits only, tol. If you specify rtol, relative tolerance is used.
  • If you specify tol_criterion = 'params', IRLS fits will run until params have converged.
  • I fixed the 2 "off by 1" errors that were causing additional iterations to run after the convergence criterion had been satisfied. Note that this breaks a few tests. The solution that I ended up going with was to specify a higher tol for the fit methods in those tests to run the additional iterations to match.

As I'm reviewing this, I realized a small typo in my documentation, so I'll fix that, but I think this is ready for review.

Some of these commits can be squashed, if necessary. Let me know.

Thanks.

fit_kwds={'tol': 1e-10})
cls.constraints = lc
cls.res1m = mod.fit_constrained(constr)._results
cls.res1m = mod.fit_constrained(constr, tol=1e-10)._results

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's better to be explicit and use atol instead of tol in these kinds of tests

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fair point. I changed this in the most recent revision.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.01%) to 85.506% when pulling 0d8ad18 on thequackdaddy:iteration into a985b90 on statsmodels:master.

@thequackdaddy thequackdaddy changed the title ENH: Relative tolerance ENH: Relative tolerance for GLM convergence May 31, 2016
@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.01%) to 85.506% when pulling e45db2e on thequackdaddy:iteration into a985b90 on statsmodels:master.

values for gradient optimization. Only relevant if
`method` is set to something other than 'IRLS'.

IRLS Parameters

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.

we cannot use nonstandard titles/headers in the docstrings because they are not recognized by the doc rendering

AFAICS either use Other Parameters or no headers for this section just continue with parameters
section 7 https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt
AFAIK we don't use Other Parameters anywhere so I'm not sure how it works.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Whoops. Didn't realize that was a "thing". I presume you could use any header. Thanks for that link. I tried to follow

@josef-pkt

Copy link
Copy Markdown
Member

that's all I can see right now. I will go over it in a bit more details on Friday and merge.

One thing I haven't looked at or thought about is whether we want to do something with the tol parameter in the signature given that atol and rtol are hiding in the kwds.

@thequackdaddy

Copy link
Copy Markdown
Member Author

Sounds good, as always Josef, thank you for your insights and helpfulness. I really appreciate it.


Notes
-----
This method does not take any extra undocumented ``kwargs``.

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.

can you delete this Notes section,
AFAICS, this is outdated because there are also optimization kwargs for fit_gradient

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I will. To avoid having a billion commits, I'll commit that in a few hours in case my OCD comes back.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.01%) to 85.506% when pulling 3ee51e5 on thequackdaddy:iteration into a985b90 on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member

Given that there were a few back and forth commits, I think this could be squashed. I don't see good breaks in the list of commits, so it could be squashed into a single commit.

Can you do that?

To clarify and summarize, the default has not changed at all. The only change in default behavior is coming from fixing the off-by-one error. Is that correct.

I think I've seen enough, ready for merge, preferably after squashing, and when travis is as green as it gets.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.01%) to 85.506% when pulling fa7ceea on thequackdaddy:iteration into a985b90 on statsmodels:master.

@thequackdaddy

Copy link
Copy Markdown
Member Author

Yes, I can squash. I'm not as useless at that as I used to be.

  • Default criterion of atol=1e-8 on devaince is unchanged. We are using np.allclose instead of a homebrewed equivalent.
  • A change in results is because this will do 1 less iteration than the previous version because of the correction of the off by one error.
  • You can use tol_criterion = 'params' to check convergence of params instead of deviance. As far as I know, every tool I've used has defaulted to deviance (R and 2 proprietary commercial products are the only other tools I've run GLMs on.)

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.01%) to 85.506% when pulling fa7ceea on thequackdaddy:iteration into a985b90 on statsmodels:master.

Had to adjust 2 tests to pass...

One more test...

**fit_kwds != fit_kwds

DOC typos and fixes

Using atol instead of tol.

Doc typo with default rtol = 0.

More doc clarifications... need to stop being so OCD.

IRLS Parameters not a numpydoc-approved header.

Remove Notes.
@thequackdaddy

thequackdaddy commented Jun 1, 2016 •

Copy link
Copy Markdown
Member Author

Squashed and all green. Feel free to merge at your leisure.

@josef-pkt

Copy link
Copy Markdown
Member

@thequackdaddy Thanks for another improvement to GLM
merging

@josef-pkt
josef-pkt merged commit e62551c into statsmodels:master Jun 1, 2016
@thequackdaddy
thequackdaddy deleted the iteration branch June 1, 2016 02:47
@josef-pkt

Copy link
Copy Markdown
Member

It would be useful for future reference and recommendation and possible changes in default settings if you could add some feedback comments, once you get experience with how well this works and have recommendation for good values for rtol in your kind of use cases.

Based on the discussion here I still think we need to change the defaults, but this PR is backwards compatible so much easier to merge.

@thequackdaddy

Copy link
Copy Markdown
Member Author

I don't disagree. Honestly, what I've been doing is just setting max_iter=10, which has worked well enough. When you have 100,000+ records, and the models I'm building are relatively clean and straightforward, I usually get convergence pretty quickly. But I like the idea of using rtol more, personally.

With that said, I can understand the advantages of atol. I personally won't use it, but I am not the only user here...

Thanks again.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.01%) to 85.506% when pulling 05afd28 on thequackdaddy:iteration into a985b90 on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member

The crucial qualifier is "relatively clean and straightforward".

Overall, I think the current (a)tol on deviance is a bad idea (even if many packages use it), if we want reliable parameter estimates, or an indication and convergence warnings if the parameters don't converge cleanly and straightforwardly.

@thequackdaddy

Copy link
Copy Markdown
Member Author

Fair point. I had never considered using params as the convergence criterion. As I think about that more, rtol on params is intriguing.

(Thinking out loud below)

The one issue that I have with this is that in practicality, I set one column in the dataset to a constant 1 (add_constant). The rest of the columns are indicators for presence or absence of a feature (male/female, discount, etc.) or a standardized interval value (policyholder age, standardized). When modeling something like severity per claim or average loss per year, the param associated with the constant column will be a large positive number (in the hundreds to ten-thousands) while the other params will be centered around 0 with params probably < 0.3 or so (generally speaking). So atol on params would not be ideal because it might take a long to converge the constant column because we're talking about 12-13 digits. rtol is a different story, but I worry about what would happen if you have an alias in the dataset (which happens). There, I've seen one of the aliased parameters numbers really close to zero (think 1e-100), so getting convergence on rtol would be problematic too.

With that said, at this point I statsmodels can fit a GLM with 3.5 million records and 25 columns on a virtual machine with a eight 1.9 GHZ processors in about a 1.5 minutes when I limit to 10 iterations. After this change, I think that time is down to around about one minute (its about 5-7 iterations for deviance to converge... not sure about params.) That's about as good as any commercial package I've dealt with. The bottleneck that I still struggle with in model-constructing is the converting my MSSQL database into numpy arrays/pandas dataframes. The real issue isn't so much the data transfer but creating all the dummy variables and standardized intervals quickly. I've played with a few approaches and all have been wholly unsatisfying, but I stumbled across a new idea a few days ago that I need to play with.

@josef-pkt

Copy link
Copy Markdown
Member

Did you try plain numpy for creating the dummy variables?
Do you know the unique values for the categorical variables in advance?
But that discussion is in a different issue.

for tolerance I think that in cases like yours, both atol and rtol would have to be set. For example in unit tests I usually fine tune both for assert_allclose. My guess is that a default of rtol=atol=1e-8 or 1e-6 would work in most cases for params. However, atol might be too large if we have a tiny param but a large effect because the scale of the exog is large. The proper tolerance might be in terms of standardized coefficients, i.e. etol * exog.std(), if exog varies a lot in scale. Bad scaling should be avoided in any case.
score could be checked with an atol because it is supposed to be zero at the optimum, and if it's not close to zero, then it also indicates some convergence problems.

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.

3 participants