
    0Ph;                         d Z ddlZddlmZmZ ddlmZmZ ddlZ	ddl
mZ ddlmZmZmZmZ ddlmZ dd	lmZ dd
lmZmZ ddlmZmZmZ ddlmZmZ  G d deee          ZddZ dS )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)fast_logdetrandomized_svdsquared_norm)check_is_fittedvalidate_datac                   j   e Zd ZU dZ eeddd          dg eeddd          gdg eeddd          gd	dg ed
dh          g eeddd          g eddh          dgdgd	Ze	e
d<   	 d!ddddd
dddddZ ed          d!d            Zd Zd Zd Zd Zd!dZd"dZed              ZdS )#FactorAnalysisaR  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                    || _         || _        || _        || _        || _        || _        || _        |	| _        || _        d S N)	r"   r$   r#   r%   r'   r&   r(   r!   r)   )
selfr"   r#   r$   r%   r&   r'   r(   r)   r!   s
             f/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sklearn/decomposition/_factor_analysis.py__init__zFactorAnalysis.__init__   sK     )	 $#6 ,(     )prefer_skip_nested_validationc                      t           | j        t          j        d          }|j        \  }} j        |t          j        |d           _        | j        z  }t          |          }|t          dt          j
        z            z  z   }t          j        |d          } j        t          j        ||j                  }nWt           j                  |k    r&t!          dt           j                  |fz            t          j         j                  }g }	t          j         }
d	} j        d
k    rfd}nt)           j                   fd}t-           j                  D ]/}t          j        |          |z   } ||||z  z            \  }}}|dz  }t          j        t          j        |dz
  d                    ddt          j        f         |z  }~||z  }|t          j        t          j	        |                    z   }||t          j        t          j	        |                    z   z  }|| dz  z  }|	                    |           ||
z
   j        k     r nM|}
