Skip to content

ENH: linalg helper: orthogonal complement of matrix #3039

Open

Description

@josef-pkt

(parking another helper function, so it doesn't get lost)

Written to understand orthogonal complement which is heavily used in VECM/cointegration.
Should also show up in canonical correlation, reduced rank regression and similar.
Also looks similar to reparameterization to include constraints (which I wrote without understanding the math).

general story: econometrics books often refer to things without telling how to compute it.
Eg.
constraints: w.l.o.g. we only consider this constraint, because the other forms can be obtained by reparameterization/transformation".

Related to here: normalization of cointegrating vectors to [eye, beta_2] requires a sequence of equations so that first variables with coefficients normalize to eye include elements of all cointegrating vectors. (But authors like Lutkepohl don't say how.)
My guess, not verified, is that below this will show up in the inv of the first part during normalization.
I need an example to check this.

# -*- coding: utf-8 -*-
"""
Created on Fri Jun 17 13:42:36 2016

Author: Josef Perktold
License: BSD-3


example from http://ltcconline.net/greenl/courses/203/Vectors/orthogonalComplements.htm

no reference for the use of SVD, but it should be "obvious"

"""

import numpy as np

def orthogonal_complement(x, normalize=True, threshold=1e-15):
    """Compute orthogonal complement of a matrix

    this works along axis zero, i.e. rank == column rank,
    or number of rows > column rank
    otherwise orthogonal complement is empty

    TODO possibly: use normalize='top' or 'bottom'

    """
    x = np.asarray(x)
    r, c = x.shape
    if r < c:
        import warnings
        warnings.warn('fewer rows than columns', UserWarning)

    # we assume svd is ordered by decreasing singular value, o.w. need sort
    s, v, d = np.linalg.svd(x)
    rank = (v > threshold).sum()

    oc = s[:, rank:]

    if normalize:
        k_oc = oc.shape[1]
        oc = oc.dot(np.linalg.inv(oc[:k_oc, :]))
    return oc


xxx = np.array([[1,0,1,0,2], [0,1,1,1,0], [1,1,1,1,1]]).T
ocn = np.round(orthogonal_complement(xxx, normalize=True), 2)
print(ocn)
print(orthogonal_complement(xxx, normalize=False))
print(ocn.T.dot(xxx))

"""
# some math courses seem to normalize at the bottom

>>> x2 = np.array([[1., 3, 0], [2, 1, 4]])
>>> np.round(orthogonal_complement(x2.T, normalize=True), 2)
array([[ 1.  ],
       [-0.33],
       [-0.42]])
>>> orthogonal_complement(x2.T, normalize=True)
array([[ 1.        ],
       [-0.33333333],
       [-0.41666667]])
>>> oc2 = orthogonal_complement(x2.T, normalize=True)
>>> oc2 / oc2[-1]
array([[-2.4],
       [ 0.8],
       [ 1. ]])
"""

Activity

  1. added this to the 0.10 milestone on Oct 27, 2018
  2. josef-pkt commented on Oct 27, 2018

    @josef-pkt
    MemberAuthor

    bump I think something like this would be useful for transforming spline basis functions in #5296

    If we have some spline basis, and we want to remove some subspace from it.

    • currently, I have the "centering" transformation to replicate patsy/mgcv to remove constant and center spline basis so that the mean partial prediction is zero.
    • in a spline basis that starts with a constant and a trend column, we can just remove the first one or two columns.
    • in the general case, we want to take out some subspace, e.g. constant and linear function if they are not columns already.

    in two steps we could do this with

    • get orthogonal complement, e.g. residuals of multivariate ols
    • get full rank subspace by including only singular/eigen vectors with positive singular values

    The orthogonal_complement above sounds like it's just getting the "null" space.
    Aside: I don't remember what normalize is supposed to be.

    We want something similar to CCA that includes the projection on a set of conditioning variables.
    We have a cca function and a full CCA class which might handle this case (but I haven't checked the math yet).

    #5296 adds a matrix_sqrt helper function that includes handling of singular matrices and null space, but is only for symmetric square matrices like covariance matrices.

  3. josef-pkt commented on Oct 27, 2018

    @josef-pkt
    MemberAuthor

    see also #4992 for organizing linalg tools

  4. josef-pkt commented on Nov 2, 2018

    @josef-pkt
    MemberAuthor

    another case, I don't know whether that is handled by the above
    use case #5364 variable addition score/LM test

    reduced rank partial projection
    I would like that partial projection returns the orthogonal space with minimal number of columns, i.e. so that the orthogonal array has full rank.

    bs.basis_.shape
    (203, 20)
    
    from statsmodels.stats.multivariate_tools import partial_project
    projection_resid = partial_project(bs.basis_, res_glm.model.exog)
    
    np.linalg.matrix_rank(projection_resid.resid), projection_resid.resid.shape[1]
    (18, 20)
    

    the pca function can do this, but we need to know the keepdim in advance

    from statsmodels.sandbox.tools.tools_pca import pca
    red = pca(projection_resid.resid, keepdim=18)[1]
    
  5. JaeDukSeo commented on Nov 20, 2018

    @JaeDukSeo

    @josef-pkt great code love it

  6. JaeDukSeo commented on Nov 20, 2018

    @JaeDukSeo

    @josef-pkt are you a professor?

  7. JaeDukSeo commented on Nov 20, 2018

    @JaeDukSeo

    if so sorry for my language, the code is great

  8. josef-pkt commented on Nov 20, 2018

    @josef-pkt
    MemberAuthor

    (I edited your comment a bit to keep the language here clean.)
    When I was an economist I got up to being an assistant professor.

    Thanks, it's good to here that I'm not the only one that likes this kind of code. The code itself is pretty simple, but it's difficult for someone who is not a linalg expert which I'm not.

  9. josef-pkt commented on Dec 9, 2018

    @josef-pkt
    MemberAuthor

    docstring missing, e.g. what is normalize doing?
    we can add a second x0=None for the usecase of having the orthogonal complement of x relative to x0. I'm not sure the terminology is correct, but that's what we need in my comment above for variable addition hypothesis tests.

  10. JaeDukSeo commented on Apr 10, 2019

    @JaeDukSeo

    great code! just came back to see

  11. josef-pkt commented on Aug 26, 2022

    @josef-pkt
    MemberAuthor

    checking my local files

    ex_gam_bs_autos_cleaned.ipynb includes a section on score_test using partial_project and pca
    https://gist.github.com/josef-pkt/453de603b019143e831fbdd4dfb6aa30

    aside: I didn't find a GAM notebook in the doc examples

  12. modified the milestones: 0.10, 0.15 on Jan 14, 2023
  13. josef-pkt commented on Nov 5, 2025

    @josef-pkt
    MemberAuthor

    one issue (currently not quite clear to me)

    What's the stateful transform to do prediction if we have the original, untransformed data?

    orthogonal complement versus partial_project (AFAIR, AFAIU)

    • orthogonal complement just looks for spanning the subspace, the actual components are not directly related to the original variables
      The transformation has a size in terms of k_vars.
    • partial project residuals use regression to predict residuals which are orthogonal to the conditioning variables.
      The transformation is in terms of the M matrix, i.e. eye minus projection matrix. The size is in terms of nobs, (nobs x nobs)

    The former is fine if we want to use inference (hypothesis tests, variable selection) on the subspace, but it does not provide information about contribution of original variables.
    The latter can be used to check contribution of the original variables, orthogonalized to the base variables.

    Partial project depends on the individual observations. This is fine for the estimation sample, but makes the stateful transformation for prediction more difficult.
    I guess we need to keep the param estimates and compute residuals from the out of sample observations.

    context:
    I ran into a nested anova example. Even though the structure is balanced (each main categorical has the same number of leaf categoricals and the same number observations in each cell), the design matrix is not orthogonal between main effect of main categorical and nesting interaction effect.
    related to #9480

  14. josef-pkt commented on Nov 5, 2025

    @josef-pkt
    MemberAuthor

    Similar idea which, AFAIR, I never tried.

    Cholesky decomposition starting after some base variables.
    The transform should leave the base variables unchanged and sequentially orthogonalize the extra variables.

    My guess is that one way of doing this is to run a full Cholesky/QR and replace the first submatrix of the transformation matrix by the identity matrix.

    Disadvantage is that we treat extra variables in an asymmetric way. That would be ok if it is sequential, e.g. degrees of polynomials, or, again, if we are only interested in the joint effect of a subgroup of extra variables (e.g. either keep all those or drop them all together, or only joint hypothesis tests).

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions