Repository files navigation

FactorAnalyzer

Build statusCode coverageConda versionPyPI versionDocsPre-commit checks

This is a Python module to perform exploratory and factor analysis (EFA), with several optional rotations. It also includes a class to perform confirmatory factor analysis (CFA), with certain pre-defined constraints. In exploratory factor analysis, factor extraction can be performed using a variety of estimation techniques. The factor_analyzer package allows users to perform EFA using either (1) a minimum residual (MINRES) solution, (2) a maximum likelihood (ML) solution, or (3) a principal factor solution. However, CFA can only be performed using an ML solution.

Both the EFA and CFA classes within this package are fully compatible with scikit-learn. Portions of this code are ported from the excellent R library psych, and the sem package provided inspiration for the CFA class.

Please see the official documentation for additional details.

Description

Exploratory factor analysis (EFA) is a statistical technique used to identify latent relationships among sets of observed variables in a dataset. In particular, EFA seeks to model a large set of observed variables as linear combinations of some smaller set of unobserved, latent factors. The matrix of weights, or factor loadings, generated from an EFA model describes the underlying relationships between each variable and the latent factors.

Confirmatory factor analysis (CFA), a closely associated technique, is used to test an a priori hypothesis about latent relationships among sets of observed variables. In CFA, the researcher specifies the expected pattern of factor loadings (and possibly other constraints), and fits a model according to this specification.

Typically, a number of factors (K) in an EFA or CFA model is selected such that it is substantially smaller than the number of variables. The factor analysis model can be estimated using a variety of standard estimation methods, including but not limited MINRES or ML.

Factor loadings are similar to standardized regression coefficients, and variables with higher loadings on a particular factor can be interpreted as explaining a larger proportion of the variation in that factor. In the case of EFA, factor loading matrices are usually rotated after the factor analysis model is estimated in order to produce a simpler, more interpretable structure to identify which variables are loading on a particular factor.

Two common types of rotations are:

  1. The varimax rotation, which rotates the factor loading matrix so as to maximize the sum of the variance of squared loadings, while preserving the orthogonality of the loading matrix.
  2. The promax rotation, a method for oblique rotation, which builds upon the varimax rotation, but ultimately allows factors to become correlated.

This package includes a factor_analyzer module with a stand-alone FactorAnalyzer class. The class includes fit() and transform() methods that enable users to perform factor analysis and score new data using the fitted factor model. Users can also perform optional rotations on a factor loading matrix using the Rotator class.

The following rotation options are available in both FactorAnalyzer and Rotator:

  1. varimax (orthogonal rotation)
  2. promax (oblique rotation)
  3. oblimin (oblique rotation)
  4. oblimax (orthogonal rotation)
  5. quartimin (oblique rotation)
  6. quartimax (orthogonal rotation)
  7. equamax (orthogonal rotation)
  8. geomin_obl (oblique rotation)
  9. geomin_ort (orthogonal rotation)

In addition, the package includes a confirmatory_factor_analyzer module with a stand-alone ConfirmatoryFactorAnalyzer class. The class includes fit() and transform() that enable users to perform confirmatory factor analysis and score new data using the fitted model. Performing CFA requires users to specify in advance a model specification with the expected factor loading relationships. This can be done using the ModelSpecificationParser class.

Note that the ConfirmatoryFactorAnalyzer class is very experimental at this point, so use it with caution, especially if your data are highly non-normal.

Examples

Exploratory factor analysis example.

In [1]: importpandasaspd
...: fromfactor_analyzerimportFactorAnalyzerIn [2]: df_features=pd.read_csv('tests/data/test02.csv')
In [3]: fa=FactorAnalyzer(rotation=None)
In [4]: fa.fit(df_features)
Out[4]:
FactorAnalyzer(bounds=(0.005, 1), impute='median', is_corr_matrix=False,
method='minres', n_factors=3, rotation=None, rotation_kwargs={},
use_smc=True)
In [5]: fa.loadings_Out[5]:
array([[-0.12991218, 0.16398151, 0.73823491],
[ 0.03899558, 0.04658425, 0.01150343],
[ 0.34874135, 0.61452341, -0.07255666],
[ 0.45318006, 0.7192668 , -0.0754647 ],
[ 0.36688794, 0.44377343, -0.01737066],
[ 0.74141382, -0.15008235, 0.29977513],
[ 0.741675 , -0.16123009, -0.20744497],
[ 0.82910167, -0.20519428, 0.04930817],
[ 0.76041819, -0.23768727, -0.12068582],
[ 0.81533404, -0.12494695, 0.17639684]])
In [6]: fa.get_communalities()
Out[6]:
array([0.5887579 , 0.00382308, 0.50452402, 0.72841182, 0.33184336,
0.66208429, 0.61911037, 0.73194557, 0.64929612, 0.71149718])

Confirmatory factor analysis example.

In [1]: importpandasaspdIn [2]: fromfactor_analyzerimport (ConfirmatoryFactorAnalyzer,
...: ModelSpecificationParser)
In [3]: df_features=pd.read_csv('tests/data/test11.csv')
In [4]: model_dict= {"F1": ["V1", "V2", "V3", "V4"],
...: "F2": ["V5", "V6", "V7", "V8"]}
In [5]: model_spec=ModelSpecificationParser.parse_model_specification_from_dict(df_features,
...: model_dict)
In [6]: cfa=ConfirmatoryFactorAnalyzer(model_spec, disp=False)
In [7]: cfa.fit(df_features.values)
In [8]: cfa.loadings_Out[8]:
array([[0.99131285, 0. ],
[0.46074919, 0. ],
[0.3502267 , 0. ],
[0.58331488, 0. ],
[0. , 0.98621042],
[0. , 0.73389239],
[0. , 0.37602988],
[0. , 0.50049507]])
In [9]: cfa.factor_varcovs_Out[9]:
array([[1. , 0.17385704],
[0.17385704, 1. ]])
In [10]: cfa.transform(df_features.values)
Out[10]:
array([[-0.46852166, -1.08708035],
[ 2.59025301, 1.20227783],
[-0.47215977, 2.65697245],
...,
[-1.5930886 , -0.91804114],
[ 0.19430887, 0.88174818],
[-0.27863554, -0.7695101 ]])

Requirements

  • Python 3.8 or higher
  • numpy
  • pandas
  • scipy
  • scikit-learn >= 1.6.0

Contributing

Contributions to factor_analyzer are very welcome. Please file an issue in the repository if you would like to contribute.

You can install the development requirements in a virtual environment with:

python -m pip install -e .[dev]
pre-commit install

Installation

You can install this package via pip with:

$ pip install factor_analyzer

Alternatively, you can install via conda with:

$ conda install -c ets factor_analyzer

License

GNU General Public License (>= 2)

About

A Python module to perform exploratory & confirmatory factor analyses.

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

FactorAnalyzer

Build statusCode coverageConda versionPyPI versionDocsPre-commit checks

This is a Python module to perform exploratory and factor analysis (EFA), with several optional rotations. It also includes a class to perform confirmatory factor analysis (CFA), with certain pre-defined constraints. In exploratory factor analysis, factor extraction can be performed using a variety of estimation techniques. The factor_analyzer package allows users to perform EFA using either (1) a minimum residual (MINRES) solution, (2) a maximum likelihood (ML) solution, or (3) a principal factor solution. However, CFA can only be performed using an ML solution.

Both the EFA and CFA classes within this package are fully compatible with scikit-learn. Portions of this code are ported from the excellent R library psych, and the sem package provided inspiration for the CFA class.

Please see the official documentation for additional details.

Description

Exploratory factor analysis (EFA) is a statistical technique used to identify latent relationships among sets of observed variables in a dataset. In particular, EFA seeks to model a large set of observed variables as linear combinations of some smaller set of unobserved, latent factors. The matrix of weights, or factor loadings, generated from an EFA model describes the underlying relationships between each variable and the latent factors.

Confirmatory factor analysis (CFA), a closely associated technique, is used to test an a priori hypothesis about latent relationships among sets of observed variables. In CFA, the researcher specifies the expected pattern of factor loadings (and possibly other constraints), and fits a model according to this specification.

Typically, a number of factors (K) in an EFA or CFA model is selected such that it is substantially smaller than the number of variables. The factor analysis model can be estimated using a variety of standard estimation methods, including but not limited MINRES or ML.

Factor loadings are similar to standardized regression coefficients, and variables with higher loadings on a particular factor can be interpreted as explaining a larger proportion of the variation in that factor. In the case of EFA, factor loading matrices are usually rotated after the factor analysis model is estimated in order to produce a simpler, more interpretable structure to identify which variables are loading on a particular factor.

Two common types of rotations are:

  1. The varimax rotation, which rotates the factor loading matrix so as to maximize the sum of the variance of squared loadings, while preserving the orthogonality of the loading matrix.
  2. The promax rotation, a method for oblique rotation, which builds upon the varimax rotation, but ultimately allows factors to become correlated.

This package includes a factor_analyzer module with a stand-alone FactorAnalyzer class. The class includes fit() and transform() methods that enable users to perform factor analysis and score new data using the fitted factor model. Users can also perform optional rotations on a factor loading matrix using the Rotator class.

The following rotation options are available in both FactorAnalyzer and Rotator:

  1. varimax (orthogonal rotation)
  2. promax (oblique rotation)
  3. oblimin (oblique rotation)
  4. oblimax (orthogonal rotation)
  5. quartimin (oblique rotation)
  6. quartimax (orthogonal rotation)
  7. equamax (orthogonal rotation)
  8. geomin_obl (oblique rotation)
  9. geomin_ort (orthogonal rotation)

In addition, the package includes a confirmatory_factor_analyzer module with a stand-alone ConfirmatoryFactorAnalyzer class. The class includes fit() and transform() that enable users to perform confirmatory factor analysis and score new data using the fitted model. Performing CFA requires users to specify in advance a model specification with the expected factor loading relationships. This can be done using the ModelSpecificationParser class.

Note that the ConfirmatoryFactorAnalyzer class is very experimental at this point, so use it with caution, especially if your data are highly non-normal.

Examples

Exploratory factor analysis example.

In [1]: importpandasaspd
...: fromfactor_analyzerimportFactorAnalyzerIn [2]: df_features=pd.read_csv('tests/data/test02.csv')
In [3]: fa=FactorAnalyzer(rotation=None)
In [4]: fa.fit(df_features)
Out[4]:
FactorAnalyzer(bounds=(0.005, 1), impute='median', is_corr_matrix=False,
method='minres', n_factors=3, rotation=None, rotation_kwargs={},
use_smc=True)
In [5]: fa.loadings_Out[5]:
array([[-0.12991218, 0.16398151, 0.73823491],
[ 0.03899558, 0.04658425, 0.01150343],
[ 0.34874135, 0.61452341, -0.07255666],
[ 0.45318006, 0.7192668 , -0.0754647 ],
[ 0.36688794, 0.44377343, -0.01737066],
[ 0.74141382, -0.15008235, 0.29977513],
[ 0.741675 , -0.16123009, -0.20744497],
[ 0.82910167, -0.20519428, 0.04930817],
[ 0.76041819, -0.23768727, -0.12068582],
[ 0.81533404, -0.12494695, 0.17639684]])
In [6]: fa.get_communalities()
Out[6]:
array([0.5887579 , 0.00382308, 0.50452402, 0.72841182, 0.33184336,
0.66208429, 0.61911037, 0.73194557, 0.64929612, 0.71149718])

Confirmatory factor analysis example.

In [1]: importpandasaspdIn [2]: fromfactor_analyzerimport (ConfirmatoryFactorAnalyzer,
...: ModelSpecificationParser)
In [3]: df_features=pd.read_csv('tests/data/test11.csv')
In [4]: model_dict= {"F1": ["V1", "V2", "V3", "V4"],
...: "F2": ["V5", "V6", "V7", "V8"]}
In [5]: model_spec=ModelSpecificationParser.parse_model_specification_from_dict(df_features,
...: model_dict)
In [6]: cfa=ConfirmatoryFactorAnalyzer(model_spec, disp=False)
In [7]: cfa.fit(df_features.values)
In [8]: cfa.loadings_Out[8]:
array([[0.99131285, 0. ],
[0.46074919, 0. ],
[0.3502267 , 0. ],
[0.58331488, 0. ],
[0. , 0.98621042],
[0. , 0.73389239],
[0. , 0.37602988],
[0. , 0.50049507]])
In [9]: cfa.factor_varcovs_Out[9]:
array([[1. , 0.17385704],
[0.17385704, 1. ]])
In [10]: cfa.transform(df_features.values)
Out[10]:
array([[-0.46852166, -1.08708035],
[ 2.59025301, 1.20227783],
[-0.47215977, 2.65697245],
...,
[-1.5930886 , -0.91804114],
[ 0.19430887, 0.88174818],
[-0.27863554, -0.7695101 ]])

Requirements

  • Python 3.8 or higher
  • numpy
  • pandas
  • scipy
  • scikit-learn >= 1.6.0

Contributing

Contributions to factor_analyzer are very welcome. Please file an issue in the repository if you would like to contribute.

You can install the development requirements in a virtual environment with:

python -m pip install -e .[dev]
pre-commit install

Installation

You can install this package via pip with:

$ pip install factor_analyzer

Alternatively, you can install via conda with:

$ conda install -c ets factor_analyzer

License

GNU General Public License (>= 2)

About

A Python module to perform exploratory & confirmatory factor analyses.

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

FactorAnalyzer

Build statusCode coverageConda versionPyPI versionDocsPre-commit checks

This is a Python module to perform exploratory and factor analysis (EFA), with several optional rotations. It also includes a class to perform confirmatory factor analysis (CFA), with certain pre-defined constraints. In exploratory factor analysis, factor extraction can be performed using a variety of estimation techniques. The factor_analyzer package allows users to perform EFA using either (1) a minimum residual (MINRES) solution, (2) a maximum likelihood (ML) solution, or (3) a principal factor solution. However, CFA can only be performed using an ML solution.

Both the EFA and CFA classes within this package are fully compatible with scikit-learn. Portions of this code are ported from the excellent R library psych, and the sem package provided inspiration for the CFA class.

Please see the official documentation for additional details.

Description

Exploratory factor analysis (EFA) is a statistical technique used to identify latent relationships among sets of observed variables in a dataset. In particular, EFA seeks to model a large set of observed variables as linear combinations of some smaller set of unobserved, latent factors. The matrix of weights, or factor loadings, generated from an EFA model describes the underlying relationships between each variable and the latent factors.

Confirmatory factor analysis (CFA), a closely associated technique, is used to test an a priori hypothesis about latent relationships among sets of observed variables. In CFA, the researcher specifies the expected pattern of factor loadings (and possibly other constraints), and fits a model according to this specification.

Typically, a number of factors (K) in an EFA or CFA model is selected such that it is substantially smaller than the number of variables. The factor analysis model can be estimated using a variety of standard estimation methods, including but not limited MINRES or ML.

Factor loadings are similar to standardized regression coefficients, and variables with higher loadings on a particular factor can be interpreted as explaining a larger proportion of the variation in that factor. In the case of EFA, factor loading matrices are usually rotated after the factor analysis model is estimated in order to produce a simpler, more interpretable structure to identify which variables are loading on a particular factor.

Two common types of rotations are:

  1. The varimax rotation, which rotates the factor loading matrix so as to maximize the sum of the variance of squared loadings, while preserving the orthogonality of the loading matrix.
  2. The promax rotation, a method for oblique rotation, which builds upon the varimax rotation, but ultimately allows factors to become correlated.

This package includes a factor_analyzer module with a stand-alone FactorAnalyzer class. The class includes fit() and transform() methods that enable users to perform factor analysis and score new data using the fitted factor model. Users can also perform optional rotations on a factor loading matrix using the Rotator class.

The following rotation options are available in both FactorAnalyzer and Rotator:

  1. varimax (orthogonal rotation)
  2. promax (oblique rotation)
  3. oblimin (oblique rotation)
  4. oblimax (orthogonal rotation)
  5. quartimin (oblique rotation)
  6. quartimax (orthogonal rotation)
  7. equamax (orthogonal rotation)
  8. geomin_obl (oblique rotation)
  9. geomin_ort (orthogonal rotation)

In addition, the package includes a confirmatory_factor_analyzer module with a stand-alone ConfirmatoryFactorAnalyzer class. The class includes fit() and transform() that enable users to perform confirmatory factor analysis and score new data using the fitted model. Performing CFA requires users to specify in advance a model specification with the expected factor loading relationships. This can be done using the ModelSpecificationParser class.

Note that the ConfirmatoryFactorAnalyzer class is very experimental at this point, so use it with caution, especially if your data are highly non-normal.

Examples

Exploratory factor analysis example.

In [1]: importpandasaspd
...: fromfactor_analyzerimportFactorAnalyzerIn [2]: df_features=pd.read_csv('tests/data/test02.csv')
In [3]: fa=FactorAnalyzer(rotation=None)
In [4]: fa.fit(df_features)
Out[4]:
FactorAnalyzer(bounds=(0.005, 1), impute='median', is_corr_matrix=False,
method='minres', n_factors=3, rotation=None, rotation_kwargs={},
use_smc=True)
In [5]: fa.loadings_Out[5]:
array([[-0.12991218, 0.16398151, 0.73823491],
[ 0.03899558, 0.04658425, 0.01150343],
[ 0.34874135, 0.61452341, -0.07255666],
[ 0.45318006, 0.7192668 , -0.0754647 ],
[ 0.36688794, 0.44377343, -0.01737066],
[ 0.74141382, -0.15008235, 0.29977513],
[ 0.741675 , -0.16123009, -0.20744497],
[ 0.82910167, -0.20519428, 0.04930817],
[ 0.76041819, -0.23768727, -0.12068582],
[ 0.81533404, -0.12494695, 0.17639684]])
In [6]: fa.get_communalities()
Out[6]:
array([0.5887579 , 0.00382308, 0.50452402, 0.72841182, 0.33184336,
0.66208429, 0.61911037, 0.73194557, 0.64929612, 0.71149718])

Confirmatory factor analysis example.

In [1]: importpandasaspdIn [2]: fromfactor_analyzerimport (ConfirmatoryFactorAnalyzer,
...: ModelSpecificationParser)
In [3]: df_features=pd.read_csv('tests/data/test11.csv')
In [4]: model_dict= {"F1": ["V1", "V2", "V3", "V4"],
...: "F2": ["V5", "V6", "V7", "V8"]}
In [5]: model_spec=ModelSpecificationParser.parse_model_specification_from_dict(df_features,
...: model_dict)
In [6]: cfa=ConfirmatoryFactorAnalyzer(model_spec, disp=False)
In [7]: cfa.fit(df_features.values)
In [8]: cfa.loadings_Out[8]:
array([[0.99131285, 0. ],
[0.46074919, 0. ],
[0.3502267 , 0. ],
[0.58331488, 0. ],
[0. , 0.98621042],
[0. , 0.73389239],
[0. , 0.37602988],
[0. , 0.50049507]])
In [9]: cfa.factor_varcovs_Out[9]:
array([[1. , 0.17385704],
[0.17385704, 1. ]])
In [10]: cfa.transform(df_features.values)
Out[10]:
array([[-0.46852166, -1.08708035],
[ 2.59025301, 1.20227783],
[-0.47215977, 2.65697245],
...,
[-1.5930886 , -0.91804114],
[ 0.19430887, 0.88174818],
[-0.27863554, -0.7695101 ]])

Requirements

  • Python 3.8 or higher
  • numpy
  • pandas
  • scipy
  • scikit-learn >= 1.6.0

Contributing

Contributions to factor_analyzer are very welcome. Please file an issue in the repository if you would like to contribute.

You can install the development requirements in a virtual environment with:

python -m pip install -e .[dev]
pre-commit install

Installation

You can install this package via pip with:

$ pip install factor_analyzer

Alternatively, you can install via conda with:

$ conda install -c ets factor_analyzer

License

GNU General Public License (>= 2)

About

A Python module to perform exploratory & confirmatory factor analyses.

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

FactorAnalyzer

Build statusCode coverageConda versionPyPI versionDocsPre-commit checks

This is a Python module to perform exploratory and factor analysis (EFA), with several optional rotations. It also includes a class to perform confirmatory factor analysis (CFA), with certain pre-defined constraints. In exploratory factor analysis, factor extraction can be performed using a variety of estimation techniques. The factor_analyzer package allows users to perform EFA using either (1) a minimum residual (MINRES) solution, (2) a maximum likelihood (ML) solution, or (3) a principal factor solution. However, CFA can only be performed using an ML solution.

Both the EFA and CFA classes within this package are fully compatible with scikit-learn. Portions of this code are ported from the excellent R library psych, and the sem package provided inspiration for the CFA class.

Please see the official documentation for additional details.

Description

Exploratory factor analysis (EFA) is a statistical technique used to identify latent relationships among sets of observed variables in a dataset. In particular, EFA seeks to model a large set of observed variables as linear combinations of some smaller set of unobserved, latent factors. The matrix of weights, or factor loadings, generated from an EFA model describes the underlying relationships between each variable and the latent factors.

Confirmatory factor analysis (CFA), a closely associated technique, is used to test an a priori hypothesis about latent relationships among sets of observed variables. In CFA, the researcher specifies the expected pattern of factor loadings (and possibly other constraints), and fits a model according to this specification.

Typically, a number of factors (K) in an EFA or CFA model is selected such that it is substantially smaller than the number of variables. The factor analysis model can be estimated using a variety of standard estimation methods, including but not limited MINRES or ML.

Factor loadings are similar to standardized regression coefficients, and variables with higher loadings on a particular factor can be interpreted as explaining a larger proportion of the variation in that factor. In the case of EFA, factor loading matrices are usually rotated after the factor analysis model is estimated in order to produce a simpler, more interpretable structure to identify which variables are loading on a particular factor.

Two common types of rotations are:

  1. The varimax rotation, which rotates the factor loading matrix so as to maximize the sum of the variance of squared loadings, while preserving the orthogonality of the loading matrix.
  2. The promax rotation, a method for oblique rotation, which builds upon the varimax rotation, but ultimately allows factors to become correlated.

This package includes a factor_analyzer module with a stand-alone FactorAnalyzer class. The class includes fit() and transform() methods that enable users to perform factor analysis and score new data using the fitted factor model. Users can also perform optional rotations on a factor loading matrix using the Rotator class.

The following rotation options are available in both FactorAnalyzer and Rotator:

  1. varimax (orthogonal rotation)
  2. promax (oblique rotation)
  3. oblimin (oblique rotation)
  4. oblimax (orthogonal rotation)
  5. quartimin (oblique rotation)
  6. quartimax (orthogonal rotation)
  7. equamax (orthogonal rotation)
  8. geomin_obl (oblique rotation)
  9. geomin_ort (orthogonal rotation)

In addition, the package includes a confirmatory_factor_analyzer module with a stand-alone ConfirmatoryFactorAnalyzer class. The class includes fit() and transform() that enable users to perform confirmatory factor analysis and score new data using the fitted model. Performing CFA requires users to specify in advance a model specification with the expected factor loading relationships. This can be done using the ModelSpecificationParser class.

Note that the ConfirmatoryFactorAnalyzer class is very experimental at this point, so use it with caution, especially if your data are highly non-normal.

Examples

Exploratory factor analysis example.

In [1]: importpandasaspd
...: fromfactor_analyzerimportFactorAnalyzerIn [2]: df_features=pd.read_csv('tests/data/test02.csv')
In [3]: fa=FactorAnalyzer(rotation=None)
In [4]: fa.fit(df_features)
Out[4]:
FactorAnalyzer(bounds=(0.005, 1), impute='median', is_corr_matrix=False,
method='minres', n_factors=3, rotation=None, rotation_kwargs={},
use_smc=True)
In [5]: fa.loadings_Out[5]:
array([[-0.12991218, 0.16398151, 0.73823491],
[ 0.03899558, 0.04658425, 0.01150343],
[ 0.34874135, 0.61452341, -0.07255666],
[ 0.45318006, 0.7192668 , -0.0754647 ],
[ 0.36688794, 0.44377343, -0.01737066],
[ 0.74141382, -0.15008235, 0.29977513],
[ 0.741675 , -0.16123009, -0.20744497],
[ 0.82910167, -0.20519428, 0.04930817],
[ 0.76041819, -0.23768727, -0.12068582],
[ 0.81533404, -0.12494695, 0.17639684]])
In [6]: fa.get_communalities()
Out[6]:
array([0.5887579 , 0.00382308, 0.50452402, 0.72841182, 0.33184336,
0.66208429, 0.61911037, 0.73194557, 0.64929612, 0.71149718])

Confirmatory factor analysis example.

In [1]: importpandasaspdIn [2]: fromfactor_analyzerimport (ConfirmatoryFactorAnalyzer,
...: ModelSpecificationParser)
In [3]: df_features=pd.read_csv('tests/data/test11.csv')
In [4]: model_dict= {"F1": ["V1", "V2", "V3", "V4"],
...: "F2": ["V5", "V6", "V7", "V8"]}
In [5]: model_spec=ModelSpecificationParser.parse_model_specification_from_dict(df_features,
...: model_dict)
In [6]: cfa=ConfirmatoryFactorAnalyzer(model_spec, disp=False)
In [7]: cfa.fit(df_features.values)
In [8]: cfa.loadings_Out[8]:
array([[0.99131285, 0. ],
[0.46074919, 0. ],
[0.3502267 , 0. ],
[0.58331488, 0. ],
[0. , 0.98621042],
[0. , 0.73389239],
[0. , 0.37602988],
[0. , 0.50049507]])
In [9]: cfa.factor_varcovs_Out[9]:
array([[1. , 0.17385704],
[0.17385704, 1. ]])
In [10]: cfa.transform(df_features.values)
Out[10]:
array([[-0.46852166, -1.08708035],
[ 2.59025301, 1.20227783],
[-0.47215977, 2.65697245],
...,
[-1.5930886 , -0.91804114],
[ 0.19430887, 0.88174818],
[-0.27863554, -0.7695101 ]])

Requirements

  • Python 3.8 or higher
  • numpy
  • pandas
  • scipy
  • scikit-learn >= 1.6.0

Contributing

Contributions to factor_analyzer are very welcome. Please file an issue in the repository if you would like to contribute.

You can install the development requirements in a virtual environment with:

python -m pip install -e .[dev]
pre-commit install

Installation

You can install this package via pip with:

$ pip install factor_analyzer

Alternatively, you can install via conda with:

$ conda install -c ets factor_analyzer

License

GNU General Public License (>= 2)

About

A Python module to perform exploratory & confirmatory factor analyses.

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

FactorAnalyzer

Build statusCode coverageConda versionPyPI versionDocsPre-commit checks

This is a Python module to perform exploratory and factor analysis (EFA), with several optional rotations. It also includes a class to perform confirmatory factor analysis (CFA), with certain pre-defined constraints. In exploratory factor analysis, factor extraction can be performed using a variety of estimation techniques. The factor_analyzer package allows users to perform EFA using either (1) a minimum residual (MINRES) solution, (2) a maximum likelihood (ML) solution, or (3) a principal factor solution. However, CFA can only be performed using an ML solution.

Both the EFA and CFA classes within this package are fully compatible with scikit-learn. Portions of this code are ported from the excellent R library psych, and the sem package provided inspiration for the CFA class.

Please see the official documentation for additional details.

Description

Exploratory factor analysis (EFA) is a statistical technique used to identify latent relationships among sets of observed variables in a dataset. In particular, EFA seeks to model a large set of observed variables as linear combinations of some smaller set of unobserved, latent factors. The matrix of weights, or factor loadings, generated from an EFA model describes the underlying relationships between each variable and the latent factors.

Confirmatory factor analysis (CFA), a closely associated technique, is used to test an a priori hypothesis about latent relationships among sets of observed variables. In CFA, the researcher specifies the expected pattern of factor loadings (and possibly other constraints), and fits a model according to this specification.

Typically, a number of factors (K) in an EFA or CFA model is selected such that it is substantially smaller than the number of variables. The factor analysis model can be estimated using a variety of standard estimation methods, including but not limited MINRES or ML.

Factor loadings are similar to standardized regression coefficients, and variables with higher loadings on a particular factor can be interpreted as explaining a larger proportion of the variation in that factor. In the case of EFA, factor loading matrices are usually rotated after the factor analysis model is estimated in order to produce a simpler, more interpretable structure to identify which variables are loading on a particular factor.

Two common types of rotations are:

  1. The varimax rotation, which rotates the factor loading matrix so as to maximize the sum of the variance of squared loadings, while preserving the orthogonality of the loading matrix.
  2. The promax rotation, a method for oblique rotation, which builds upon the varimax rotation, but ultimately allows factors to become correlated.

This package includes a factor_analyzer module with a stand-alone FactorAnalyzer class. The class includes fit() and transform() methods that enable users to perform factor analysis and score new data using the fitted factor model. Users can also perform optional rotations on a factor loading matrix using the Rotator class.

The following rotation options are available in both FactorAnalyzer and Rotator:

  1. varimax (orthogonal rotation)
  2. promax (oblique rotation)
  3. oblimin (oblique rotation)
  4. oblimax (orthogonal rotation)
  5. quartimin (oblique rotation)
  6. quartimax (orthogonal rotation)
  7. equamax (orthogonal rotation)
  8. geomin_obl (oblique rotation)
  9. geomin_ort (orthogonal rotation)

In addition, the package includes a confirmatory_factor_analyzer module with a stand-alone ConfirmatoryFactorAnalyzer class. The class includes fit() and transform() that enable users to perform confirmatory factor analysis and score new data using the fitted model. Performing CFA requires users to specify in advance a model specification with the expected factor loading relationships. This can be done using the ModelSpecificationParser class.

Note that the ConfirmatoryFactorAnalyzer class is very experimental at this point, so use it with caution, especially if your data are highly non-normal.

Examples

Exploratory factor analysis example.

In [1]: importpandasaspd
...: fromfactor_analyzerimportFactorAnalyzerIn [2]: df_features=pd.read_csv('tests/data/test02.csv')
In [3]: fa=FactorAnalyzer(rotation=None)
In [4]: fa.fit(df_features)
Out[4]:
FactorAnalyzer(bounds=(0.005, 1), impute='median', is_corr_matrix=False,
method='minres', n_factors=3, rotation=None, rotation_kwargs={},
use_smc=True)
In [5]: fa.loadings_Out[5]:
array([[-0.12991218, 0.16398151, 0.73823491],
[ 0.03899558, 0.04658425, 0.01150343],
[ 0.34874135, 0.61452341, -0.07255666],
[ 0.45318006, 0.7192668 , -0.0754647 ],
[ 0.36688794, 0.44377343, -0.01737066],
[ 0.74141382, -0.15008235, 0.29977513],
[ 0.741675 , -0.16123009, -0.20744497],
[ 0.82910167, -0.20519428, 0.04930817],
[ 0.76041819, -0.23768727, -0.12068582],
[ 0.81533404, -0.12494695, 0.17639684]])
In [6]: fa.get_communalities()
Out[6]:
array([0.5887579 , 0.00382308, 0.50452402, 0.72841182, 0.33184336,
0.66208429, 0.61911037, 0.73194557, 0.64929612, 0.71149718])

Confirmatory factor analysis example.

In [1]: importpandasaspdIn [2]: fromfactor_analyzerimport (ConfirmatoryFactorAnalyzer,
...: ModelSpecificationParser)
In [3]: df_features=pd.read_csv('tests/data/test11.csv')
In [4]: model_dict= {"F1": ["V1", "V2", "V3", "V4"],
...: "F2": ["V5", "V6", "V7", "V8"]}
In [5]: model_spec=ModelSpecificationParser.parse_model_specification_from_dict(df_features,
...: model_dict)
In [6]: cfa=ConfirmatoryFactorAnalyzer(model_spec, disp=False)
In [7]: cfa.fit(df_features.values)
In [8]: cfa.loadings_Out[8]:
array([[0.99131285, 0. ],
[0.46074919, 0. ],
[0.3502267 , 0. ],
[0.58331488, 0. ],
[0. , 0.98621042],
[0. , 0.73389239],
[0. , 0.37602988],
[0. , 0.50049507]])
In [9]: cfa.factor_varcovs_Out[9]:
array([[1. , 0.17385704],
[0.17385704, 1. ]])
In [10]: cfa.transform(df_features.values)
Out[10]:
array([[-0.46852166, -1.08708035],
[ 2.59025301, 1.20227783],
[-0.47215977, 2.65697245],
...,
[-1.5930886 , -0.91804114],
[ 0.19430887, 0.88174818],
[-0.27863554, -0.7695101 ]])

Requirements

  • Python 3.8 or higher
  • numpy
  • pandas
  • scipy
  • scikit-learn >= 1.6.0

Contributing

Contributions to factor_analyzer are very welcome. Please file an issue in the repository if you would like to contribute.

You can install the development requirements in a virtual environment with:

python -m pip install -e .[dev]
pre-commit install

Installation

You can install this package via pip with:

$ pip install factor_analyzer

Alternatively, you can install via conda with:

$ conda install -c ets factor_analyzer

License

GNU General Public License (>= 2)

About

A Python module to perform exploratory & confirmatory factor analyses.

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

