Skip to content

MAINT: Scipy minimize wrapper Nelder-Mead and Powell bounds - #8317

Closed
wnfldchen wants to merge 4 commits into
statsmodels:mainfrom
wnfldchen:fit_minimize_bounds
Closed

wnfldchen wants to merge 4 commits into
statsmodels:mainfrom
wnfldchen:fit_minimize_bounds

Conversation

@wnfldchen

Copy link
Copy Markdown
Contributor

Update scipy.optimize.minimize wrapper bounds list
@josef-pkt

Copy link
Copy Markdown
Member

Do you have an example for this using statsmodesl fit?

AFAIK we don't support bounds constraints in the models.

@wnfldchen

Copy link
Copy Markdown
Contributor Author

Do you have an example for this using statsmodesl fit?

AFAIK we don't support bounds constraints in the models.

@josef-pkt I am currently following the tutorial at https://www.statsmodels.org/v0.13.2/examples/notebooks/generated/generic_mle.html and want to do .fit(x, method='minimize', min_method='Nelder-Mead', bounds=bounds). The bounds option itself is described in https://www.statsmodels.org/v0.13.2/dev/generated/statsmodels.base.model.GenericLikelihoodModel.fit.html and there is a test test_minimize_scipy_slsqp() including it in statsmodels/base/tests/test_optimize.py#L133. The test and the has_bounds list which I updated were added in #6657. The corresponding issue to that addition, #6655, has an example which I have modified below by adding a second fit and changing the min_method to Nelder-Mead. When you run the example you can see when you compare the two summaries that Nelder-Mead is currently not behaving as expected (if it were behaving as expected the output should be similar to the original fit - for Nelder-Mead the bounds are being removed before being passed on to scipy.optimize.minimize unlike with SLSQP), after this change it will behave as expected.

import statsmodels.api as sm
data2 = sm.datasets.scotland.load()
data2.exog = sm.add_constant(data2.exog, prepend=False)
bnds = tuple([(0, None)]*data2.exog.shape[1])
glm_gamma = sm.GLM(data2.endog, data2.exog, family=sm.families.Gamma())
glm_results_slsqp = glm_gamma.fit(method='minimize', min_method='SLSQP', bounds=bnds)
print(glm_results_slsqp.summary())
glm_results_nm = glm_gamma.fit(method='minimize', min_method='Nelder-Mead', bounds=bnds)
print(glm_results_nm.summary())

If a test for this is wanted I would copy the existing test_minimize_scipy_slsqp() into a new test_minimize_scipy_nelder_mead() and just change SLSQP to Nelder-Mead, perhaps with another test comparing the two outputs.

@josef-pkt

Copy link
Copy Markdown
Member

very good, thanks for figuring this out, I had completely forgotten about this (or not paid enough attention in the first place)

related issue #4591

Yes, add the unit test, PRs need unit tests to check that it works

Note, Constraints through minimizer are not officially supported in the models because inference with possibly binding constraints is not standard, and we don't have a way to handle inference for inequality constraints yet. e.g. #1382

@josef-pkt

josef-pkt commented Jun 20, 2022 •

Copy link
Copy Markdown
Member

trying out the example without constraining the constant

results looks strange
pearson_chi2, llf and deviance are much worse in the partially constrained fit than in the constant-only model.
Puzzling was that pseudo R2 is negative (ie. worse than constant-only null model)
Pseudo R-squ. (CS): -0.2653

import numpy as np
import statsmodels.api as sm
data2 = sm.datasets.scotland.load()
data2.exog = sm.add_constant(data2.exog, prepend=False)
bnds = [(0, None)]*data2.exog.shape[1]
bnds[-1] = (None, None)
bnds = tuple(bnds)
glm_gamma = sm.GLM(data2.endog, data2.exog, family=sm.families.Gamma())
glm_results_slsqp = glm_gamma.fit(method='minimize', min_method='SLSQP', bounds=bnds)
print(glm_results_slsqp.summary())

slsqp optimization with bounds looks fragile

Aside: GLM summary does not show converged boolean

update

'L-BFGS-B' with bounds looks much better, Pseudo R-squ. (CS): 0.7854

bnds = [(0, None)]*data2.exog.shape[1]
bnds[-1] = (None, None)
bnds = tuple(bnds)
glm_gamma = sm.GLM(data2.endog, data2.exog, family=sm.families.Gamma())
glm_results_slsqp = glm_gamma.fit(method='minimize', 
                                  min_method='L-BFGS-B',
                                  #min_method='SLSQP', 
                                  bounds=bnds)
print(glm_results_slsqp.summary())

@josef-pkt

Copy link
Copy Markdown
Member

