Skip to content

ENH: add GMMIVCF/GLMIVCF control function for endogenous explanatory variable - #8812

Open
josef-pkt wants to merge 4 commits into
statsmodels:mainfrom
josef-pkt:control_function
Open

josef-pkt wants to merge 4 commits into
statsmodels:mainfrom
josef-pkt:control_function

Conversation

@josef-pkt

Copy link
Copy Markdown
Member

getting started with #7689
endogenous regressors in nonlinear models

currently GLM, and only one endogenous regressor

this add statsmodels.causal directory

@josef-pkt

josef-pkt commented Apr 20, 2023 •

Copy link
Copy Markdown
Member Author

only 36 lines of code to implement control function for all GLM families, the advantage of reusable parts 👍

If we allow for only one endogenous regressor, then we can easily add a family option for the 1st stage.
I don't know yet if I will find another package to write a unit test against.
If we add inverse Mills ratio (hazard rate) to GLM-probit, then we can verify against methods for standard bivariate normal latent variables.
(*) see below

Adding controlf_kwds to __init__ for options, like which "resid"???

multiple endogenous regressors:
besides MultivariateLS, we only have the option of adding several univariate estimators (vertical stacking will not add a correlation like in GLS). MultivariateLS params will also be the same as separate OLS, as long as we use the same instruments.
In this case, first stage parameter estimation will not take cross-correlation into account.
However, the GMM cov_params will still take into account the correlation in cov(moments) across all first stage estimates.

update
(*)

In the test case we only have a binary 1st stage regressor (i.e. 2 sample case).
In this case, predicted probabilities are independent of link and also the same as linear probability model (OLS).

So using Logit as a first stage instead of OLS does not change the results of the second stage (last 3 parameters in test case).

res2.params - res.params
array([-1.41142239e+00,  1.52702446e+00,  1.08890674e-12, -1.94577687e-12,
        1.94377847e-12])

res2.bse - res.bse
array([ 1.87557947e-01,  2.56702075e-01,  1.78288273e-10, -2.90577562e-11,
        7.99499356e-11])

same if I use Probit as a first stage, GLM-binomial with probit link
I'm a bit surprised that bse is also unchanged. I thought that maybe the cov(moments) would change and through that the cov_params, especially for non-canonical link.

res2.params - res.params
array([-9.55567914e-01,  7.64154961e-01,  4.32986980e-14, -7.37188088e-14,
        7.37188088e-14])

res2.bse - res.bse
array([ 9.26798281e-02,  1.27372806e-01,  2.76773049e-11, -3.19284266e-10,
       -2.87747937e-10])

)
res = mod.fit()
sli = slice(-3, None, None)
assert_allclose(res.params[sli], params2[sli], rtol=1e-7)

Check failure

Code scanning / CodeQL

Unhashable object hashed

This [instance](1) of [slice](2) is unhashable.
res = mod.fit()
sli = slice(-3, None, None)
assert_allclose(res.params[sli], params2[sli], rtol=1e-7)
assert_allclose(res.bse[sli], bse2[sli], rtol=1e-6)

Check failure

Code scanning / CodeQL

Unhashable object hashed

This [instance](1) of [slice](2) is unhashable.
sli = slice(-3, None, None)
assert_allclose(res.params[sli], params2[sli], rtol=1e-7)
assert_allclose(res.bse[sli], bse2[sli], rtol=1e-6)
assert_allclose(res.tvalues[sli], tvalues2[sli], rtol=1e-5)

Check failure

Code scanning / CodeQL

Unhashable object hashed

This [instance](1) of [slice](2) is unhashable.
@josef-pkt

Copy link
Copy Markdown
Member Author

CodeQL complains about slice(...) is unhashable. I silenced them as false positives. slice is used to index arrays

@josef-pkt

josef-pkt commented Apr 21, 2023 •

Copy link
Copy Markdown
Member Author

returning the second stage outcome model results, attached to res_gmm

inside fit

        res_out = res_outcome._results  # res_outcome is wrapped results
        res_out._cache = {}
        k_out = len(res_outcome.params)
        cov2 = res_gmm.cov_params()[-k_out:, -k_out:]
        res_out.cov_params_default = cov2
        res_out.normalized_cov_params = None

This has the standard GLM model attached, predict is the standard GLM predict.
This treats the control function as just another exog variable.

We can compute conditional expectation for given unobserved random term (control function values), e.g. set them to zero for prediction ignoring the random effect.
For marginal expectation E(y | x) we would still need to integrate out the random effect. (ASF, average structural function in Wooldridge base on Blundell and Powell).
We need to either add something to predict of the 2nd stage model, or add additional methods to the second stage results instance.

One possibility to make this cleaner:

Add results_class attribute to GLM, and return a subclass of GLMResults that appropriately adjusts normalized cov_params, cov_params_default and adds control function specific methods (maybe with results mixin).

@josef-pkt

Copy link
Copy Markdown
Member Author

aside to the test case
The control function takes on only 4 values, because both eev and instrument are binary.
This will not be the case if any of those are continuous variables.

uni, uni_idx, uni_counts = np.unique(res_out.model.exog[:, -1], return_inverse=True, return_counts=True)
uni, uni_counts
(array([-0.69148936, -0.23584906,  0.30851064,  0.76415094]),
 array([29, 81, 65, 25], dtype=int64))

res_out = res.results_outcome
assert_allclose(res_out.params, params2[sli], rtol=1e-7)
assert_allclose(res_out.bse, bse2[sli], rtol=1e-6)
assert_allclose(res_out.tvalues, tvalues2[sli], rtol=1e-5)

Check failure

Code scanning / CodeQL

Unhashable object hashed

This [instance](1) of [slice](2) is unhashable.
assert_allclose(res_out.params, params2[sli], rtol=1e-7)
assert_allclose(res_out.bse, bse2[sli], rtol=1e-6)
assert_allclose(res_out.tvalues, tvalues2[sli], rtol=1e-5)
assert_allclose(res_out.pvalues, pvalues2[sli], rtol=1e-5)

Check failure

Code scanning / CodeQL

Unhashable object hashed

This [instance](1) of [slice](2) is unhashable.
assert_allclose(res.params[sli], params2[sli], rtol=1e-7)
assert_allclose(res.bse[sli], bse2[sli], rtol=1e-6)
assert_allclose(res.tvalues[sli], tvalues2[sli], rtol=1e-5)
assert_allclose(res.pvalues[sli], pvalues2[sli], rtol=1e-5)

Check failure

Code scanning / CodeQL

Unhashable object hashed

This [instance](1) of [slice](2) is unhashable.

# check attached outcome model
res_out = res.results_outcome
assert_allclose(res_out.params, params2[sli], rtol=1e-7)

Check failure

Code scanning / CodeQL

Unhashable object hashed

This [instance](1) of [slice](2) is unhashable.
# check attached outcome model
res_out = res.results_outcome
assert_allclose(res_out.params, params2[sli], rtol=1e-7)
assert_allclose(res_out.bse, bse2[sli], rtol=1e-6)

Check failure

Code scanning / CodeQL

Unhashable object hashed

This [instance](1) of [slice](2) is unhashable.
@josef-pkt

josef-pkt commented Jun 17, 2024 •

Copy link
Copy Markdown
Member Author

I guess this is useful enough to include in 0.15 even if there is only one endogenous explanatory allowed.

Need to check again what options for the functional form of the control function are available. Can we replicate the usual Wooldridge cases?
e.g. include in docs/notebook the form of residual included if endogenous explanatory variable is bernoulli/binomial.

missing docstrings, especially for class Parameters.

needs notebook for doc examples

@josef-pkt josef-pkt mentioned this pull request Jun 17, 2024
6 tasks
@josef-pkt
josef-pkt requested a review from Copilot July 22, 2025 07:43

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull Request Overview

This PR introduces a new statsmodels.causal module that implements a control function approach for handling endogenous explanatory variables in GLM models. The implementation adds support for instrumental variable estimation using a two-stage control function method, currently supporting GLM models with one endogenous regressor.

  • Adds GMMIVCF and GLMIVCF classes for GMM and GLM instrumental variable control function estimation
  • Implements two-stage estimation with flexible control function specifications
  • Provides comprehensive test coverage with reference data validation