t          j        |t          j        |dz  d          z
  |          }1t;          j        dt>                     | _          j!         "                    |           _         | _#        |	 _$        |dz    _%         S )aT  Fit 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       @)r4   zInoise_variance_init dimension does not with number of features : %d != %dg-q=r   c                     t          j        | dd          \  }}}|d          |d          t          |d                    fS )NF)full_matricescheck_finite)r   svdr   )X_sVtr"   s       r/   my_svdz"FactorAnalysis.fit.<locals>.my_svd   sU    !:au5QQQ1bm|m$}}% <==!122 r1   c                     t          | j                  \  }}}||t          |           t          |          z
  fS )N)r!   n_iter)r   r(   r   )r=   r>   r?   r@   r"   r!   r.   s       r/   rA   z"FactorAnalysis.fit.<locals>.my_svd
  sL    ) !-.	  1b "l1ooQ???r1   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&   onesr4   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llconstrK   psiloglikeold_llSMALLrA   isqrt_psir?   r@   	unexp_varWllr"   r!   s   `                   @@r/   fitzFactorAnalysis.fit   s?   " !$)2:t
 
 
 !"	:(%LWQQ'''
	TZ Ys3;///,>fQQ#+'*AG444CC4+,,
:: 94344jAB  
 (4344C& ?h&&      .d.?@@L@ @ @ @ @ @ @ t}%% 	 	Aws||e+H%va8e+;&<==Ar9!GA
1s7C0011!!!RZ-@2EAMA 26"&)),,,B)bfRVC[[1111B9*s""BNN2Vtx''F*S26!Q$Q#7#7#77??CCM; #	   =$#||AD"1ur1   c                    t          |            t          | |d          }t          j        t	          | j                            }|| j        z
  }| j        | j        z  }t          j	        |t          j
        || j        j                  z             }t          j
        ||j                  }t          j
        ||          }|S )a  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   rE   eyerM   rX   rI   rZ   r   invdotT)r.   r=   IhX_transformedWpsicov_ztmps          r/   	transformzFactorAnalysis.transform7  s      	$///VC())**DJ$"66
2tT-=-? @ @@AAf]DF++sE**r1   c                     t          |            t          j        | j        j        | j                  }|j        ddt          |          dz   xx         | j        z  cc<   |S )a  Compute 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   rE   rq   rX   rr   flatrM   rZ   )r.   covs     r/   get_covariancezFactorAnalysis.get_covarianceU  sb     	fT%')9::CHHqL!!!T%99!!!
r1   c                    t          |            | j        j        d         }| j        dk    rt	          j        d| j        z            S | j        |k    r&t          j        | 	                                          S | j        }t	          j
        || j        z  |j                  }|j        ddt          |          dz   xx         dz  cc<   t	          j
        |j        t	          j
        t          j        |          |                    }|| j        ddt          j        f         z  }|| j        t          j        ddf          z  }|j        ddt          |          dz   xx         d| j        z  z  cc<   |S )zCompute data precision matrix with the FactorAnalysis model.

        Returns
        -------
        precision : ndarray of shape (n_features, n_features)
            Estimated precision of data.
        r   r   rD   N)r   rX   rG   r"   rE   diagrZ   r   rp   r|   rq   rr   rz   rM   rS   )r.   r_   rX   	precisions       r/   get_precisionzFactorAnalysis.get_precisione  so    	%+A.
 !!73!55666
**:d1133444 &F;)=={}MM	,,#i..1,,---4---F;="&I1F1F*T*TUU	T)!!!RZ-88	d*2:qqq=999	,,#i..1,,---t7K1KK---r1   c                 f   t          |            t          | |d          }|| j        z
  }|                                 }|j        d         }d|t          j        ||          z                      d          z  }|d|t          dt
          j	        z            z  t          |          z
  z  z  }|S )a4  Compute 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.
        Frm   r   g      r6   g      ?r8   )r   r   rI   r   rG   rE   rq   rT   r   rJ   r   )r.   r=   Xrr   r_   log_likes         r/   score_sampleszFactorAnalysis.score_samples  s     	$///^&&((	WQZ
2I!6!67<<!<DDDC:C"%K(8(88;y;Q;QQRRr1   c                 P    t          j        |                     |                    S )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.
        )rE   rH   r   )r.   r=   r]   s      r/   scorezFactorAnalysis.score  s"      wt))!,,---r1   ư>c                 T    t          |j        | j        |          d| j                 S )z$Rotate the factor analysis solution.)methodr#   N)_ortho_rotationrr   r)   r"   )r.   
componentsr"   r#   s       r/   rY   zFactorAnalysis._rotate  s/     z|DMsKKKd
 	
r1   c                 &    | j         j        d         S )z&Number of transformed output features.r   )rX   rG   )r.   s    r/   _n_features_outzFactorAnalysis._n_features_out  s     %a((r1   r-   )Nr   )__name__
__module____qualname____doc__r   r   r   r   r*   dict__annotations__r0   r   rk   rx   r|   r   r   r   rY   propertyr    r1   r/   r   r   '   s        | |~ "(AtFCCCTJsD8889Xh4???@ ,d3!z<":;;<#8HafEEEFZK 8994@'(
$ 
$D 
 
 
 !  ! ! ! ! !0 \555j j j 65jX  <     8  ,. . . .$
 
 
 
 ) ) X) ) )r1   r   r   r   d   c                 D   | j         \  }}t          j        |          }d}t          |          D ]}t          j        | |          }	|dk    r2|	t          j        |	dz                      d          |z            z  }
n|dk    rd}
t          j                            t          j        | j	        |	dz  |
z
                      \  }}}t          j        ||          }t          j        |          }|dk    r||d|z   z  k     r n|}t          j        | |          j	        S )zReturn rotated components.r   r   r   r6   r    r+   r   )
rG   rE   ro   rQ   rq   	transposerT   r   r<   rr   )r   r   r#   r%   nrowncolrotation_matrixrK   r>   comp_rotrw   ur?   vvar_news                  r/   r   r     s   !JD$fTllO
C8__  6*o66YR\8Q;*;*;*;*C*Cd*JKKKCC{""C)--z|Xq[35F G GHH1a&A,,&))!88#S/11E6*o..00r1   )r   r   r   )!r   rV   mathr   r   numbersr   r   numpyrE   scipyr   baser	   r
   r   r   
exceptionsr   utilsr   utils._param_validationr   r   utils.extmathr   r   r   utils.validationr   r   r   r   r   r1   r/   <module>r      so   $          " " " " " " " "                      , + + + + + & & & & & & : : : : : : : : E E E E E E E E E E = = = = = = = =L) L) L) L) L)46F L) L) L)^1 1 1 1 1 1r1   