I'm currently using a scipy version that is too old for bounds in nm.

scipy.version
'1.6.1'

@josef-pkt

Copy link
Copy Markdown
Member

We can merge this as a simple extension.
(I will look at applications of bound constrained estimation maybe later this year. I will need updated scipy to see how fragile bound constrained optimization is in our models. possible application positive lower bound on negative binomial dispersion coefficient. NB fails if dispersion goes to zero or there is underdispersion)

We need to check if an older version of scipy provides a good error message if bounds is not available.
Unit tests will need to take into account that it's not available for older supported scipy.

@josef-pkt josef-pkt mentioned this pull request Jun 22, 2022
16 of 20 tasks
@wnfldchen

Copy link
Copy Markdown
Contributor Author

@josef-pkt What do you think of the approach taken in the latest commit, which makes the bounds support check scipy version-aware and adds two version-aware tests? With this approach, I think we might be able to skip the "need to check if an older version of scipy provides a good error message if bounds is not available" as we will never be in a situation where we pass an unsupported option to an older version of scipy.

Comment thread statsmodels/base/optimizer.py Resolved
@josef-pkt

Copy link
Copy Markdown
Member

version check in code looks good.

I don't understand how the unit tests work.
Why do we get different results by scipy version? I would have thought we get an exception if an unsupported bound is specified.

@wnfldchen

Copy link
Copy Markdown
Contributor Author

I don't understand how the unit tests work. Why do we get different results by scipy version? I would have thought we get an exception if an unsupported bound is specified.

@josef-pkt Oh, I wanted to respect the existing behaviour of the code. Right now if you pass bounds to any method that does not support bounds, there is no exception thrown or warning issued, the bounds is silently ignored. Should that existing behaviour be changed? If it should be, should it be changed for all methods or just for NM and Powell?

@josef-pkt

Copy link
Copy Markdown
Member

We changed 1 or 2 versions ago that fit keywords that are not used raise an exception instead of silently being ignored.
It looks like bounds wasn't included in that.

It should raise instead of silently returning different numbers to the user.

However, I don't know where the raise for invalid optimizer keyword is. It might be triggered only when calling model.fit and not in the scipy wrapper function.
Or it could be that method="minimize" does not have the valid kwarg check.

@josef-pkt

josef-pkt commented Jul 6, 2022 •

Copy link
Copy Markdown
Member

I just checked an example, model.fit(method="minimize", min_method="Nelder-Mead", keyword=3) does not raise.
So the kwarg check is missing for minimize and only implemented for our explicit wrappers for specific minimizers.

So for this PR the options are

  • only change bounds, and drop the unit test part for the incorrect old scipy version
  • implement kwarg check for "minimize"

If this PR only includes the change in bounds, then we should implement the kwarg check in a separate PR before the next release. We might be able to delegate the kwarg check to scipy's minimize.

@bashtage

Copy link
Copy Markdown
Member

I"m happy to do the kwarg check if this one is otherwise ok.

@bashtage bashtage self-assigned this Jul 11, 2022
@wnfldchen

Copy link
Copy Markdown
Contributor Author

Ok, thanks, I've dropped the unit test case for the old scipy version. So this PR now only contains the change in bounds plus tests that for now are run only if the scipy version is new enough (the tests are skipped if it is a too old scipy version for bounds support). Thanks @bashtage for offering to do the kwarg check changes in a new PR.

@josef-pkt

Copy link
Copy Markdown
Member

thanks @bashtage

This PR looks good to me. Commits could be squashed before merge

I tried out a few more examples with bounds, but using lbfgsb.
If constraints are binding, then wald inference for the constraint parameter doesn't make much sense or is difficult to interpret. However, score_test based on the fit with bounds looks ok, assuming binding equality constraints instead of non-standard inference for inequality constraints.

@josef-pkt

Copy link
Copy Markdown
Member

@wnfldchen
can you squash the commits and check the merge conflict.

(otherwise, I will do it before merge for 0.14)

@josef-pkt josef-pkt added this to the 0.14 milestone Nov 26, 2022
@josef-pkt

Copy link
Copy Markdown
Member

reminder to myself:
another case to check is dispersion coefficient in NegBin.
Can we use scipy constraints/bounds to set a strictly positive minimum level for NB extra param?

@josef-pkt josef-pkt added the superseded Used for PRs with content that is superseded by a newer PR label Nov 30, 2022
@josef-pkt

Copy link
Copy Markdown
Member

rebased and squashed in #8545, will merge soon

@wnfldchen Thanks for the PR and enhancement

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-base superseded Used for PRs with content that is superseded by a newer PR type-enh

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants