Skip to content

Maximum likelihood factor analysis - #4156

Merged
josef-pkt merged 10 commits into
statsmodels:masterfrom
kshedden:factanal
Dec 20, 2017
Merged

josef-pkt merged 10 commits into
statsmodels:masterfrom
kshedden:factanal

Conversation

@kshedden

@kshedden kshedden commented Dec 8, 2017

Copy link
Copy Markdown
Contributor

This is an implementation of maximum likelihood factor analysis. It probably would need to be integrated with #3294.

The main reference for me was Bai and Li:

https://arxiv.org/pdf/1205.6617.pdf

They focus more on estimation in high dimensions, less on issues relating to model assessment which are very important in psychometrics. Specialized methods for the latter are not included here.

This uses direct numerical optimization of the log-likelihood. The gradient is not provided but scipy minimize seems to do OK without it here. EM is also common and we could provide that as an optional algorithm.

@coveralls

coveralls commented Dec 8, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.02%) to 81.891% when pulling 1d962d2 on kshedden:factanal into 98f5db9 on statsmodels:master.

@coveralls

coveralls commented Dec 8, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.02%) to 81.889% when pulling 61ad3f2 on kshedden:factanal into 98f5db9 on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member

@kshedden Can you review #3294 a bit? I think it should be ready to merge except for the location of the rotation option.

@kshedden @yl565 The main question right now is whether these two can be merged into master fast so it will be in 0.9, or if we postpone it to 0.10 to have more time to integrate this.

I only briefly looked at the PR. It seems to me that factanal here could be made into a private method and added as option to the fit method in the class in #3294. That leaves the rotation and results methods from here which would need to be added to the results class in #3294.

@codecov-io

codecov-io commented Dec 8, 2017 •

Copy link
Copy Markdown

Codecov Report

Merging #4156 into master will increase coverage by 0.01%.
The diff coverage is 82.96%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #4156      +/-   ##
==========================================
+ Coverage   79.38%   79.39%   +0.01%     
==========================================
  Files         554      555       +1     
  Lines       82603    82830     +227     
  Branches     9428     9452      +24     
==========================================
+ Hits        65572    65764     +192     
- Misses      14883    14905      +22     
- Partials     2148     2161      +13
Impacted Files Coverage Δ
statsmodels/iolib/summary2.py 87.08% <100%> (ø) ⬆️
statsmodels/multivariate/tests/test_factor.py 96.61% <100%> (-0.12%) ⬇️
statsmodels/multivariate/factor.py 76.78% <78.01%> (+2.66%) ⬆️
statsmodels/multivariate/tests/test_ml_factor.py 94.73% <94.73%> (ø)
statsmodels/stats/descriptivestats.py 24.13% <0%> (ø) ⬆️

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update b2c1c35...1258f18. Read the comment docs.

@kshedden

Copy link
Copy Markdown
Contributor Author

@josef-pkt, @yl565 Yes I think #3294 can be merged first and then I will modify #4156 to adapt to it.

One thing that would be desirable in my view is to add an argument cov to allow the covariance matrix to be passed directly rather than passing data, like this:

__init__(self, endog, n_factor, cov=None, exog=None, method='pa', **kwargs):

@josef-pkt

Copy link
Copy Markdown
Member

@kshedden Do you mean passing cov additional to endog or cov as a substitute for endog?

We need endog to compute the factors.

In general I would like more functions/classes that directly work with covariance, correlation or moment matrices or allow a call-back function for their computation. (main usecase that I ran into was robust or regularized covariance, but for FA and similar it is also possible to use polychoric or non-pearson correlation, AFAICS)

@kshedden

Copy link
Copy Markdown
Contributor Author

I would like to take cov as an alternative to endog. I don't think the model parameters depend on endog once cov is available (under the usual estimators). endog is required to obtain the scores, but this is an optional step that is not always needed. There are quite a few practical situations where you have a covariance matrix that needs to be factorized, but no data.