FactorAnalyzer

Build statusCode coverageConda versionPyPI versionDocsPre-commit checks

This is a Python module to perform exploratory and factor analysis (EFA), with several optional rotations. It also includes a class to perform confirmatory factor analysis (CFA), with certain pre-defined constraints. In exploratory factor analysis, factor extraction can be performed using a variety of estimation techniques. The factor_analyzer package allows users to perform EFA using either (1) a minimum residual (MINRES) solution, (2) a maximum likelihood (ML) solution, or (3) a principal factor solution. However, CFA can only be performed using an ML solution.

Both the EFA and CFA classes within this package are fully compatible with scikit-learn. Portions of this code are ported from the excellent R library psych, and the sem package provided inspiration for the CFA class.

Please see the official documentation for additional details.

Description

Exploratory factor analysis (EFA) is a statistical technique used to identify latent relationships among sets of observed variables in a dataset. In particular, EFA seeks to model a large set of observed variables as linear combinations of some smaller set of unobserved, latent factors. The matrix of weights, or factor loadings, generated from an EFA model describes the underlying relationships between each variable and the latent factors.

Confirmatory factor analysis (CFA), a closely associated technique, is used to test an a priori hypothesis about latent relationships among sets of observed variables. In CFA, the researcher specifies the expected pattern of factor loadings (and possibly other constraints), and fits a model according to this specification.

Typically, a number of factors (K) in an EFA or CFA model is selected such that it is substantially smaller than the number of variables. The factor analysis model can be estimated using a variety of standard estimation methods, including but not limited MINRES or ML.

Factor loadings are similar to standardized regression coefficients, and variables with higher loadings on a particular factor can be interpreted as explaining a larger proportion of the variation in that factor. In the case of EFA, factor loading matrices are usually rotated after the factor analysis model is estimated in order to produce a simpler, more interpretable structure to identify which variables are loading on a particular factor.

Two common types of rotations are:

  1. The varimax rotation, which rotates the factor loading matrix so as to maximize the sum of the variance of squared loadings, while preserving the orthogonality of the loading matrix.
  2. The promax rotation, a method for oblique rotation, which builds upon the varimax rotation, but ultimately allows factors to become correlated.

This package includes a factor_analyzer module with a stand-alone FactorAnalyzer class. The class includes fit() and transform() methods that enable users to perform factor analysis and score new data using the fitted factor model. Users can also perform optional rotations on a factor loading matrix using the Rotator class.

The following rotation options are available in both FactorAnalyzer and Rotator:

  1. varimax (orthogonal rotation)
  2. promax (oblique rotation)
  3. oblimin (oblique rotation)
  4. oblimax (orthogonal rotation)
  5. quartimin (oblique rotation)
  6. quartimax (orthogonal rotation)
  7. equamax (orthogonal rotation)
  8. geomin_obl (oblique rotation)
  9. geomin_ort (orthogonal rotation)

In addition, the package includes a confirmatory_factor_analyzer module with a stand-alone ConfirmatoryFactorAnalyzer class. The class includes fit() and transform() that enable users to perform confirmatory factor analysis and score new data using the fitted model. Performing CFA requires users to specify in advance a model specification with the expected factor loading relationships. This can be done using the ModelSpecificationParser class.

Note that the ConfirmatoryFactorAnalyzer class is very experimental at this point, so use it with caution, especially if your data are highly non-normal.

Examples

Exploratory factor analysis example.

In [1]: importpandasaspd
...: fromfactor_analyzerimportFactorAnalyzerIn [2]: df_features=pd.read_csv('tests/data/test02.csv')
In [3]: fa=FactorAnalyzer(rotation=None)
In [4]: fa.fit(df_features)
Out[4]:
FactorAnalyzer(bounds=(0.005, 1), impute='median', is_corr_matrix=False,
method='minres', n_factors=3, rotation=None, rotation_kwargs={},
use_smc=True)
In [5]: fa.loadings_Out[5]:
array([[-0.12991218, 0.16398151, 0.73823491],
[ 0.03899558, 0.04658425, 0.01150343],
[ 0.34874135, 0.61452341, -0.07255666],
[ 0.45318006, 0.7192668 , -0.0754647 ],
[ 0.36688794, 0.44377343, -0.01737066],
[ 0.74141382, -0.15008235, 0.29977513],
[ 0.741675 , -0.16123009, -0.20744497],
[ 0.82910167, -0.20519428, 0.04930817],
[ 0.76041819, -0.23768727, -0.12068582],
[ 0.81533404, -0.12494695, 0.17639684]])
In [6]: fa.get_communalities()
Out[6]:
array([0.5887579 , 0.00382308, 0.50452402, 0.72841182, 0.33184336,
0.66208429, 0.61911037, 0.73194557, 0.64929612, 0.71149718])

Confirmatory factor analysis example.

In [1]: importpandasaspdIn [2]: fromfactor_analyzerimport (ConfirmatoryFactorAnalyzer,
...: ModelSpecificationParser)
In [3]: df_features=pd.read_csv('tests/data/test11.csv')
In [4]: model_dict= {"F1": ["V1", "V2", "V3", "V4"],
...: "F2": ["V5", "V6", "V7", "V8"]}
In [5]: model_spec=ModelSpecificationParser.parse_model_specification_from_dict(df_features,
...: model_dict)
In [6]: cfa=ConfirmatoryFactorAnalyzer(model_spec, disp=False)
In [7]: cfa.fit(df_features.values)
In [8]: cfa.loadings_Out[8]:
array([[0.99131285, 0. ],
[0.46074919, 0. ],
[0.3502267 , 0. ],
[0.58331488, 0. ],
[0. , 0.98621042],
[0. , 0.73389239],
[0. , 0.37602988],
[0. , 0.50049507]])
In [9]: cfa.factor_varcovs_Out[9]:
array([[1. , 0.17385704],
[0.17385704, 1. ]])
In [10]: cfa.transform(df_features.values)
Out[10]:
array([[-0.46852166, -1.08708035],
[ 2.59025301, 1.20227783],
[-0.47215977, 2.65697245],
...,
[-1.5930886 , -0.91804114],
[ 0.19430887, 0.88174818],
[-0.27863554, -0.7695101 ]])

Requirements

  • Python 3.8 or higher
  • numpy
  • pandas
  • scipy
  • scikit-learn >= 1.6.0

Contributing

Contributions to factor_analyzer are very welcome. Please file an issue in the repository if you would like to contribute.

You can install the development requirements in a virtual environment with:

python -m pip install -e .[dev]
pre-commit install

Installation

You can install this package via pip with:

$ pip install factor_analyzer

Alternatively, you can install via conda with:

$ conda install -c ets factor_analyzer

License

GNU General Public License (>= 2)

About

A Python module to perform exploratory & confirmatory factor analyses.

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

FactorAnalyzer

Build statusCode coverageConda versionPyPI versionDocsPre-commit checks

This is a Python module to perform exploratory and factor analysis (EFA), with several optional rotations. It also includes a class to perform confirmatory factor analysis (CFA), with certain pre-defined constraints. In exploratory factor analysis, factor extraction can be performed using a variety of estimation techniques. The factor_analyzer package allows users to perform EFA using either (1) a minimum residual (MINRES) solution, (2) a maximum likelihood (ML) solution, or (3) a principal factor solution. However, CFA can only be performed using an ML solution.

Both the EFA and CFA classes within this package are fully compatible with scikit-learn. Portions of this code are ported from the excellent R library psych, and the sem package provided inspiration for the CFA class.

Please see the official documentation for additional details.

Description

Exploratory factor analysis (EFA) is a statistical technique used to identify latent relationships among sets of observed variables in a dataset. In particular, EFA seeks to model a large set of observed variables as linear combinations of some smaller set of unobserved, latent factors. The matrix of weights, or factor loadings, generated from an EFA model describes the underlying relationships between each variable and the latent factors.

Confirmatory factor analysis (CFA), a closely associated technique, is used to test an a priori hypothesis about latent relationships among sets of observed variables. In CFA, the researcher specifies the expected pattern of factor loadings (and possibly other constraints), and fits a model according to this specification.

Typically, a number of factors (K) in an EFA or CFA model is selected such that it is substantially smaller than the number of variables. The factor analysis model can be estimated using a variety of standard estimation methods, including but not limited MINRES or ML.

Factor loadings are similar to standardized regression coefficients, and variables with higher loadings on a particular factor can be interpreted as explaining a larger proportion of the variation in that factor. In the case of EFA, factor loading matrices are usually rotated after the factor analysis model is estimated in order to produce a simpler, more interpretable structure to identify which variables are loading on a particular factor.

Two common types of rotations are:

  1. The varimax rotation, which rotates the factor loading matrix so as to maximize the sum of the variance of squared loadings, while preserving the orthogonality of the loading matrix.
  2. The promax rotation, a method for oblique rotation, which builds upon the varimax rotation, but ultimately allows factors to become correlated.

This package includes a factor_analyzer module with a stand-alone FactorAnalyzer class. The class includes fit() and transform() methods that enable users to perform factor analysis and score new data using the fitted factor model. Users can also perform optional rotations on a factor loading matrix using the Rotator class.

The following rotation options are available in both FactorAnalyzer and Rotator:

  1. varimax (orthogonal rotation)
  2. promax (oblique rotation)
  3. oblimin (oblique rotation)
  4. oblimax (orthogonal rotation)
  5. quartimin (oblique rotation)
  6. quartimax (orthogonal rotation)
  7. equamax (orthogonal rotation)
  8. geomin_obl (oblique rotation)
  9. geomin_ort (orthogonal rotation)

In addition, the package includes a confirmatory_factor_analyzer module with a stand-alone ConfirmatoryFactorAnalyzer class. The class includes fit() and transform() that enable users to perform confirmatory factor analysis and score new data using the fitted model. Performing CFA requires users to specify in advance a model specification with the expected factor loading relationships. This can be done using the ModelSpecificationParser class.

Note that the ConfirmatoryFactorAnalyzer class is very experimental at this point, so use it with caution, especially if your data are highly non-normal.

Examples

Exploratory factor analysis example.

In [1]: importpandasaspd
...: fromfactor_analyzerimportFactorAnalyzerIn [2]: df_features=pd.read_csv('tests/data/test02.csv')
In [3]: fa=FactorAnalyzer(rotation=None)
In [4]: fa.fit(df_features)
Out[4]:
FactorAnalyzer(bounds=(0.005, 1), impute='median', is_corr_matrix=False,
method='minres', n_factors=3, rotation=None, rotation_kwargs={},
use_smc=True)
In [5]: fa.loadings_Out[5]:
array([[-0.12991218, 0.16398151, 0.73823491],
[ 0.03899558, 0.04658425, 0.01150343],
[ 0.34874135, 0.61452341, -0.07255666],
[ 0.45318006, 0.7192668 , -0.0754647 ],
[ 0.36688794, 0.44377343, -0.01737066],
[ 0.74141382, -0.15008235, 0.29977513],
[ 0.741675 , -0.16123009, -0.20744497],
[ 0.82910167, -0.20519428, 0.04930817],
[ 0.76041819, -0.23768727, -0.12068582],
[ 0.81533404, -0.12494695, 0.17639684]])
In [6]: fa.get_communalities()
Out[6]:
array([0.5887579 , 0.00382308, 0.50452402, 0.72841182, 0.33184336,
0.66208429, 0.61911037, 0.73194557, 0.64929612, 0.71149718])

Confirmatory factor analysis example.

In [1]: importpandasaspdIn [2]: fromfactor_analyzerimport (ConfirmatoryFactorAnalyzer,
...: ModelSpecificationParser)
In [3]: df_features=pd.read_csv('tests/data/test11.csv')
In [4]: model_dict= {"F1": ["V1", "V2", "V3", "V4"],
...: "F2": ["V5", "V6", "V7", "V8"]}
In [5]: model_spec=ModelSpecificationParser.parse_model_specification_from_dict(df_features,
...: model_dict)
In [6]: cfa=ConfirmatoryFactorAnalyzer(model_spec, disp=False)
In [7]: cfa.fit(df_features.values)
In [8]: cfa.loadings_Out[8]:
array([[0.99131285, 0. ],
[0.46074919, 0. ],
[0.3502267 , 0. ],
[0.58331488, 0. ],
[0. , 0.98621042],
[0. , 0.73389239],
[0. , 0.37602988],
[0. , 0.50049507]])
In [9]: cfa.factor_varcovs_Out[9]:
array([[1. , 0.17385704],
[0.17385704, 1. ]])
In [10]: cfa.transform(df_features.values)
Out[10]:
array([[-0.46852166, -1.08708035],
[ 2.59025301, 1.20227783],
[-0.47215977, 2.65697245],
...,
[-1.5930886 , -0.91804114],
[ 0.19430887, 0.88174818],
[-0.27863554, -0.7695101 ]])

Requirements

  • Python 3.8 or higher
  • numpy
  • pandas
  • scipy
  • scikit-learn >= 1.6.0

Contributing

Contributions to factor_analyzer are very welcome. Please file an issue in the repository if you would like to contribute.

You can install the development requirements in a virtual environment with:

python -m pip install -e .[dev]
pre-commit install

Installation

You can install this package via pip with:

$ pip install factor_analyzer

Alternatively, you can install via conda with:

$ conda install -c ets factor_analyzer

License

GNU General Public License (>= 2)

About

A Python module to perform exploratory & confirmatory factor analyses.

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

