
    -i;                         S r SSKrSSKJrJr  SSKJrJr  SSKr	SSK
Jr  SSKJrJrJrJr  SSKJr  SS	KJr  SS
KJrJr  SSKJrJrJr  SSKJrJr   " S S\\\5      rSS jr g)a  Factor Analysis.

A latent linear variable model.

FactorAnalysis is similar to probabilistic PCA implemented by PCA.score
While PCA assumes Gaussian noise with the same variance for each
feature, the FactorAnalysis model assumes different variances for
each of them.

This implementation is based on David Barber's Book,
Bayesian Reasoning and Machine Learning,
http://www.cs.ucl.ac.uk/staff/d.barber/brml,
Algorithm 21.1
    N)logsqrt)IntegralReal)linalg   )BaseEstimatorClassNamePrefixFeaturesOutMixinTransformerMixin_fit_context)ConvergenceWarning)check_random_state)Interval
StrOptions)_randomized_svdfast_logdetsquared_norm)check_is_fittedvalidate_datac                   &   \ rS rSr% Sr\" \SSSS9S/\" \SSSS9/S/\" \S	SSS9/S
S/\" SS15      /\" \SSSS9/\" SS15      S/S/S.	r	\
\S'    S"SSSSSSSSS.S jjr\" SS9S"S j5       rS rS rS rS rS"S jrS#S jr\S  5       rS!rg)$FactorAnalysis'   a  Factor Analysis (FA).

A simple linear generative model with Gaussian latent variables.

The observations are assumed to be caused by a linear transformation of
lower dimensional latent factors and added Gaussian noise.
Without loss of generality the factors are distributed according to a
Gaussian with zero mean and unit covariance. The noise is also zero mean
and has an arbitrary diagonal covariance matrix.

If we would restrict the model further, by assuming that the Gaussian
noise is even isotropic (all diagonal entries are the same) we would obtain
:class:`PCA`.

FactorAnalysis performs a maximum likelihood estimate of the so-called
`loading` matrix, the transformation of the latent variables to the
observed ones, using SVD based approach.

Read more in the :ref:`User Guide <FA>`.

.. versionadded:: 0.13

Parameters
----------
n_components : int, default=None
    Dimensionality of latent space, the number of components
    of ``X`` that are obtained after ``transform``.
    If None, n_components is set to the number of features.

tol : float, default=1e-2
    Stopping tolerance for log-likelihood increase.

copy : bool, default=True
    Whether to make a copy of X. If ``False``, the input X gets overwritten
    during fitting.

max_iter : int, default=1000
    Maximum number of iterations.

noise_variance_init : array-like of shape (n_features,), default=None
    The initial guess of the noise variance for each feature.
    If None, it defaults to np.ones(n_features).

svd_method : {'lapack', 'randomized'}, default='randomized'
    Which SVD method to use. If 'lapack' use standard SVD from
    scipy.linalg, if 'randomized' use fast ``randomized_svd`` function.
    Defaults to 'randomized'. For most applications 'randomized' will
    be sufficiently precise while providing significant speed gains.
    Accuracy can also be improved by setting higher values for
    `iterated_power`. If this is not sufficient, for maximum precision
    you should choose 'lapack'.

iterated_power : int, default=3
    Number of iterations for the power method. 3 by default. Only used
    if ``svd_method`` equals 'randomized'.

rotation : {'varimax', 'quartimax'}, default=None
    If not None, apply the indicated rotation. Currently, varimax and
    quartimax are implemented. See
    `"The varimax criterion for analytic rotation in factor analysis"
    <https://link.springer.com/article/10.1007%2FBF02289233>`_
    H. F. Kaiser, 1958.

    .. versionadded:: 0.24

random_state : int or RandomState instance, default=0
    Only used when ``svd_method`` equals 'randomized'. Pass an int for
    reproducible results across multiple function calls.
    See :term:`Glossary <random_state>`.

Attributes
----------
components_ : ndarray of shape (n_components, n_features)
    Components with maximum variance.

