Skip to content

ENH: Vectorized OLS, simplified Multivariate Linear Regression using OLS #4771

Open

Description

@thomasaarholt

I'm attempting to do multivariate linear regression using statsmodels. For that, I am using the Ordinary Least Squares model. Just to be precise, this is not multiple linear regression, but multivariate - for the case AX=b, b has multiple dimensions. I am using a set number of components (A, shape (1024, 4)) to fit a number of spectra (b, shape(1024, 50).

Now, the docstring of OLS() describes the first input variable (in this case my y) as:

endog : array-like
    1-d endogenous response variable. The dependent variable.

which emphasises that this should not be used for my 2D b.

At this point, I should first ask:
Is there a better model for me to use?

However, the following case gives the correct multivariate fitting using the above model:

>>> import statsmodels.api as sm
>>> import numpy as np

>>> length = 1024
>>> pixels = 50
>>> number_of_components = 4
>>> ymulti = np.random.random((length, pixels))
>>> ysingle = np.random.random((length, ))
>>> A = np.random.random((length, number_of_components))

>>> model = sm.OLS(ymulti, A)
>>> result = model.fit()
>>> result.params.shape
(4, 50)

The problem is that all the other functionality of the model, including .summary() and result.HC3_se is showing the errors, and fails due to shape mismatch. I'm just showing two examples here, but there are many others, all with similar errors.

They all appear to be related to simple fixes, i.e. taking the transpose of the second entry of the numpy dot product.

The summary() might be a bit more tricky, since the components now describe a much higher number of pixels, so I'm not sure how that would be handled.

>>> result.summary()
~/miniconda3/envs/py36/lib/python3.6/site-packages/statsmodels/regression/linear_model.py in ssr(self)
   1513     def ssr(self):
   1514         wresid = self.wresid
-> 1515         return np.dot(wresid, wresid)
   1516 
   1517     @cache_readonly

ValueError: shapes (1024,50) and (1024,50) not aligned: 50 (dim 1) != 1024 (dim 0)
>>> result.HC3_se
...error traceback removed for clarity...
~/miniconda3/envs/py36/lib/python3.6/site-packages/statsmodels/regression/linear_model.py in cov_HC3(self)
   1680         h = np.diag(chain_dot(
   1681             self.model.wexog, self.normalized_cov_params, self.model.wexog.T))
-> 1682         self.het_scale = (self.wresid / (1 - h))**2
   1683         cov_HC3 = self._HCCM(self.het_scale)
   1684         return cov_HC3

ValueError: operands could not be broadcast together with shapes (1024,50) (1024,) 

Activity

  1. josef-pkt commented on Jul 3, 2018

    @josef-pkt
    Member

    It's not a bug, it's by design that OLS only works for univariate response endog.
    params works because the linalg is automatically vectorized.

    The class to handle the multivariate case is
    https://github.com/statsmodels/statsmodels/blob/master/statsmodels/multivariate/multivariate_ols.py#L367
    However, it is an incomplete model that currently only supports the MANOVA test.

    What's your assumption on the residual covariance, i.e. correlation across endog for the same observation? Specifically, do you just need vectorized single endog OLS or do you need inference that takes cross-endog correlation into account?

    (I'm travelling and on vacation with only limited internet time at the moment.)

  2. thomasaarholt commented on Jul 5, 2018

    @thomasaarholt
    Author

    @josef-pkt I only need a vectorized form of single endog OLS. A for loop of "normal" OLS satisfies my problem, except for speed.

    @bashtage I'll check this out.

    Having learnt where to look (thanks @josef-pkt), I've noted #4179. That issue covers the problem, so I'm closing this.

  3. josef-pkt commented on Jul 5, 2018

    @josef-pkt
    Member

    the specific issues for this case are #2203 #718

    The main point is how to design this for the tradeoff between generality and computational efficiency for special cases (and that somebody has to write the code).

    General SUR would allow for different exog for each endog and allows full parameter tests and restrictions within and across equations/endog.
    MultivariateOLS assumes identical exog for each endog but allows for cross-endog parameter hypothesis tests. (similar to VAR, MNLogit)
    VectorizedOLS would be just single equation OLS vectorized to reuse common parts and avoid some loops or expanded arrays, i.e. we never need a full cov_params, i.e. square (k_endog * k_exog)

  4. thomasaarholt commented on Jul 6, 2018

    @thomasaarholt
    Author

    Thanks for the response @josef-pkt.

    I take it that there currently is not an implementation of VectorizedOLS?

  5. josef-pkt commented on Jul 12, 2018

    @josef-pkt
    Member

    No, there is not, not yet.

    What results do you need?
    I think the values for the params_table, bse and others, can be computed without loop and full cov_params.
    summary could be implemented similar to MNLogit.

    I guess other results like vectorized t_test would need more work. (results.t_test is vectorized for multiple contrasts but not for multiple cov_params).

    For ssr we might want to have a 1-d vectorized ssr and not the cross-equation or cross-endog covariance, i.e. (resid * resid).sum(0) instead of resid.T.dot(resid). The latter would be for MultivariateOLS. The same for scale, mse_resid and similar.

  6. josef-pkt commented on Jul 12, 2018

    @josef-pkt
    Member

    vectorized t_test should also be simple to implement but needs to be specifically written for this.

    something like this (not correct, I think there is a dot too many in the denominator)
    bse_contrast = contrast.dot(params) / sqrt(contrast.dot(normalized_cov_params.dot(contrast.T) * results.scale)

    (the point is that parts like (contrast.dot(normalized_cov_params.dot(contrast.T) are the same for each equation)

  7. changed the title [-]Possible bug in Multivariate Linear Regression using OLS[/-] [+]ENH: Vectorized OLS, simplified Multivariate Linear Regression using OLS[/+] on Jul 12, 2018
  8. josef-pkt commented on Nov 7, 2018

    @josef-pkt
    Member

    bump for a prototype (thoughts during lunch break)

    subclass OLS but return a VectorizedOLSResults instance
    initial methods and attributes

    • params (2-dim)
    • resid, fittedvalues (2-dim)
    • predict (2-dim
    • fixed inference attributes: bse, tvalues pvalues, confint (2-dim, confint is 3dim or separate low, upp)
    • t_test for a single linear restriction within endog and identical hypothesis across endog, can most likely return a contract results instance.
      i.e. t_test is vectorized across endog but not across hypothesis for a single param.
    • wald test: ? not at first but should be possible, vectorized by scale vector
    • summary ?

    fit statistic:

    • rsquared
    • llf
    • f_value, f_pvalue ?
  9. josef-pkt commented on Nov 14, 2018

    @josef-pkt
    Member

    a initial version is now in #5382

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

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions