Skip to content

ENH: factor analysis follow-up #4164

Open

Description

@josef-pkt

#3294 (merged in #4161) has several comments discussion design ideas. Most likely some refactoring will be necessary with the addition of new features.

PR #4156 has MLE for factor analysis

Stata has several additional results and post estimation results that we are still missing. Some results only apply if FA has been estimated by MLE

a few ENH possibilities

  • factor scoring: compute factor arrays, not unique and several methods are possible
  • more methods to choose the number of factors
  • implementation: use initially a large number of factors and compute some results for each number of factors, as far as those are independent of initial choice of factors. e.g. Stata allows to rotate fewer factors than computed in the raw loadings matrix.
  • hypothesis tests, fit statistics: likelihood based statistics require MLE.
  • display help for interpreting rotated loadings: cutoff to skip printing small loadings coefficients, sort
  • ...

unclear to me: cov versus corr

The basic results are scale invariant or equivariant, but some extra results might not be, and for other results we want to go back to the original scaling, i.e. we need standard deviation or cov.
example: I was getting confused about computing the underlying factors because using correlation or standardized exog changes the scale to normalized/beta coefficients.
(There is a considerable literature on using corr instead of cov in FA and covariance structure models. Not all methods are invariant or equivariant, but I didn't read any details.)

Activity

  1. added this to the 0.10 milestone on Dec 14, 2017
  2. josef-pkt commented on Dec 14, 2017

    @josef-pkt
    MemberAuthor

    trying out one piece: visual aids for loading matrix using pandas

    converting loading dataframe to strings without small values

    ld = loadings_df.round(3).astype(str)
    ld[loadings_df.abs() < 0.3] = ''
    ld
    
    ld.to_latex()
    

    for html

    loadings_df.style.applymap(highlight_large).applymap(color_white_small)
    

    with styling functions (just experiments, thresholds hard coded):

    def highlight_large(val, two=True):
        '''
        highlight larger values.
        '''
        if not two:
         return 'background-color: yellow' if np.abs(val) > 0.5 else ''
    
        if np.abs(val) > 0.5:
            ss0 = 'background-color: yellow'
        elif np.abs(val) > 0.4:
            ss0 = 'background-color: #FFC'
        else:
            ss0 = ''
        return ss0
    
    def color_white_small(val):
        """
        Takes a scalar and returns a string with
        the css property `'color: white'` for small values, black otherwise.
    
        assumes black on white display
        """
        color = 'white' if np.abs(val) < 0.3 else 'black'
        return 'color: %s' % color
    

    (trying out https://stats.idre.ucla.edu/stata/output/factor-analysis/
    Stata's rotated values differ a bit, but they use a "horst" options in the example, whatever that is)

  3. josef-pkt commented on Dec 14, 2017

    @josef-pkt
    MemberAuthor

    small update: It looks like "horst" option has been renamed to "normalize"

    I can reverse engineer, based on the hints in the Stata documentation (normalize loading to rows norm=1 before rotation, then we need to renormalize after rotation to have the same communality

    In [142]:
    from statsmodels.multivariate.factor_rotation import rotate_factors, promax
    L, T = rotate_factors(res_u.loadings_no_rot / np.sqrt(res_u.communality[:, None]), 'varimax')
    Ln = L * np.sqrt(res_u.communality[:, None])
    Ln[0] / [0.7714,    0.1740,    0.2260], Ln[1] / [0.7256,    0.2130,    0.2171]
    
    Out[142]:
    (array([ 1.00005027, -1.00018477, -0.99974534]),
     array([ 1.0000974 , -1.00009217, -0.99937947]))
    

    But the same doesn't work for 'promax', I guess because oblique rotation don't preserve simple adding up to communality because factors are correlated.
    (or promax is buggy, there is some qualifying code comment)

  4. josef-pkt commented on Dec 14, 2017

    @josef-pkt
    MemberAuthor

    ENH: rotate doesn't attach the rotation matrix, T is thrown away.

  5. yl565 commented on Dec 15, 2017

    @yl565
    Contributor

    I like to implement Horn’s parallel analysis but I am having trouble accessing Horn's original article "A rationale and test for the number of factors in factor analysis"... I think a reasonable way to generate random data is to permute the raw data like in permutation test

  6. josef-pkt commented on Dec 15, 2017

    @josef-pkt
    MemberAuthor

    Horn's original article is not very interesting. It's not very explicit and uses an outdated version. (samples are random draws from maybe a normal distribution, or data that has been made to look close to normally distributed)

    Glorfeld seems to have introduced the 95% rule or using a quantile of the eigenvalue distribution instead of mean of simulated eigenvalues

    Dinno argues that the simulation distribution doesn't matter and wrote paran in R and Stata based on Glorfeld.

    Hayton, James C., David G. Allen, and Vida Scarpello. 2004 provide a good overview and implementation notes for SPSS
    O'Connor has both SAS and SPSS code in the article, and compares it also with Velicer's MAP

    The other articles, Crawford, Green and co-authors sound interesting. They look at it from sequential testing perspective, but I didn't look at the details to see what changes to the parallel algorithm they propose

    edit (after another brief look at overview/simulation articles)
    Crawford, Green, ... sequential method seems to require new simulation for deciding between k versus k+1 under the k null model. That means it's computationally more expensive and could be used only for the critical decision, e.g. after making an initial range decision based on Velicer's MAP or traditional parallel analysis
    (end edit)

    (There are some articles specific to ordinal variables like Garrido, but I didn't look at those)

    here's my Zotero list for "parallel" (I only skimmed parts and read a few sections of those articles):

    Crawford, Aaron V., Samuel B. Green, Roy Levy, Wen-Juo Lo, Lietta Scott, Dubravka Svetina, and Marilyn S. Thompson. 2010. “Evaluation of Parallel Analysis Methods for Determining the Number of Factors.” Educational and Psychological Measurement 70 (6):885–901. https://doi.org/10.1177/0013164410379332.

    Dinno, A. 2009. “Implementing Horn’s Parallel Analysis for Principal Component Analysis and Factor Analysis.” Stata Journal 9 (2):291–98.

    Dinno, Alexis. 2009. “Exploring the Sensitivity of Horn’s Parallel Analysis to the Distributional Form of Random Data.” Multivariate Behavioral Research 44 (3):362–88. https://doi.org/10.1080/00273170902938969.

    Garrido, Luis Eduardo, Francisco José Abad, and Vicente Ponsoda. 2013. “A New Look at Horn’s Parallel Analysis with Ordinal Variables.” Psychological Methods 18 (4):454–74. https://doi.org/10.1037/a0030005.

    Glorfeld, Louis W. 1995. “An Improvement on Horn’s Parallel Analysis Methodology for Selecting the Correct Number of Factors to Retain.” Educational and Psychological Measurement 55 (3):377–93. https://doi.org/10.1177/0013164495055003002.

    Green, Samuel B., Roy Levy, Marilyn S. Thompson, Min Lu, and Wen-Juo Lo. 2012. “A Proposed Solution to the Problem With Using Completely Random Data to Assess the Number of Factors With Parallel Analysis.” Educational and Psychological Measurement 72 (3):357–74. https://doi.org/10.1177/0013164411422252.

    Green, Samuel B., Nickalus Redell, Marilyn S. Thompson, and Roy Levy. 2016. “Accuracy of Revised and Traditional Parallel Analyses for Assessing Dimensionality with Binary Data.” Educational and Psychological Measurement 76 (1):5–21. https://doi.org/10.1177/0013164415581898.

    Green, Samuel B., Marilyn S. Thompson, Roy Levy, and Wen-Juo Lo. 2015. “Type I and Type II Error Rates and Overall Accuracy of the Revised Parallel Analysis Method for Determining the Number of Factors.” Educational and Psychological Measurement 75 (3):428–57. https://doi.org/10.1177/0013164414546566.

    Hayton, James C. 2009. “Commentary on ‘Exploring the Sensitivity of Horn’s Parallel Analysis to the Distributional Form of Random Data.’” Multivariate Behavioral Research 44 (3):389–95. https://doi.org/10.1080/00273170902939033.

    Hayton, James C., David G. Allen, and Vida Scarpello. 2004. “Factor Retention Decisions in Exploratory Factor Analysis: A Tutorial on Parallel Analysis.” Organizational Research Methods 7 (2):191–205. https://doi.org/10.1177/1094428104263675.

    O’connor, Brian P. 2000. “SPSS and SAS Programs for Determining the Number of Components Using Parallel Analysis and Velicer’s MAP Test.” Behavior Research Methods, Instruments, & Computers 32 (3):396–402. https://doi.org/10.3758/BF03200807.

  7. josef-pkt commented on Dec 15, 2017

    @josef-pkt
    MemberAuthor

    another issue:

    rotate could take a shortcut if the number of factors is 1, and just use the unrotated loading matrix (column)
    currently it emits
    RuntimeWarning: divide by zero encountered in log10 table.append([i_try, f, np.log10(s), al])

  8. josef-pkt commented on Dec 16, 2017

    @josef-pkt
    MemberAuthor

    Heywood?

    estimated communality > 1

    In [22]: res_r.communality
    Out[22]:
    array([ 0.57779158,  0.00546568,  0.14667013,  0.48566394,  0.07718203,
            0.48937477,  0.78774832,  1.40606732,  0.3125896 ,  0.02371634,
            0.47725439])
    

    from another semi-random example using a UCI wine quality dataset
    https://archive.ics.uci.edu/ml/datasets/Wine+Quality

    @yl565 @kshedden
    I haven't looked at the explanation for Heywood cases yet, I only saw it mentioned in the Stata and SAS documentation, where I think they force communality to be <= 1.

    http://nbviewer.jupyter.org/gist/josef-pkt/1da753c160a054c9f342e735ee9be05e

  9. josef-pkt commented on Dec 18, 2017

    @josef-pkt
    MemberAuthor

    update on factor scores:
    After a long time trying to replicate Stata, I finally managed to match their regression and ML/bartlett factor scores. (They didn't specify that Sigma in their formula is the raw correlation and not the fitted correlation. My impression from articles and books was that the fitted parameters are used, which is similar but not very close in terms of predicted factors.)

    The example case I used is after varimax rotation. After oblique rotation we also need the covariance of the rotated factors. My guess is that the only way to get those is by having access to the rotation matrix.
    This is currently not attached. rotate rotates but doesn't provide any information about the rotation.
    (If it's not available, then I think we can reverse engineer it because we have both loading matrices.)

    Another issue: sign indeterminacy in loadings matrix
    Stata has one factor with dominant positive values, while ours has negative values.
    My guess is that we want to standardize the sign so that the largest coefficient for each factor is positive.
    (not checked, but I did this a long time ago for PCA or similar.)

  10. josef-pkt commented on Dec 19, 2017

    @josef-pkt
    MemberAuthor

    issue: unverified rotation methods, and rotation options

    I guess we need a warning in the docstring
    from the unit tests

        results.rotate('equamax')  # Not the same as R fa
    
        results.rotate('promax')  # Not the same as R fa
    
        results.rotate('biquartimin')  # Not the same as R fa
    

    promax is essentially identical to varimax at around atol = 1e-5
    I just saw that Stata uses promax(3) as default, ours has hardcoded promax(2). We need to forward args to the rotation method to allow this to be changed by users.
    Even if I use promax(2) in Stata, the loadings matrix doesn't match up.

    oblimin looks identical to Stata: rotate, oblique oblimin except for signs and ordering of factors in loading matrix.
    (I have no idea how the sign and ordering is determined, most likely just the consequence of an implementation detail of the algorithm.)

    transformation matrix and Phi (corr_factors) also matches up to sign and ordering

    transformation matrix
    To = np.linalg.pinv(res_w.loadings).dot(res_w.loadings_no_rot).T

    correlation of factors, Stata matrix list e(r_Phi)

    To.T.dot(To)
    array([[ 1.        , -0.24173146, -0.49755607],
           [-0.24173146,  1.        ,  0.06087843],
           [-0.49755607,  0.06087843,  1.        ]])
    

    compared to Stata

    . matrix list e(r_Phi)
    
    symmetric e(r_Phi)[3,3]
               Factor1    Factor2    Factor3
    Factor1          1
    Factor2  .49755537          1
    Factor3  .24174295  .06088571          1
    
  11. josef-pkt commented on Dec 19, 2017

    @josef-pkt
    MemberAuthor

    predict factors after oblique oblimin

    tt changes order and sign of factors

    this looks identical to
    predict f1o f2o f3o
    "Scoring coefficients (method = regression; based on oblimin(0) rotated factors)"

    tt = np.array([[-1, 0, 0], [0, 0, 1], [0, 1, 0]])
    tt.dot(corr_f.dot(res_w.loadings.T.dot(np.linalg.inv(sig_r)))).T
    

    scored factors for first few observation are also identical up to some print precision

    tscore.T.dot(df_ws.values.T).T

  12. josef-pkt commented on Dec 20, 2017

    @josef-pkt
    MemberAuthor

    turning Factor into a "proper" model: add attributes and watch changes

    I needed the original correlation matrix. However, when I attached it to the model it was not correct because fit_pa made an inplace modification to the diagonal. Inplace modification is efficient in terms of the algorithm but prevents reuse. I guess, AFAICS from code, a user provided corr would also be modified inplace.

    Also: for computing the factors themselves (factor scoring) we need the standardized endog. If user provides new endog (for prediction of factors), then we need to keep loc and scale of the standardization around, assuming that we need to apply the same transformation (stateful transform as in patsy)
    we will eventually need a standardize keyword, and maybe follow the standard predict pattern with trasnform keyword.

  13. josef-pkt commented on Dec 22, 2017

    @josef-pkt
    MemberAuthor

    I just saw that scikit-learn has a sign flip function for svd
    https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py#L499
    currently signs of factor in loadings are "random"

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

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions