
    -i2@                         S r SSKJr  SSKrSSKJrJr  SSKJ	r	  SSK
Jr  SSKJr  SS	KJr  SS
KJrJr  SSKJr  SSKJr   " S S\5      rg)z*Incremental Principal Components Analysis.    )IntegralN)linalgsparse)metadata_routing   )_fit_context)gen_batches)Interval)_incremental_mean_and_varsvd_flip)validate_data   )_BasePCAc            
          ^  \ rS rSr% SrS\R                  0r\" \	SSSS9S/S/S/\" \	SSSS9S/S	.r
\\S
'   SSSSS.S jjr\" SS9SS j5       r\" SS9SS j5       rU 4S jrU 4S jrSrU =r$ )IncrementalPCA   ah  Incremental principal components analysis (IPCA).

Linear dimensionality reduction using Singular Value Decomposition of
the data, keeping only the most significant singular vectors to
project the data to a lower dimensional space. The input data is centered
but not scaled for each feature before applying the SVD.

Depending on the size of the input data, this algorithm can be much more
memory efficient than a PCA, and allows sparse input.

This algorithm has constant memory complexity, on the order
of ``batch_size * n_features``, enabling use of np.memmap files without
loading the entire file into memory. For sparse matrices, the input
is converted to dense in batches (in order to be able to subtract the
mean) which avoids storing the entire dense matrix at any one time.

The computational overhead of each SVD is
``O(batch_size * n_features ** 2)``, but only 2 * batch_size samples
remain in memory at a time. There will be ``n_samples / batch_size`` SVD
computations to get the principal components, versus 1 large SVD of
complexity ``O(n_samples * n_features ** 2)`` for PCA.

For a usage example, see
:ref:`sphx_glr_auto_examples_decomposition_plot_incremental_pca.py`.

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

.. versionadded:: 0.16

Parameters
----------
n_components : int, default=None
    Number of components to keep. If ``n_components`` is ``None``,
    then ``n_components`` is set to ``min(n_samples, n_features)``.

whiten : bool, default=False
    When True (False by default) the ``components_`` vectors are divided
    by ``n_samples`` times ``components_`` to ensure uncorrelated outputs
    with unit component-wise variances.

    Whitening will remove some information from the transformed signal
    (the relative variance scales of the components) but can sometimes
    improve the predictive accuracy of the downstream estimators by
    making data respect some hard-wired assumptions.

copy : bool, default=True
    If False, X will be overwritten. ``copy=False`` can be used to
    save memory but is unsafe for general use.

batch_size : int, default=None
    The number of samples to use for each batch. Only used when calling
    ``fit``. If ``batch_size`` is ``None``, then ``batch_size``
    is inferred from the data and set to ``5 * n_features``, to provide a
    balance between approximation accuracy and memory consumption.

Attributes
----------
components_ : ndarray of shape (n_components, n_features)
    Principal axes in feature space, representing the directions of
    maximum variance in the data. Equivalently, the right singular
    vectors of the centered input data, parallel to its eigenvectors.
    The components are sorted by decreasing ``explained_variance_``.

explained_variance_ : ndarray of shape (n_components,)
    Variance explained by each of the selected components.

explained_variance_ratio_ : ndarray of shape (n_components,)
    Percentage of variance explained by each of the selected components.
    If all components are stored, the sum of explained variances is equal
    to 1.0.

singular_values_ : ndarray of shape (n_components,)
    The singular values corresponding to each of the selected components.
    The singular values are equal to the 2-norms of the ``n_components``
    variables in the lower-dimensional space.

mean_ : ndarray of shape (n_features,)
    Per-feature empirical mean, aggregate over calls to ``partial_fit``.

var_ : ndarray of shape (n_features,)
    Per-feature empirical variance, aggregate over calls to
    ``partial_fit``.

noise_variance_ : float
    The estimated noise covariance following the Probabilistic PCA model
    from Tipping and Bishop 1999. See "Pattern Recognition and
    Machine Learning" by C. Bishop, 12.2.1 p. 574 or
    http://www.miketipping.com/papers/met-mppca.pdf.

n_components_ : int
    The estimated number of components. Relevant when
    ``n_components=None``.

n_samples_seen_ : int
    The number of samples processed by the estimator. Will be reset on
    new calls to fit, but increments across ``partial_fit`` calls.

batch_size_ : int
    Inferred batch size from ``batch_size``.

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 (PCA).
KernelPCA : Kernel Principal component analysis (KPCA).
SparsePCA : Sparse Principal Components Analysis (SparsePCA).
TruncatedSVD : Dimensionality reduction using truncated SVD.

Notes
-----
Implements the incremental PCA model from:
*D. Ross, J. Lim, R. Lin, M. Yang, Incremental Learning for Robust Visual
Tracking, International Journal of Computer Vision, Volume 77, Issue 1-3,
pp. 125-141, May 2008.*
See https://www.cs.toronto.edu/~dross/ivt/RossLimLinYang_ijcv.pdf

This model is an extension of the Sequential Karhunen-Loeve Transform from:
:doi:`A. Levy and M. Lindenbaum, Sequential Karhunen-Loeve Basis Extraction and
its Application to Images, IEEE Transactions on Image Processing, Volume 9,
Number 8, pp. 1371-1374, August 2000. <10.1109/83.855432>`

We have specifically abstained from an optimization used by authors of both
papers, a QR decomposition used in specific situations to reduce the
algorithmic complexity of the SVD. The source for this technique is
*Matrix Computations, Third Edition, G. Holub and C. Van Loan, Chapter 5,
section 5.4.4, pp 252-253.*. This technique has been omitted because it is
advantageous only when decomposing a matrix with ``n_samples`` (rows)
>= 5/3 * ``n_features`` (columns), and hurts the readability of the
implemented algorithm. This would be a good opportunity for future
optimization, if it is deemed necessary.

References
----------
D. Ross, J. Lim, R. Lin, M. Yang. Incremental Learning for Robust Visual
Tracking, International Journal of Computer Vision, Volume 77,
Issue 1-3, pp. 125-141, May 2008.

G. Golub and C. Van Loan. Matrix Computations, Third Edition, Chapter 5,
Section 5.4.4, pp. 252-253.

Examples
--------
>>> from sklearn.datasets import load_digits
>>> from sklearn.decomposition import IncrementalPCA
>>> from scipy import sparse
>>> X, _ = load_digits(return_X_y=True)
>>> transformer = IncrementalPCA(n_components=7, batch_size=200)
>>> # either partially fit on smaller batches of data
>>> transformer.partial_fit(X[:100, :])
IncrementalPCA(batch_size=200, n_components=7)
>>> # or let the fit function itself divide the data into batches
>>> X_sparse = sparse.csr_matrix(X)
>>> X_transformed = transformer.fit_transform(X_sparse)
>>> X_transformed.shape
(1797, 7)
check_inputr   Nleft)closedbooleann_componentswhitencopy
batch_size_parameter_constraintsFT)r   r   r   c                4    Xl         X l        X0l        X@l        g Nr   )selfr   r   r   r   s        Y/var/www/html/venv/lib/python3.13/site-packages/sklearn/decomposition/_incremental_pca.py__init__IncrementalPCA.__init__   s    (	$    )prefer_skip_nested_validationc           	      .   SU l         SU l        SU l        SU l        SU l        SU l        SU l        SU l        [        U U/ SQU R                  [        R                  [        R                  /SS9nUR                  u  p4U R                  c  SU-  U l        OU R                  U l        [!        X0R                  U R"                  =(       d    SS9 HB  nX   n[$        R&                  " U5      (       a  UR)                  5       nU R+                  US	S
9  MD     U $ )a  Fit the model with X, using minibatches of size batch_size.

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
    Training data, where `n_samples` is the number of samples and
    `n_features` is the number of features.

y : Ignored
    Not used, present for API consistency by convention.

Returns
-------
self : object
    Returns the instance itself.
Nr           )csrcsclilT)accept_sparser   dtypeforce_writeable   min_batch_sizeF)r   )components_n_samples_seen_mean_var_singular_values_explained_variance_explained_variance_ratio_noise_variance_r   r   npfloat64float32shaper   batch_size_r	   r   r   issparsetoarraypartial_fit)r   Xy	n_samples
n_featuresbatchX_batchs          r    fitIncrementalPCA.fit   s   $   
	 $#' )-&#/::rzz* 
 !"	??" :~D#D ''8I8I8NQ
E hGw''!//+W%8
 r#   c           
      p   [        U S5      (       + nU(       a\  [        R                  " U5      (       a  [        S5      e[	        U UU R
                  [        R                  [        R                  /SUS9nUR                  u  pVU(       a  SU l
        U R                  c=  U R                  c  [        XV5      U l        OU R                  R                  S   U l        OnU R                  U::  d  [        SU R                  U4-  5      eU R                  U:  a#  U(       a  [        SU R                   S	U S
35      eU R                  U l        U R                  bX  U R                  R                  S   U R                  :w  a1  [        SU R                  R                  S   U R                  4-  5      e[        U S5      (       d  SU l        SU l        SU l        [%        UU R                   U R"                  [        R&                  " U R                  UR                  S   5      S9u  pxn	U	S   n	U R                  S:X  a  X-  nO[        R(                  " USS9n
X-  n[        R*                  " U R                  U	-  U-  5      U R                   U
-
  -  n[        R,                  " U R.                  R1                  S5      U R                  -  UU45      n[2        R4                  " USSS9u  pn[7        XSS9u  pUS-  U	S-
  -  nUS-  [        R8                  " X-  5      -  nXl        USU R                   U l
        USU R                   U l        Xpl        Xl        USU R                   U l        USU R                   U l        U R                  XV4;  a#  XR                  S R)                  5       U l        U $ SU l        U $ )a  Incremental fit with X. All of X is processed as a single batch.

Parameters
----------
X : array-like of shape (n_samples, n_features)
    Training data, where `n_samples` is the number of samples and
    `n_features` is the number of features.

y : Ignored
    Not used, present for API consistency by convention.

check_input : bool, default=True
    Run check_array on X.

Returns
-------
self : object
    Returns the instance itself.
r0   zIncrementalPCA.partial_fit does not support sparse input. Either convert data to dense or use IncrementalPCA.fit to do so in batches.T)r   r+   r,   resetNr   zdn_components=%r invalid for n_features=%d, need more rows than columns for IncrementalPCA processingzn_components=z6 must be less or equal to the batch number of samples z  for the first partial_fit call.z{Number of input features has changed from %i to %i between calls to partial_fit! Try setting n_components to a fixed value.r1   r&   r   )	last_meanlast_variancelast_sample_count)axis)r   F)full_matricescheck_finite)u_based_decisionr   ) hasattrr   r=   	TypeErrorr   r   r8   r9   r:   r;   r0   r   minn_components_
ValueErrorr1   r2   r3   r   repeatmeansqrtvstackr4   reshaper   svdr   sumr5   r6   r7   )r   r@   rA   r   
first_passrB   rC   col_meancol_varn_total_samplescol_batch_meanmean_correctionUSVtexplained_varianceexplained_variance_ratios                    r    r?   IncrementalPCA.partial_fit   s   * !}55
q!!E 
 YYzz2::. $ A !"	#D$'%(%?"%)%5%5%;%;A%>"""j0 $ 1 1:>? 
 *z 1 12 3//8k :$$  "&!2!2D(""1%););;9 ##))!,d.@.@AB  t.//#$D DJDI .Gjj)) ii(<(<aggajI	.
*? *!, 1$MAWWQQ/NA gg%%79Dn,.O 		))11':T=M=MM#A ::au5Ib7T_q%89#$a4"&&1J*K#K .2 2 23 !"6D$6$6 7
	#56J8J8J#K )ABVDDVDV)W&i%<<#56H6H6J#K#P#P#RD   $'D r#   c                 ^  > [         R                  " U5      (       a  UR                  S   n/ n[        X R                  U R
                  =(       d    SS9 H1  nUR                  [        TU ]!  X   R                  5       5      5        M3     [        R                  " U5      $ [        TU ]!  U5      $ )aI  Apply dimensionality reduction to X.

X is projected on the first principal components previously extracted
from a training set, using minibatches of size batch_size if X is
sparse.

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
    New data, where `n_samples` is the number of samples
    and `n_features` is the number of features.

Returns
-------
X_new : ndarray of shape (n_samples, n_components)
    Projection of X in the first principal components.

Examples
--------

>>> import numpy as np
>>> from sklearn.decomposition import IncrementalPCA
>>> X = np.array([[-1, -1], [-2, -1], [-3, -2],
...               [1, 1], [2, 1], [3, 2]])
>>> ipca = IncrementalPCA(n_components=2, batch_size=3)
>>> ipca.fit(X)
IncrementalPCA(batch_size=3, n_components=2)
>>> ipca.transform(X) # doctest: +SKIP
r   r.   )r   r=   r;   r	   r<   r   appendsuper	transformr>   r8   rZ   )r   r@   rB   outputrD   	__class__s        r    rm   IncrementalPCA.transform}  s    < ??1
IF$++D<M<M<RQR eg/0@0@0BCD 99V$$7$Q''r#   c                 F   > [         TU ]  5       nSUR                  l        U$ NT)rl   __sklearn_tags__
input_tagsr   )r   tagsro   s     r    rs   IncrementalPCA.__sklearn_tags__  s!    w')!%r#   )r   r<   r0   r   r5   r6   r2   r   rU   r1   r7   r4   r3   r   r   rr   )__name__
__module____qualname____firstlineno____doc__r   UNUSED._IncrementalPCA__metadata_request__partial_fitr
   r   r   dict__annotations__r!   r   rF   r?   rm   rs   __static_attributes____classcell__)ro   s   @r    r   r      s    eN (56F6M6M&N# "(AtFCTJ+!T&A4H	$D %EQU % 51 61f 5z 6zx'(R r#   r   )r{   numbersr   numpyr8   scipyr   r   sklearn.utilsr   baser   utilsr	   utils._param_validationr
   utils.extmathr   r   utils.validationr   _baser   r    r#   r    <module>r      s6    0
     *   . ? , UX Ur#   