loglike_ : list of shape (n_iterations,)
    The log likelihood at each iteration.

noise_variance_ : ndarray of shape (n_features,)
    The estimated noise variance for each feature.

n_iter_ : int
    Number of iterations run.

mean_ : ndarray of shape (n_features,)
    Per-feature empirical mean, estimated from the training set.

n_features_in_ : int
    Number of features seen during :term:`fit`.

    .. versionadded:: 0.24

feature_names_in_ : ndarray of shape (`n_features_in_`,)
    Names of features seen during :term:`fit`. Defined only when `X`
    has feature names that are all strings.

    .. versionadded:: 1.0

See Also
--------
PCA: Principal component analysis is also a latent linear variable model
    which however assumes equal noise variance for each feature.
    This extra assumption makes probabilistic PCA faster as it can be
    computed in closed form.
FastICA: Independent component analysis, a latent variable model with
    non-Gaussian latent variables.

References
----------
- David Barber, Bayesian Reasoning and Machine Learning,
  Algorithm 21.1.

- Christopher M. Bishop: Pattern Recognition and Machine Learning,
  Chapter 12.2.4.

Examples
--------
>>> from sklearn.datasets import load_digits
>>> from sklearn.decomposition import FactorAnalysis
>>> X, _ = load_digits(return_X_y=True)
>>> transformer = FactorAnalysis(n_components=7, random_state=0)
>>> X_transformed = transformer.fit_transform(X)
>>> X_transformed.shape
(1797, 7)
r   Nleft)closed        boolean   z
array-like
randomizedlapackvarimax	quartimaxrandom_state)	n_componentstolcopymax_iternoise_variance_init
svd_methoditerated_powerrotationr"   _parameter_constraintsg{Gz?Ti     )r$   r%   r&   r'   r(   r)   r*   r"   c                p    Xl         X0l        X l        X@l        X`l        XPl        Xpl        Xl        Xl        g N)	r#   r%   r$   r&   r(   r'   r)   r"   r*   )
selfr#   r$   r%   r&   r'   r(   r)   r*   r"   s
             Y/var/www/html/venv/lib/python3.13/site-packages/sklearn/decomposition/_factor_analysis.py__init__FactorAnalysis.__init__   s5     )	 $#6 ,(     )prefer_skip_nested_validationc           	      t  ^ ^^ [        T UT R                  [        R                  SS9nUR                  u  p4T R
                  mTc  Um[        R                  " USS9T l        UT R                  -  n[        U5      nU[        S[        R                  -  5      -  T-   n[        R                  " USS9nT R                  c  [        R                  " XAR                  S9nO\[        T R                  5      U:w  a#  [!        S[        T R                  5      U4-  5      e[        R"                  " T R                  5      n/ n	[        R$                  * n
S	nT R&                  S
:X  a  U4S jnO[)        T R*                  5      mUUU 4S jn[-        T R.                  5       GH=  n[        R                  " U5      U-   nU" XU-  -  5      u  nnnUS-  n[        R                  " [        R0                  " US-
  S5      5      SS2[        R2                  4   U-  nAUU-  nU[        R4                  " [        R                  " U5      5      -   nUU[        R4                  " [        R                  " U5      5      -   -  nUU* S-  -  nU	R7                  U5        UU
-
  T R8                  :  a    ORUn
[        R0                  " U[        R4                  " US-  SS9-
  U5      nGM@     [:        R<                  " S[>        5        WT l         T RB                  b  T RE                  U5      T l         UT l#        U	T l$        WS-   T l%        T $ )zFit the FactorAnalysis model to X using SVD based approach.

Parameters
----------
X : array-like of shape (n_samples, n_features)
    Training data.

y : Ignored
    Ignored parameter.

Returns
-------
self : object
    FactorAnalysis class instance.
T)r%   dtypeforce_writeableNr   axis       @)r6   zInoise_variance_init dimension does not with number of features : %d != %dg-q=r   c                 d   > [         R                  " U SSS9u  pnUS T US T [        UTS  5      4$ )NF)full_matricescheck_finite)r   svdr   )X_sVtr#   s       r0   my_svd"FactorAnalysis.fit.<locals>.my_svd   sF    !::au5Qbm|$}% <=!12 r3   c                 h   > [        U TTTR                  S9u  pnX#[        U 5      [        U5      -
  4$ )N)r"   n_iter)r   r)   r   )r?   r@   rA   rB   r#   r"   r/   s       r0   rC   rD   
  s=    * !-..	b l1oQ???r3   r         ?r   zUFactorAnalysis did not converge. You might want to increase the number of iterations.r   )&r   r%   npfloat64shaper#   meanmean_r   r   pivarr'   onesr6   len
ValueErrorarrayinfr(   r   r"   ranger&   maximumnewaxissumappendr$   warningswarnr   components_r*   _rotatenoise_variance_loglike_n_iter_)r/   r?   y	n_samples
n_featuresnsqrtllconstrN   psiloglikeold_llSMALLrC   isqrt_psirA   rB   	unexp_varWllr#   r"   s   `                   @@r0   fitFactorAnalysis.fit   s   " !$))2::t
 !"	((%LWWQQ'
	TZZ Ys3;//,>ffQQ##+''*GG4C4++,
: 94334jAB 
 ((4334C&& ??h& .d.?.?@L@ t}}%Awws|e+H%ae+;&<=Ar9!GA

1s7C01!RZZ-@2EAMA 266"&&),,B)bffRVVC[111B9*s""BNN2Vtxx'F**S266!Q$Q#77?C' &* MM9 #	 ==$#||AD"1ur3   c                    [        U 5        [        XSS9n[        R                  " [	        U R
                  5      5      nXR                  -
  nU R
                  U R                  -  n[        R                  " U[        R                  " X@R
                  R                  5      -   5      n[        R                  " X4R                  5      n[        R                  " Xe5      nU$ )aN  Apply dimensionality reduction to X using the model.

Compute the expected mean of the latent variables.
See Barber, 21.2.33 (or Bishop, 12.66).

Parameters
----------
X : array-like of shape (n_samples, n_features)
    Training data.

Returns
-------
X_new : ndarray of shape (n_samples, n_components)
    The latent variables of X.
Freset)r   r   rH   eyerP   r[   rL   r]   r   invdotT)r/   r?   IhX_transformedWpsicov_ztmps          r0   	transformFactorAnalysis.transform7  s      	$/VVC(()*JJ$"6"66

2t-=-=-?-? @@Aff]FF+s*r3   c                     [        U 5        [        R                  " U R                  R                  U R                  5      nUR
                  SS[        U5      S-   2==   U R                  -  ss'   U$ )zCompute data covariance with the FactorAnalysis model.

``cov = components_.T * components_ + diag(noise_variance)``

Returns
-------
cov : ndarray of shape (n_features, n_features)
    Estimated covariance of data.
Nr   )r   rH   ru   r[   rv   flatrP   r]   )r/   covs     r0   get_covarianceFactorAnalysis.get_covarianceU  sY     	ffT%%'')9)9:CHqL!T%9%99!
r3   c                 b   [        U 5        U R                  R                  S   nU R                  S:X  a#  [        R
                  " SU R                  -  5      $ U R                  U:X  a$  [        R                  " U R                  5       5      $ U R                  n[        R                  " X R                  -  UR                  5      nUR                  SS[        U5      S-   2==   S-  ss'   [        R                  " UR                  [        R                  " [        R                  " U5      U5      5      nX0R                  SS2[        R                  4   -  nX0R                  [        R                  SS24   * -  nUR                  SS[        U5      S-   2==   SU R                  -  -  ss'   U$ )zCompute data precision matrix with the FactorAnalysis model.

Returns
-------
precision : ndarray of shape (n_features, n_features)
    Estimated precision of data.
r   r   rG   N)r   r[   rJ   r#   rH   diagr]   r   rt   r   ru   rv   r   rP   rV   )r/   rb   r[   	precisions       r0   get_precisionFactorAnalysis.get_precisione  sT    	%%++A.
 !773!5!5566
*::d11344 &&FF;)=)=={}}M	,#i.1,,-4-FF;=="&&I1F*TU	))!RZZ-88	**2::q=999	,#i.1,,-t7K7K1KK-r3   c                 >   [        U 5        [        XSS9nXR                  -
  nU R                  5       nUR                  S   nSU[
        R                  " X#5      -  R                  SS9-  nUSU[        S[
        R                  -  5      -  [        U5      -
  -  -  nU$ )zCompute the log-likelihood of each sample.

Parameters
----------
X : ndarray of shape (n_samples, n_features)
    The data.

Returns
-------
ll : ndarray of shape (n_samples,)
    Log-likelihood of each sample under the current model.
Frq   r   g      r8   g      ?r:   )r   r   rL   r   rJ   rH   ru   rW   r   rM   r   )r/   r?   Xrr   rb   log_likes         r0   score_samplesFactorAnalysis.score_samples  s     	$/^&&(	WWQZ
2!67<<!<DDC:C"%%K(88;y;QQRRr3   c                 L    [         R                  " U R                  U5      5      $ )a  Compute the average log-likelihood of the samples.

Parameters
----------
X : ndarray of shape (n_samples, n_features)
    The data.

y : Ignored
    Ignored parameter.

Returns
-------
ll : float
    Average log-likelihood of the samples under the current model.
)rH   rK   r   )r/   r?   r`   s      r0   scoreFactorAnalysis.score  s      wwt))!,--r3   c                 Z    [        UR                  U R                  US9SU R                   $ )z$Rotate the factor analysis solution.)methodr$   N)_ortho_rotationrv   r*   r#   )r/   
componentsr#   r$   s       r0   r\   FactorAnalysis._rotate  s-     z||DMMsKd
 	
r3   c                 4    U R                   R                  S   $ )z&Number of transformed output features.r   )r[   rJ   )r/   s    r0   _n_features_outFactorAnalysis._n_features_out  s     %%a((r3   )r[   r%   r)   r^   r&   rL   r#   r_   r]   r'   r"   r*   r(   r$   r.   )Nư>)__name__
__module____qualname____firstlineno____doc__r   r   r   r   r+   dict__annotations__r1   r   rn   r|   r   r   r   r   r\   propertyr   __static_attributes__ r3   r0   r   r   '   s   |~ "(AtFCTJsD89h4?@ ,d3!<":;<#HafEFK 894@'(
$D 
 !  !0 5j 6jX< 8,.$
 ) )r3   r   c                 d   U R                   u  pE[        R                  " U5      nSn[        U5       H  n[        R                  " X5      n	US:X  a-  U	[        R
                  " U	S-  R                  SS9U-  5      -  n
OUS:X  a  Sn
[        R                  R                  [        R                  " U R                  U	S-  W
-
  5      5      u  pn[        R                  " X5      n[        R                  " U5      nUS:w  a  XSU-   -  :  a    OUnM     [        R                  " X5      R                  $ )zReturn rotated components.r   r    r   r8   r!   r,   r   )
rJ   rH   rs   rT   ru   	transposerW   r   r>   rv   )r   r   r$   r&   nrowncolrotation_matrixrN   r@   comp_rotr{   urA   vvar_news                  r0   r   r     s    !!JDffTlO
C8_66*6YR\\8Q;*;*;*;*Cd*JKKC{"C))--z||Xq[35F GHa&&,&&)!8S/1  66*.000r3   )r    r   d   )!r   rY   mathr   r   numbersr   r   numpyrH   scipyr   baser	   r
   r   r   
exceptionsr   utilsr   utils._param_validationr   r   utils.extmathr   r   r   utils.validationr   r   r   r   r   r3   r0   <module>r      sS   $   "    , & : F F =L)46F L)^1r3   