FactorAnalyzer

Build statusCode coverageConda versionPyPI versionDocsPre-commit checks

This is a Python module to perform exploratory and factor analysis (EFA), with several optional rotations. It also includes a class to perform confirmatory factor analysis (CFA), with certain pre-defined constraints. In exploratory factor analysis, factor extraction can be performed using a variety of estimation techniques. The factor_analyzer package allows users to perform EFA using either (1) a minimum residual (MINRES) solution, (2) a maximum likelihood (ML) solution, or (3) a principal factor solution. However, CFA can only be performed using an ML solution.

Both the EFA and CFA classes within this package are fully compatible with scikit-learn. Portions of this code are ported from the excellent R library psych, and the sem package provided inspiration for the CFA class.

Please see the official documentation for additional details.

Description

Exploratory factor analysis (EFA) is a statistical technique used to identify latent relationships among sets of observed variables in a dataset. In particular, EFA seeks to model a large set of observed variables as linear combinations of some smaller set of unobserved, latent factors. The matrix of weights, or factor loadings, generated from an EFA model describes the underlying relationships between each variable and the latent factors.

Confirmatory factor analysis (CFA), a closely associated technique, is used to test an a priori hypothesis about latent relationships among sets of observed variables. In CFA, the researcher specifies the expected pattern of factor loadings (and possibly other constraints), and fits a model according to this specification.

Typically, a number of factors (K) in an EFA or CFA model is selected such that it is substantially smaller than the number of variables. The factor analysis model can be estimated using a variety of standard estimation methods, including but not limited MINRES or ML.

Factor loadings are similar to standardized regression coefficients, and variables with higher loadings on a particular factor can be interpreted as explaining a larger proportion of the variation in that factor. In the case of EFA, factor loading matrices are usually rotated after the factor analysis model is estimated in order to produce a simpler, more interpretable structure to identify which variables are loading on a particular factor.

Two common types of rotations are:

  1. The varimax rotation, which rotates the factor loading matrix so as to maximize the sum of the variance of squared loadings, while preserving the orthogonality of the loading matrix.
  2. The promax rotation, a method for oblique rotation, which builds upon the varimax rotation, but ultimately allows factors to become correlated.

This package includes a factor_analyzer module with a stand-alone FactorAnalyzer class. The class includes fit() and transform() methods that enable users to perform factor analysis and score new data using the fitted factor model. Users can also perform optional rotations on a factor loading matrix using the Rotator class.

The following rotation options are available in both FactorAnalyzer and Rotator:

  1. varimax (orthogonal rotation)
  2. promax (oblique rotation)
  3. oblimin (oblique rotation)
  4. oblimax (orthogonal rotation)
  5. quartimin (oblique rotation)
  6. quartimax (orthogonal rotation)
  7. equamax (orthogonal rotation)
  8. geomin_obl (oblique rotation)
  9. geomin_ort (orthogonal rotation)

In addition, the package includes a confirmatory_factor_analyzer module with a stand-alone ConfirmatoryFactorAnalyzer class. The class includes fit() and transform() that enable users to perform confirmatory factor analysis and score new data using the fitted model. Performing CFA requires users to specify in advance a model specification with the expected factor loading relationships. This can be done using the ModelSpecificationParser class.

Note that the ConfirmatoryFactorAnalyzer class is very experimental at this point, so use it with caution, especially if your data are highly non-normal.

Examples

Exploratory factor analysis example.

In [1]: importpandasaspd
...: fromfactor_analyzerimportFactorAnalyzerIn [2]: df_features=pd.read_csv('tests/data/test02.csv')
In [3]: fa=FactorAnalyzer(rotation=None)
In [4]: fa.fit(df_features)
Out[4]:
FactorAnalyzer(bounds=(0.005, 1), impute='median', is_corr_matrix=False,
method='minres', n_factors=3, rotation=None, rotation_kwargs={},
use_smc=True)
In [5]: fa.loadings_Out[5]:
array([[-0.12991218, 0.16398151, 0.73823491],
[ 0.03899558, 0.04658425, 0.01150343],
[ 0.34874135, 0.61452341, -0.07255666],
[ 0.45318006, 0.7192668 , -0.0754647 ],
[ 0.36688794, 0.44377343, -0.01737066],
[ 0.74141382, -0.15008235, 0.29977513],
[ 0.741675 , -0.16123009, -0.20744497],
[ 0.82910167, -0.20519428, 0.04930817],
[ 0.76041819, -0.23768727, -0.12068582],
[ 0.81533404, -0.12494695, 0.17639684]])
In [6]: fa.get_communalities()
Out[6]:
array([0.5887579 , 0.00382308, 0.50452402, 0.72841182, 0.33184336,
0.66208429, 0.61911037, 0.73194557, 0.64929612, 0.71149718])

Confirmatory factor analysis example.

In [1]: importpandasaspdIn [2]: fromfactor_analyzerimport (ConfirmatoryFactorAnalyzer,
...: ModelSpecificationParser)
In [3]: df_features=pd.read_csv('tests/data/test11.csv')
In [4]: model_dict= {"F1": ["V1", "V2", "V3", "V4"],
...: "F2": ["V5", "V6", "V7", "V8"]}
In [5]: model_spec=ModelSpecificationParser.parse_model_specification_from_dict(df_features,
...: model_dict)
In [6]: cfa=ConfirmatoryFactorAnalyzer(model_spec, disp=False)
In [7]: cfa.fit(df_features.values)
In [8]: cfa.loadings_Out[8]:
array([[0.99131285, 0. ],
[0.46074919, 0. ],
[0.3502267 , 0. ],
[0.58331488, 0. ],
[0. , 0.98621042],
[0. , 0.73389239],
[0. , 0.37602988],
[0. , 0.50049507]])
In [9]: cfa.factor_varcovs_Out[9]:
array([[1. , 0.17385704],
[0.17385704, 1. ]])
In [10]: cfa.transform(df_features.values)
Out[10]:
array([[-0.46852166, -1.08708035],
[ 2.59025301, 1.20227783],
[-0.47215977, 2.65697245],
...,
[-1.5930886 , -0.91804114],
[ 0.19430887, 0.88174818],
[-0.27863554, -0.7695101 ]])

Requirements

  • Python 3.8 or higher
  • numpy
  • pandas
  • scipy
  • scikit-learn >= 1.6.0

Contributing

Contributions to factor_analyzer are very welcome. Please file an issue in the repository if you would like to contribute.

You can install the development requirements in a virtual environment with:

python -m pip install -e .[dev]
pre-commit install

Installation

You can install this package via pip with:

$ pip install factor_analyzer

Alternatively, you can install via conda with:

$ conda install -c ets factor_analyzer

License

GNU General Public License (>= 2)

About

A Python module to perform exploratory & confirmatory factor analyses.

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages