
    -iR                        S SK r S SKrS SKrS SKrS SKJrJrJ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  S S	KJr  S S
KJrJrJr  S SKJr  S SKJr  S r S r!S r"S r#\RH                  RK                  S\5      S 5       r&\RH                  RK                  S/ SQ5      \RH                  RK                  SSS/5      S 5       5       r'S r(S r)S r*S r+\RH                  RK                  S/ SQ5      S 5       r,S r-S r.S  r/S! r0\RH                  RK                  S/ SQ5      S" 5       r1\RH                  RK                  S#/ S$Q5      S% 5       r2S& r3S' r4S( r5S) r6S* r7S+ r8g),    N)	load_iris
make_blobsmake_circles)PCA	KernelPCA)NotFittedError)
Perceptron)
rbf_kernel)GridSearchCV)Pipeline)StandardScaler)assert_allcloseassert_array_almost_equalassert_array_equal)CSR_CONTAINERS)_check_psd_eigenvaluesc           	         [         R                  R                  U 5      nUR                  S5      nUR                  S5      nS nS GH  nSSSU4 H  n[	        U5      (       + n[        SXeUS	9nUR                  U5      n	UR                  U5      R                  U5      n
[        [         R                  " U	5      [         R                  " U
5      5        U	R                  S
:w  d   eUR                  U5      nUR                  S   U	R                  S   :X  d   eU(       d  M  UR                  U5      nUR                  UR                  :X  a  M   e   GM     g)zNominal test for all solvers and all known kernels + a custom one

It tests
 - that fit_transform is equivalent to fit+transform
 - that the shapes of transforms and inverse transforms are correct
         r   c                 Z    U0 :X  d   e[         R                  " X5      R                  5       $ )N)npminimumsum)xykwargss      ^/var/www/html/venv/lib/python3.13/site-packages/sklearn/decomposition/tests/test_kernel_pca.py	histogram"test_kernel_pca.<locals>.histogram#   s&    ||zz!##%%    autodensearpack
randomizedlinearrbfpolyr   )kerneleigen_solverfit_inverse_transformr      N)r   randomRandomStaterandom_samplecallabler   fit_transformfit	transformr   abssizeshapeinverse_transform)global_random_seedrngX_fitX_predr!   r-   r,   invkpcaX_fit_transformedX_fit_transformed2X_pred_transformedX_pred2s                r    test_kernel_pcarE      sI    ))

 2
3Cf%Ev&F&
 B	:F v&&C &SVD !% 2 25 9!%%!:!:5!A%()2662D+E %))Q... "&!7%++A.2C2I2I!2LLLL s001CD}}4445 ; Br#   c                      [        SSSS9n Sn[        R                  " [        US9   U R	                  [
        R                  R                  SS5      5        SSS5        g! , (       d  f       g= f)zCheck that kPCA raises an error if the parameters are invalid

Tests fitting inverse transform with a precomputed kernel raises a
ValueError.

   Tprecomputed)n_componentsr.   r,   z6Cannot fit_inverse_transform with a precomputed kernelmatchN)r   pytestraises
ValueErrorr5   r   r0   randn)	estimatorerr_mss     r    "test_kernel_pca_invalid_parametersrR   F   sR     tMI FF	z	0biioob"-. 
1	0	0s   0A  
A.c                 "   [         R                  R                  U 5      nUR                  SS5      n[	        US9R                  U5      nUR                  U5      nUR                  5       nSUSS2S4'   UR                  U5      n[        XF5        g)zCheck robustness to mutations in the original training array

Test that after fitting a kPCA model, it stays independent of any
mutation of the values of the original data object by relying on an
internal copy.
rG   )random_statei  Nr   )	r   r0   r1   randr   r5   r6   copyr   )r;   stateXr@   transformed1X_copytransformed2s          r    $test_kernel_pca_consistent_transformr\   T   sz     II!!"45E

2rA%(,,Q/D>>!$LVVXFAadG>>&)Ll9r#   c           
         [         R                  R                  U 5      nUR                  SS5      nSnU H  n[         R                  " S5      n[        S5       H'  n[        SXAS9nUR                  U5      S   XVSS24'   M)     [        U[         R                  " USSS24   S5      R                  SS5      5        M     g)	zyTest that Kernel PCA produces deterministic output

Tests that the same inputs and random state produce the same output.
rG   )r'   r&   )   r   r^   r   )rI   r-   rT   r   N)r   r0   r1   rU   zerosranger   r4   r   tilereshape)r;   r<   rX   r-   solvertransformed_Xir@   s           r    $test_kernel_pca_deterministic_outputrf   g   s    
 ))

 2
