Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion doc/source/changes/7.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ be added to 7.1. 7.2 also contains the fixes below.
the scaled data, about 16 - log10(c) digits are correct, against 16 - 2 log10(c) with
``method="pinv"``. With nearly collinear regressors (c of about 1e6), the median error
of the 2SLS estimates and their robust standard errors falls from about 5e-4 to 4e-11
in simulations. ``method="pinv"``, the default, gives the same results as 7.1. The IV
in simulations. ``method="pinv"``, the default, gives the same results as 7.1, except
for the kappa of LIML in the cases of issue 823 below. The IV
covariance estimators, ``estimate_parameters``, ``cragg_donald``, ``cragg_donald_f``,
``kleibergen_paap``, ``kleibergen_paap_f`` and ``FirstStageResults`` take the same
keyword. ``IVGMM``, ``IVGMMCUE`` and ``IVJIVE`` do not, since they are not k-class
Expand All @@ -43,6 +44,13 @@ be added to 7.1. 7.2 also contains the fixes below.
instruments, which the estimates use. 7.1 tested the unweighted ones, whose condition
number can differ greatly, so that a model whose weighted instruments are nearly
collinear was accepted (:issue:`873`).
- The kappa of LIML is computed from residuals scaled to have columns of unit length,
so that it does not depend on the units of the variables. 7.1 computed it from the
residuals as they were, so that with 2 or more endogenous regressors it changed by
up to about 2.6e-4 in relative terms when a variable was rescaled. An endogenous
regressor that is (numerically) a linear combination of the exogenous regressors
and instruments is now detected, and ``fit`` raises a ``ValueError`` if ``kappa``
is not provided; 7.1 returned the rounding error as kappa (:issue:`823`).

.. rubric:: Backward-incompatible changes