Reviewed Changes

Copilot reviewed 4 out of 6 changed files in this pull request and generated 3 comments.

File Description
statsmodels/causal/init.py Creates the new causal module with test framework integration
statsmodels/causal/ivcontrol_function.py Core implementation of control function classes and estimation methods
statsmodels/causal/tests/test_ivcontrol.py Test suite validating model functionality against reference results
statsmodels/causal/tests/results/temp_residinclude.csv Test data containing instrument, endogenous, and outcome variables
Comments suppressed due to low confidence (1)

statsmodels/causal/ivcontrol_function.py:126

  • [nitpick] Parameter names use generic 's{i}' format which is not descriptive. Consider using more meaningful names that distinguish between first-stage and outcome parameters.
                          param_names=[f"s{i}" for i in range(len(params))])

mod = GLMIVCF(endog, explan, endog_explan, instruments,
family=families.Binomial(),
family_first=families.Binomial(link=families.links.Probit()),
cf_kwds = {"resid": "resid_response"},

Copilot AI Jul 22, 2025

Copy link

Choose a reason for hiding this comment

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

[nitpick] Missing space after equals sign in dictionary. Should be cf_kwds = {"resid": "resid_response"} for consistency with Python formatting standards.

Copilot uses AI. Check for mistakes.
Comment on lines +16 to +23
def momcond(params, modelcf=None):
mod_first = modelcf.model_first

y2 = modelcf.endog
x2 = modelcf.explan

params1 = params[:2]
params2 = params[2:]

Copilot AI Jul 22, 2025

Copy link

Choose a reason for hiding this comment

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

Magic number '2' is used for slicing parameters without explanation. Consider using a named constant or documenting why the first 2 parameters belong to the first stage model.

Suggested change
def momcond(params, modelcf=None):
mod_first = modelcf.model_first
y2 = modelcf.endog
x2 = modelcf.explan
params1 = params[:2]
params2 = params[2:]
# Number of parameters belonging to the first-stage model
NUM_FIRST_STAGE_PARAMS = 2
def momcond(params, modelcf=None):
mod_first = modelcf.model_first
y2 = modelcf.endog
x2 = modelcf.explan
params1 = params[:NUM_FIRST_STAGE_PARAMS]
params2 = params[NUM_FIRST_STAGE_PARAMS:]

Copilot uses AI. Check for mistakes.
param_names=[f"s{i}" for i in range(len(params))])
mod_gmm.model = self
res_gmm = mod_gmm.fit(start_params=params, maxiter=0)
res_out = res_outcome._results # res_outcome is wrapped results

Copilot AI Jul 22, 2025

Copy link

Choose a reason for hiding this comment

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

Accessing private attribute _results suggests tight coupling. Consider using a public interface or documenting why direct access to private attributes is necessary.

Copilot uses AI. Check for mistakes.
@josef-pkt

josef-pkt commented Jul 24, 2025 •

Copy link
Copy Markdown
Member Author

semi-random idea to have flexibility in control function for which residuals and which transformation of them should be used:

provide option to use callback function the the user can provide, function takes first stage results instance as argument and should return 1-dim or 2-dim control functions.
First stage results has different resid that can be transformed by user, e.g. polynomial.

This way we could hard code just a simple default, e.g. polynomial of resid_pearson, and user can use callback if other control functions are desired.

If we allow for multiple endogenous regressors, then callback would have to be a list (or maybe better a tuple) of functions including possibly None for keeping default for an endogenous regressors.
Distinction between one and multiple endogenous regressors could be isinstance check for tuple (to ignore any non-tuple array-like). Or alternatively, we use a dict for multiple endogenous regressor with variable names as keys.

@josef-pkt josef-pkt changed the title ENH: add GMMIVCF control function for endogenous explanatory variable ENH: add GMMIVCF/GLMIVCF control function for endogenous explanatory variable Jul 24, 2025
@josef-pkt

Copy link
Copy Markdown
Member Author

notebook with example of GLMIVCF is in my local notebook try_controlfunction_glm.ipynb

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