3CRA&L)rA!&SD"&"4"4Q"7":MQ$  	rww}QT/BB'G'O'OPRTU'VW r#   csr_containerc           
         [         R                  R                  U5      nU " UR                  S5      5      nU " UR                  S5      5      nS H  nS H  n[	        SUUSSS9nUR                  U5      nUR                  U5      R                  U5      n	[        [         R                  " U5      [         R                  " U	5      5        UR                  U5      n
U
R                  S	   UR                  S	   :X  d   e[        R                  " [        5         UR                  U
5        S
S
S
5        M     M     g
! , (       d  f       M  = f)zTest that kPCA works on a sparse data input.

Same test as ``test_kernel_pca except inverse_transform`` since it's not
implemented for sparse matrices.
r   r   )r%   r'   r(   )r)   r*   r+   r   Fr   )r,   r-   r.   rT   r/   N)r   r0   r1   r2   r   r4   r5   r6   r   r7   r9   rL   rM   r   r:   )rg   r;   r<   r=   r>   r-   r,   r@   rA   rB   rC   s              r    test_kernel_pca_sparseri   x   s!    ))

 2
3C#++F34E3,,V45F8/F)&+D !% 2 25 9!%%!:!:5!A%()2662D+E
 "&!7%++A.2C2I2I!2LLLL
 ~.&&'9: /.- 0 9. /.s   D::
E	rc   r$   
n_featuresr   rG   c           
         [         R                  R                  U5      nUR                  SU45      nUR                  SU45      nU S:X  a  SOSn[	        [         R
                  " [        X`S9R                  U5      R                  U5      5      [         R
                  " [        X`S:w  a  U OSS	9R                  U5      R                  U5      5      5        g
)zTest that kPCA with linear kernel is equivalent to PCA for all solvers.

KernelPCA with linear kernel should produce the same output as PCA.
r   r   r'      r   )r-   r&   full)
svd_solverN)
r   r0   r1   r2   r   r7   r   r5   r6   r   )rc   rj   r;   r<   r=   r>   n_compss          r    test_kernel_pca_linear_kernelrp      s     ))

 2
3Cq*o.E:/F X%a1G
y6::5AKKFST
.?FVLSZYv	
r#   c                  $   [         R                  R                  S5      n U R                  S5      nU R                  S5      nS HI  nS H@  n[	        XCS9nUR                  U5      R                  U5      R                  nUSU4:X  a  M@   e   MK     g)	zTest that `n_components` is correctly taken into account for projections

For all solvers this tests that the output has the correct shape depending
on the selected number of components.
r   r   r   r&   r'   r(   )r/   r   r   rI   r-   r   N)r   r0   r1   r2   r   r5   r6   r9   )r<   r=   r>   r-   cr@   r9   s          r    test_kernel_pca_n_componentsru      s     ))


"Cf%Ev&F9A!GDHHUO--f5;;EQF?"?	  :r#   c                  N   [         R                  " SS/SS/SS//5      n [        5       nUR                  U 5      nUR                  S:X  d   e[        SS9nUR                  U 5      nUR                  S:X  d   e[        SSS9nUR                  U 5      nUR                  S:X  d   eg	)
zCheck that the ``remove_zero_eig`` parameter works correctly.

Tests that the null-space (Zero) eigenvalues are removed when
remove_zero_eig=True, whereas they are not by default.
      ?r/   )rl   r   r   rI   )rl   r   T)rI   remove_zero_eigN)r   arrayr   r4   r9   )rX   r@   Xts      r    test_remove_zero_eigr|      s     	9a.1a&1i.9:A ;D			A	B88v!$D			A	B88v!T:D			A	B88vr#   c                     [         R                  " SS/SS//5      n [        R                  " 5          [        R                  " S[
        5        [         R                  " SS9   [        SSSS	9nUR                  U 5      R                  U 5      nUR                  U 5      n[        [         R                  " U5      [         R                  " U5      5        S
S
S
5        S
S
S
5        g
! , (       d  f       N= f! , (       d  f       g
= f)zNon-regression test for issue #12141 (PR #12143)

This test checks that fit().transform() returns the same result as
fit_transform() in case of non-removed zero eigenvalue.
r/   r   errorwarn)allr   Fr&   )rI   ry   r-   N)r   rz   warningscatch_warningssimplefilterRuntimeWarningerrstater   r5   r6   r4   r   r7   )r=   kABs       r    test_leave_zero_eigr      s     HHq!fq!f%&E 
	 	 	"
 	g~6[[V$q%gVAe&&u-A&A%bffQi; % 
#	" %$ 
#	"s$   0C5"A1C$C5$
C2	.C55
Dc                    [         R                  R                  U 5      nUR                  S5      nUR                  S5      nS GH  n[	        SUSS9R                  U5      R                  U5      n[	        SUSSS9R                  [         R                  " X"R                  5      5      R                  [         R                  " X2R                  5      5      n[	        SUSSS9R                  [         R                  " X"R                  5      5      n[	        SUSSS9R                  [         R                  " X"R                  5      5      R                  [         R                  " X"R                  5      5      n[        [         R                  " U5      [         R                  " U5      5        [        [         R                  " U5      [         R                  " U5      5        GM     g	)
z?Test that kPCA works with a precomputed kernel, for all solversr   r   rr   r   r   r-   rT   rH   )r-   r,   rT   N)r   r0   r1   r2   r   r5   r6   dotTr4   r   r7   )	r;   r<   r=   r>   r-   X_kpcaX_kpca2X_kpca_trainX_kpca_train2s	            r    test_kernel_pca_precomputedr      s^   
))

 2
3Cf%Ev&F9alCSZYv 	 ]QR Sww'(Yrvvfgg./ 	 !LQ

-ugg.
/ 	
 ]QR Sww'(YrvveWW-. 	 	""&&."&&/B!"&&"6}8MN; :r#   c                    SS/SS//n[        SU SSS9nUR                  U5        SS	/S	S//n[        SU SSS9nUR                  U5        [        UR                  UR                  5        [        UR                  UR                  5        g
)zCheck that the kernel centerer works.

Tests that a non symmetric precomputed kernel is actually accepted
because the kernel centerer does its job correctly.
r/   r   rl   (   rH   r   )r,   r-   rI   rT   	   iN)r   r5   r   eigenvectors_eigenvalues_)rc   Kr@   Kckpca_cs        r    )test_kernel_pca_precomputed_non_symmetricr     s     Q!RA6PQD 	HHQK b'B7	B6PQF JJrN t))6+?+?@t((&*=*=>r#   c                     [        SSSSS9u  p[        SSS9n[        S	U4S
[        SS94/5      n[	        S[
        R                  " SS5      -  S9n[        USUS9nUR                  X5        UR                  S:X  d   eg)zCheck that kPCA works as expected in a grid search pipeline

Test if we can do a grid-search to find parameters to separate
circles with a perceptron model.
  333333?皙?r   	n_samplesfactornoiserT   r*   r   r,   rI   
kernel_pcar	   r   max_iter       @)kernel_pca__gammarl   cv
param_gridr/   N)
r   r   r   r	   dictr   aranger   r5   best_score_)rX   r   r@   pipeliner   grid_searchs         r    test_gridsearch_pipeliner   :  s     #cANDAE2D,-jRS>T/UVWHryyQ/?(?@JxA*EKOOA""a'''r#   c                     [        SSSSS9u  p[        SSS9n[        S	U4S
[        SS94/5      n[	        [
        R                  " SS5      S9n[        USUS9n[        U SS9nUR                  Xa5        UR                  S:X  d   eg)zCheck that kPCA works as expected in a grid search pipeline (2)

Test if we can do a grid-search to find parameters to separate
circles with a perceptron model. This test uses a precomputed kernel.
r   r   r   r   r   rH   r   r   r   r	   r   r   r/   )Perceptron__max_iterrl   r   r   )gammaN)r   r   r   r	   r   r   r   r   r
   r5   r   )rX   r   r@   r   r   r   X_kernels          r    $test_gridsearch_pipeline_precomputedr   I  s     #cANDAM:D,-jRS>T/UVWH299Q?;JxA*EK!3'HOOH ""a'''r#   c                     [        SSSSS9u  p[        SS9R                  X5      R                  X5      nUS:  d   e[	        S	S
SSS9nUR                  U 5      n[        SS9R                  XA5      R                  XA5      nUS:X  d   eg)a  Check that kPCA projects in a space where nested circles are separable

Tests that 2D nested circles become separable with a perceptron when
projected in the first 2 kPCA using an RBF kernel, while raw samples
are not directly separable in the original space.
r   r   r   r   r   r   r   g?r*   r   Tr   )r,   rI   r.   r   rw   N)r   r	   r5   scorer   r4   )rX   r   train_scorer@   r   s        r    test_nested_circlesr   Y  s     #cANDA a(,,Q288>K 1DD "F a(,,V7==fHK#r#   c                     SS/SS/SS//n [        SSSS	9nUR                  U 5        UR                  R                  5       S:X  d   e[        R
                  " UR                  [        UR                  5      :H  5      (       d   eg
)zuCheck that ``_check_psd_eigenvalues`` is correctly called in kPCA

Non-regression test for issue #12140 (PR #12145).
r   r/   gw̫   @g:0yE>r   r)   r   T)r,   rI   r.   N)r   r5   r   minr   r   r   rX   r@   s     r    test_kernel_conditioningr   u  s     Q(D!Ha=1AH1DQDHHQK   "a'''66$##'=d>O>O'PPQQQQr#   c           	         / SQ/ SQ/ SQ/ SQ/ SQ/ SQ/ SQ/ SQ/n[        S	U S
S9n[        R                  " [        SS9   UR	                  U5        SSS5        [        S	U SS9nU S:X  a4  [        R                  " [        SS9   UR	                  U5        SSS5        gUR	                  U5        g! , (       d  f       Ne= f! , (       d  f       g= f)a  Check how KernelPCA works with non-PSD kernels depending on n_components

Tests for all methods what happens with a non PSD gram matrix (this
can happen in an isomap scenario, or with custom kernel functions, or
maybe with ill-posed datasets).

When ``n_component`` is large enough to capture a negative eigenvalue, an
error should be raised. Otherwise, KernelPCA should run without error
since the negative eigenvalues are not selected.
)gQ@      p=
# @p=
ף@r   r   
ףp=
(\))r   gQ      @ףp=
r   r   Q(\@)r   r   g(\.@Q @r   r   333333&{G:7)r   r   r         @333333r   RQ?)r   r   r   r   r   r   r   r   )r   r   r   r   r   r   r   r   )r   r   r   r   r   r   gq=
ףp@     #@)r   r   r   r   r   r   r   g(\u5@rH      )r,   r-   rI   z*There are significant negative eigenvaluesrJ   Nr   r(   )r   rL   rM   rN   r5   )rc   r   r@   s      r    test_precomputed_kernel_not_psdr     s      	<<;:::;=		A MQOD	z)U	V 
W MQOD ]]J
 HHQK
 
 	% 