Expand Down
84 changes: 66 additions & 18 deletions linearmodels/iv/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
c_,
column_stack,
diag,
divide,
dtype,
eye,
finfo,
Expand All @@ -33,6 +34,7 @@
sqrt,
squeeze,
unique,
zeros_like,
)
from numpy.linalg import (
LinAlgError,
Expand Down Expand Up @@ -706,19 +708,22 @@ def _estimate_kappa(
This occurs if there are fewer than 1 + the number of endogenous
regressors observations more than the number of exogenous regressors and
instruments, and if the columns of the residuals are collinear, to
rounding error, or a column is 0, for another reason.
rounding error, or a column is 0, for another reason. It is also raised
if a column of the residuals is only rounding error relative to the
residuals on the exogenous regressors, so that the dependent variable
or an endogenous regressor is (numerically) a linear combination of
the exogenous regressors and instruments, see issue 823.

Notes
-----
Whether the residuals are linearly dependent does not depend on the units of
the variables: the count of observations does not, and the rank is tested on
residuals that are scaled to have columns of unit length. Kappa is computed
from the residuals as they are. Two cases are not covered, see issue 823. With
method="pinv", the accuracy of kappa depends on the units of the variables if
there are 2 or more endogenous regressors. With either method, a regressor
that is exactly a linear combination of the exogenous regressors and
instruments, which has residuals that are only rounding error, is not
detected.
residuals that are scaled to have columns of unit length. With
method="pinv", kappa is computed from residuals scaled to have columns of
unit length, so that it does not depend on the units of the variables
either, see issue 823. A regressor that is exactly a linear combination of
the exogenous regressors and instruments is detected before the
computation, and kappa is not estimated.
"""
y, x, z = self._wy, self._wx, self._wz
is_exog = self._regressor_is_exog
Expand Down Expand Up @@ -763,11 +768,38 @@ def _estimate_kappa(
if same:
ex1 = ez

# A column of the residuals on the exogenous regressors and instruments
# that is only rounding error, relative to the residuals on the
# exogenous regressors, is a dependent variable or an endogenous
# regressor that is (numerically) a linear combination of the
# exogenous regressors and instruments, see issue 823. Its kappa is
# rounding error, not the kappa of the data, so kappa is not
# estimated. The comparison is against the residuals on the exogenous
# regressors, so that a variable with a small coefficient of variation
# in a model without a constant is not flagged. A column whose
# residuals on the exogenous regressors are 0 is also 0 here, and is
# flagged, as it is by the rank test below
ez_norm = norm(ez, axis=0)
ex1_norm = norm(ex1, axis=0)
relative = divide(
ez_norm, ex1_norm, out=zeros_like(ez_norm), where=ex1_norm > 0
)
if npany(relative <= _KAPPA_TOLERANCE):
raise LinAlgError(
"The residuals of the dependent variable and the endogenous "
"regressors on the exogenous regressors and instruments are "
"rounding error relative to the residuals on the exogenous "
"regressors, so that an endogenous regressor (or the "
"dependent variable) is (numerically) a linear combination "
"of the exogenous regressors and instruments, and kappa "
"cannot be estimated."
)

# The rank is tested on a copy of the residuals with columns of unit length, so
# that it does not depend on the units of the variables. A column that is exactly
# 0 cannot be scaled, and is linearly dependent. Kappa is computed from the
# residuals as they are, see issue 823
scale = norm(ez, axis=0)
# 0 cannot be scaled, and is linearly dependent. The detection above guarantees
# that no column is 0 here
scale = ez_norm
full_rank = False
if npall(scale > 0):
full_rank = bool(matrix_rank(ez / scale, tol=_KAPPA_TOLERANCE) == ncol)
Expand All @@ -787,8 +819,14 @@ def _estimate_kappa(
scaled_ex1 = solve_triangular(r, ex1.T, trans="T").T
return float(svd(scaled_ex1, compute_uv=False)[-1] ** 2), z_dec

vpmzv_sqinv = inv_sqrth(ez.T @ ez)
q = vpmzv_sqinv @ (ex1.T @ ex1) @ vpmzv_sqinv
# Kappa is computed from residuals scaled to have columns of unit length, so
# that it does not depend on the units of the variables, see issue 823.
# Scaling the columns of the residuals is a congruence transformation of
# both cross products, so the generalized eigenvalues are unchanged
ez_scaled = ez / ez_norm
ex1_scaled = ex1 / ez_norm
vpmzv_sqinv = inv_sqrth(ez_scaled.T @ ez_scaled)
q = vpmzv_sqinv @ (ex1_scaled.T @ ex1_scaled) @ vpmzv_sqinv
return min(eigvalsh(q)), z_dec

def _post_estimation(
Expand Down Expand Up @@ -1250,11 +1288,14 @@ class IVLIML(_IVLSModelBase):
results are an ``InvalidTestStatistic``, since they use the estimate of
:math:`\kappa`.

Two cases are not covered, see :issue:`823`. An endogenous regressor that is
exactly a linear combination of the exogenous regressors and instruments has
residuals that are only rounding error, and so does :math:`\kappa`. With 2 or
more endogenous regressors, :math:`\kappa` loses accuracy, and the estimate can
fail, if the variables are on very different scales.
An endogenous regressor that is exactly a linear combination of the
exogenous regressors and instruments has residuals that are only rounding
error, relative to the residuals on the exogenous regressors, and so does
:math:`\kappa`: :math:`\kappa` is not defined then, and ``fit`` raises a
``ValueError`` if ``kappa`` is not provided. With 2 or more endogenous
regressors, :math:`\kappa` is computed from residuals scaled to have columns
of unit length, so that it does not depend on the units of the variables,
see :issue:`823`.

.. versionchanged:: 7.1

Expand All @@ -1264,6 +1305,13 @@ class IVLIML(_IVLSModelBase):
endogenous regressor and one instrument. It was NaN on some platforms, with
the estimates and their covariance, and a ``RuntimeWarning`` was emitted.

.. versionchanged:: 7.2

A ``ValueError`` is raised if an endogenous regressor is (numerically) a
linear combination of the exogenous regressors and instruments, and
:math:`\kappa` is computed from residuals scaled to have columns of unit
length, so that it does not depend on the units of the variables.

The ``method`` of ``fit`` is described in the Notes of :class:`IV2SLS`.

.. versionadded:: 7.2
Expand Down
7 changes: 6 additions & 1 deletion linearmodels/tests/iv/test_absorbing_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,12 @@ def test_cluster_message_names_only_what_the_models_have(data):
z = pd.DataFrame(
np.random.default_rng(2).standard_normal((NOBS, 2)), columns=["z0", "z1"]
)
endog = (z.sum(axis=1) + x["x0"]).to_frame("e")
# Not exactly a combination of the instruments and the exogenous regressors:
# an endogenous regressor that is spanned by them has no kappa (issue 823),
# and fit raises before it reaches the covariance estimator
endog = (
z.sum(axis=1) + x["x0"] + 0.01 * np.random.default_rng(3).standard_normal(NOBS)
).to_frame("e")
with pytest.warns(MissingValueWarning, match="missing values"):
models = {
"IV2SLS": IV2SLS(y, x, endog, z),
Expand Down
49 changes: 37 additions & 12 deletions linearmodels/tests/iv/test_liml_kappa_singular.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,13 @@
singular cannot depend on the units of the variables, and so a column of W that
is rescaled by 1e6 or 1e-6 does not change whether kappa is defined.

Where kappa is defined it is computed as it was. The accuracy of kappa depends on
the units of the variables if there are 2 or more endogenous regressors, and a
regressor that is exactly a linear combination of the exogenous regressors and
instruments is not detected (issue 823). The tests pin the values, which are
noise in the second case, to those of the previous computation.
Where kappa is defined it is computed from residuals scaled to have columns of
unit length, so that it does not depend on the units of the variables
(issue 823). On designs without rescaling the values are the same as those of
the previous computation, to rounding error. A regressor that is exactly a
linear combination of the exogenous regressors and instruments is detected, and
kappa is not estimated: its residuals are only rounding error, relative to the
residuals on the exogenous regressors.

The expected values are computed from the definition. The projections come from
QR decompositions and kappa from scipy.linalg.eigh(A, B), so that none of the
Expand Down Expand Up @@ -348,22 +350,45 @@ def span_data(seed):


@pytest.mark.parametrize("seed", range(8))
def test_kappa_of_a_regressor_in_the_span_of_the_instruments_is_computed_as_before(
def test_kappa_of_a_regressor_in_the_span_of_the_instruments_is_not_estimated(
seed,
):
# The residuals of the regressor are rounding error, and so is kappa (issue 823),
# which is near 1. Dividing the residuals by their norms magnified the rounding
# The residuals of the regressor are rounding error, and so is kappa (issue 823).
# Kappa is not estimated: IVLIML raises, IV2SLS and IVJIVE set the kappa of LIML
# to NaN and mark the overidentification tests invalid, and a kappa that is given
# still fits. Dividing the residuals by their norms would magnify the rounding
# error by 1e14, and kappa was -5.5e10 where it is 1.002657 (seed 0, Windows)
check_computed_as_before(IVLIML(*span_data(seed), kappa=1.0))
y, exog, endog, instr = span_data(seed)
mod = IVLIML(y, exog, endog, instr)
with pytest.raises(ValueError, match="Unable to estimate kappa"):
mod.fit()
with pytest.raises(LinAlgError, match="linear combination"):
mod._estimate_kappa()
res = IV2SLS(y, exog, endog, instr).fit()
assert np.isnan(res._liml_kappa)
assert isinstance(res.anderson_rubin, InvalidTestStatistic)
assert isinstance(res.basmann_f, InvalidTestStatistic)
res = IVJIVE(y, exog, endog, instr).fit()
assert np.isnan(res._liml_kappa)
assert isinstance(res.anderson_rubin, InvalidTestStatistic)
assert isinstance(res.basmann_f, InvalidTestStatistic)
res = IVLIML(y, exog, endog, instr, kappa=1.0).fit()
expected = k_class(y, exog, endog, instr, 1.0)
assert_allclose(res.params.to_numpy(), expected, rtol=1e-6, atol=1e-8)


@pytest.mark.parametrize(
"scales", SCALES_TWO_ENDOG, ids=[str(s) for s in SCALES_TWO_ENDOG]
)
def test_kappa_of_regressors_on_different_scales_is_computed_as_before(scales):
# The values are not the kappa of the data if the scales differ much (issue 823)
def test_kappa_of_regressors_on_different_scales_is_the_generalized_eigenvalue(
scales,
):
# The kappa of the data does not depend on the units of the variables (issue 823)
design = (1, 2, 4, 120)
check_computed_as_before(IVLIML(*args(*scaled(design, scales)), kappa=1.0))
expected = reference_kappa(*data_for(design, seed=3))
y, exog, endog, instr = scaled(design, scales)
res = IVLIML(*args(y, exog, endog, instr)).fit()
assert_allclose(res.kappa, expected, rtol=1e-10)


# ----------------------------------------------------------------------------
Expand Down
Loading