@josef-pkt

josef-pkt commented Dec 10, 2017 •

Copy link
Copy Markdown
Member

@kshedden I think it's better to leave adding cov as substitute for endog for 0.10. I don't see right away how this will work, when some results will depend on availability of endog.

a bit related: I was changing my mind several times about what arguments I need in computing the covariance of a covariance estimator. It's straightforward under normality assumption using cov, but we need a kurtosis estimate or a 4th moment estimate in the more general cases.
https://github.com/statsmodels/statsmodels/pull/4143/files#diff-4956ab798139dc28ab6854559f7292ecR174

Aside: You wrote stats.correlation_tools.cov_nearest_factor and cov_nearest_factor_homog. Do they produce a version of factor analysis? Can they be reused in multivariate?

@josef-pkt

Copy link
Copy Markdown
Member

I think it's better to leave adding cov as substitute for endog for 0.10.

I take this back, in the FA in #3294 endog is used only to compute the cov, only endog_names are used in results.

@kshedden

kshedden commented Dec 10, 2017 via email

Copy link
Copy Markdown
Contributor Author

@coveralls

coveralls commented Dec 15, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.02%) to 81.997% when pulling 2e47f1c on kshedden:factanal into b2c1c35 on statsmodels:master.

@kshedden

Copy link
Copy Markdown
Contributor Author

The test that fails is due to right padding of some rows of the summary with spaces. Not sure now how to address that.

@kshedden

Copy link
Copy Markdown
Contributor Author

summary fails for some reason when there is only one factor (a single column data-frame is added to the list of summary tables)

@josef-pkt

Copy link
Copy Markdown
Member

This pull request introduces 1 alert - view on lgtm.com

new alerts:

  • 1 for Potentially uninitialized local variable

Comment posted by lgtm.com

@josef-pkt

Copy link
Copy Markdown
Member

Travis, appveyor fail because you removed the results class

    from statsmodels.multivariate.factor import Factor
statsmodels/multivariate/factor.py:5: in <module>
    from .factor_results import FactorResults
E   ImportError: No module named 'statsmodels.multivariate.factor_results'

maybe you forgot to add the factor_results module.

why do you want to move the results class?

@kshedden

kshedden commented Dec 15, 2017 via email

Copy link
Copy Markdown
Contributor Author

@yl565

yl565 commented Dec 15, 2017

Copy link
Copy Markdown
Contributor

Remove from and use factor.FactorResults may work (https://stackoverflow.com/questions/11698530/two-python-modules-require-each-others-contents-can-that-work)
But I think maybe its better you pass the results to Factor.fit in tuple and call FactorResults in Factor.fit after elif method == 'ml':

@josef-pkt

Copy link
Copy Markdown
Member

I think the MLE factanal code can be merged into the main moduel factor.py.

I don't expect this to get so large that we need to split the main factor analysis over several modules. And as far as I can see it should conceptually all belong together.

@kshedden

Copy link
Copy Markdown
Contributor Author

Everything is back in one file now. I still have an issue with summary2 not handling a one column matrix (the summary2 code divides by x.dim[1] - 1).

@josef-pkt

Copy link
Copy Markdown
Member

quickfix for summary2

in iolib.summary2 line 249 which causes the exception, add a lower bound of 1 on nsep

nsep = max(tables[i].shape[1] - 1, 1)

It works for an example with one factor, but I haven't looked more closely at it.
Given that it didn't work for a single column, the change should not be dangerous and won't be in a current unit test yet

@josef-pkt

josef-pkt commented Dec 15, 2017 •

Copy link
Copy Markdown
Member

I also just ran into the whitespace failure for summary txt after cleaning trailing whitespace for a test that I'm writing.

You can replace the last part of test_example_compare_to_R_output to remove trailing whitespace in the actual (2 lines added):

    actual = results.summary().as_text()
    actual = '\n'.join(line.rstrip() for line in actual.splitlines())
    actual += '\n'
    assert_equal(actual, desired)

The unit test passes then for me locally.

@coveralls

coveralls commented Dec 17, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.009%) to 81.991% when pulling 9d29042 on kshedden:factanal into b2c1c35 on statsmodels:master.