W	V
 
s   B0C0
B>
CrI   )r   rG   r^   c                    Su  p[        X-   SSSS9u  p4USU2SS24   X1S2SS24   pe[        U SSS9R                  U5      R                  U5      n[        U S	SS9R                  U5      R                  U5      n[	        [
        R                  " U5      [
        R                  " U5      5        [        U S
SS9R                  U5      R                  U5      n	[	        [
        R                  " U	5      [
        R                  " U5      5        g)zGCheck that 'dense' 'arpack' & 'randomized' solvers give similar results)i  d   r   r   r   r   Nr&   r   r'   r(   )r   r   r5   r6   r   r   r7   )
rI   n_trainn_testrX   _r=   r>   ref_preda_predr_preds
             r    #test_kernel_pca_solvers_equivalencer     s    
 !OG#S1DA hwhkNAhkN6 	,W1E	U	6	  	,XAF	U	6	  bffVnbffX.>? 	,\J	U	6	  bffVnbffX.>?r#   c                     [        SSSS9tp[        SSSSS	9nUR                  U 5      nUR                  U5      n[        R
                  R                  X-
  5      [        R
                  R                  U 5      -  S
:  d   eg)zTest if the reconstruction is a good approximation.

Note that in general it is not possible to get an arbitrarily good
reconstruction because of kernel centering that does not
preserve all the information of the original data.
r   r   r   r   rj   rT   r^   r*   TgMbP?)rI   r,   r.   alpha皙?N)r   r   r4   r:   r   linalgnorm)rX   r   r@   X_trans	X_reconsts        r    0test_kernel_pca_inverse_transform_reconstructionr     sx     CEATD   #G&&w/I99>>!-(299>>!+<<tCCCr#   c                  "   [         R                  R                  S5      R                  SS5      n [	        5       nUR                  U 5        [        R                  " [        5         UR                  U 5        S S S 5        g ! , (       d  f       g = f)N   r   rl   )
r   r0   rO   rb   r   r5   rL   rM   r   r:   r   s     r    &test_kernel_pca_raise_not_fitted_errorr     sY    
		##Aq)A;DHHQK	~	&q! 
'	&	&s   %B  
Bc                  D   [        S/ SQ/ SQ/SSS9u  p[        5       R                  U 5      n X R                  5       -  n [	        5       nUR                  U 5      R
                  UR                  U R                  [        R                  5      5      R
                  :X  d   eg)zTest that the decomposition is similar for 32 and 64 bits data

Non regression test for
https://github.com/scikit-learn/scikit-learn/issues/18146
   )r   r   r   )r/   r/   r/   r   r   )r   centersrT   cluster_stdN)	r   r   r4   r   r   r9   astyper   float32)rX   r   r@   s      r    test_32_64_decomposition_shaper     s     y)41RUDA 	&&q)ALA ;Da &&$*<*<QXXbjj=Q*R*X*XXXXr#   c                      [        SSSS9tp[        SS9R                  U 5      nUR                  5       n[	        [        S5       Vs/ s H  nSU 3PM
     snU5        gs  snf )	z&Check feature names out for KernelPCA.r   r   r   r   r   rx   	kernelpcaN)r   r   r5   get_feature_names_outr   r`   )rX   r   r@   namesre   s        r    !test_kernel_pca_feature_names_outr     s[    CEA!$((+D&&(Eq:A)A3:EB:s   Ac                    [         R                  R                  U 5      nUR                  S5      nSUSSS.nSUR                  S   -  n[        S	SS0UD6R                  U5      n[        S	SU0UD6R                  U5      nUR                  U:X  d   eUR                  U:X  d   eUR                  UR                  U5      5      nUR                  UR                  U5      5      n[        Xx5        g)
zUCheck that gamma is set correctly when not provided.

Non-regression test for #26280
r   r   Tr*   )rI   rT   r.   r,   r/   r   N )r   r0   r1   r2   r9   r   r5   gamma_r:   r6   r   )	r;   r<   rX   r   expected_gammakpca1kpca2X1_reconX2_recons	            r    %test_kernel_pca_inverse_correct_gammar     s    
 ))

 2
3C&!A !%	F ^N+D+F+//2E5N5f599!<E<<>)))<<>)))&&uq'9:H&&uq'9:HH'r#   c                      [         R                  " S5        [        SSS9u  p[        R                  " SS9   [        SSS9R                  U 5        SSS5        g! , (       d  f       g= f)	zCheck that KernelPCA works with pandas output when the solver is arpack.

Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/27579
pandasT)as_frame
return_X_y)transform_outputr   r'   rs   N)rL   importorskipr   sklearnconfig_contextr   r4   )rX   r   s     r    test_kernel_pca_pandas_outputr  -  sO     !dt4DA				:qx8FFqI 
;	:	:s   A
A()9r   numpyr   rL   r  sklearn.datasetsr   r   r   sklearn.decompositionr   r   sklearn.exceptionsr   sklearn.linear_modelr	   sklearn.metrics.pairwiser
   sklearn.model_selectionr   sklearn.pipeliner   sklearn.preprocessingr   sklearn.utils._testingr   r   r   sklearn.utils.fixesr   sklearn.utils.validationr   rE   rR   r\   rf   markparametrizeri   rp   ru   r|   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r   r#   r    <module>r     s       @ @ 0 - + / 0 % 0 
 / ;+5\/:&X" .9"; :";J #LM2w/ 0 N0#$,<2#OL #LM? N?4(( 8R  #LM0 N0f 5!@ 6!@HD""Y"C(8	Jr#   