def test_exact():
"""
Test if we can recover exact factor-structured matrices with default

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

no docstring for unit tests, use code comment #

@josef-pkt

Copy link
Copy Markdown
Member

all green now.

I did a brief read through the code, and I didn't see any problems.
The loglike is in a nested function and so it is not accessible. I guess we will need it as a separate, accessible method when we add more likelihood ratio based hypothesis tests or aic, bic and similar.

I think we need to squash the commits heavily to avoid the code movement and separate module in the history.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.007%) to 81.988% when pulling 1678dc4 on kshedden:factanal into b2c1c35 on statsmodels:master.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.01%) to 81.991% when pulling cf072f8 on kshedden:factanal into b2c1c35 on statsmodels:master.

1 similar comment
@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.01%) to 81.991% when pulling cf072f8 on kshedden:factanal into b2c1c35 on statsmodels:master.

@kshedden

Copy link
Copy Markdown
Contributor Author

Time reduced by half using analytic score function.

Possible point of user confusion: fit has maxiter, tol arguments for principal axes method, and also has opt dictionary for ML estimation, where opt may have tol and maxiter as keys.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.002%) to 81.98% when pulling 9a0d2d9 on kshedden:factanal into b2c1c35 on statsmodels:master.

@cache_readonly
def load_stderr(self):
"""
The standard errors of the loadings.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This has to specify "of the MLE rotated loadings"


assert_equal(rslt.df, 4)

# Smoke test for standard errors

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

better to use a regression test: just plug in current numbers

if type(par) is np.ndarray:
uniq, load = self._unpack(par)
else:
load, uniq = par[0], par[1]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

reversing the order of load, uniq might get confusing

@josef-pkt

Copy link
Copy Markdown
Member

test failures are most likely a wrong score method
Also, better add from __future__ import division

one python 2.7 has huge numbers in a failing score test. I don't see integer division, but adding the future is safer

@coveralls

coveralls commented Dec 19, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.02%) to 82.0% when pulling 3807cbb on kshedden:factanal into b2c1c35 on statsmodels:master.

# Do the optimization
if opt is None:
opt = _opt_defaults
r = minimize(nloglike, start, jac=nscore, method=opt_method,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

you could add mle_retvals to the results class, so it's possible to inspect convergence information.

@coveralls

coveralls commented Dec 20, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.02%) to 82.003% when pulling 5faeefb on kshedden:factanal into b2c1c35 on statsmodels:master.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.02%) to 82.003% when pulling 1258f18 on kshedden:factanal into b2c1c35 on statsmodels:master.

1 similar comment
@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.02%) to 82.003% when pulling 1258f18 on kshedden:factanal into b2c1c35 on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member

@kshedden If you are finished here, then we can merge this. It's all green now.

I'm trying to finish up #4171 with unit tests against Stata, so I can merge it on top of this merged PR.

#4164 has some comments on extensions and refactorings.
AFAICS, it will be better to move this to a full Model-Results pattern, which means mainly being more careful with attaching attributes and inplace modifications.

@kshedden

kshedden commented Dec 20, 2017 via email

Copy link
Copy Markdown
Contributor Author

@josef-pkt
josef-pkt merged commit 3f9c351 into statsmodels:master Dec 20, 2017
@josef-pkt

Copy link
Copy Markdown
Member

merged, factor analysis is starting to look good

@kshedden Thank you

@josef-pkt josef-pkt added this to the 0.9 milestone Dec 20, 2017
@josef-pkt josef-pkt mentioned this pull request Apr 9, 2018
@josef-pkt josef-pkt modified the milestone: 0.9 Apr 15, 2018
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.

5 participants