
    -i                     8   S r SSKrSSKJrJr  SSKrSSKJr	  SSK
JrJr  SSKJr  SSKJrJrJrJr  SSKJrJrJr  SS	KJr  SS
KJrJr  SSKJr  SSKJ r J!r!J"r"   " S S\\\5      r# " S S\\\5      r$ " S S\\\5      r% " S S\\5      r& " S S\\\5      r'g)zOApproximate kernel feature maps based on Fourier transforms and count sketches.    N)IntegralReal)fftifft)svd   )BaseEstimatorClassNamePrefixFeaturesOutMixinTransformerMixin_fit_context)KERNEL_PARAMSPAIRWISE_KERNEL_FUNCTIONSpairwise_kernels)check_random_state)Interval
StrOptions)safe_sparse_dot)_check_feature_names_incheck_is_fittedvalidate_datac            
          ^  \ rS rSr% Sr\" \SSSS9/\" \SSSS9/\" \SSSS9/\" \SSSS9/S	/S
.r\	\
S'   SSSSSS
.S jr\" SS9SS j5       rS rU 4S jrSrU =r$ )PolynomialCountSketch   a  Polynomial kernel approximation via Tensor Sketch.

Implements Tensor Sketch, which approximates the feature map
of the polynomial kernel::

    K(X, Y) = (gamma * <X, Y> + coef0)^degree

by efficiently computing a Count Sketch of the outer product of a
vector with itself using Fast Fourier Transforms (FFT). Read more in the
:ref:`User Guide <polynomial_kernel_approx>`.

.. versionadded:: 0.24

Parameters
----------
gamma : float, default=1.0
    Parameter of the polynomial kernel whose feature map
    will be approximated.

degree : int, default=2
    Degree of the polynomial kernel whose feature map
    will be approximated.

coef0 : int, default=0
    Constant term of the polynomial kernel whose feature map
    will be approximated.

n_components : int, default=100
    Dimensionality of the output feature space. Usually, `n_components`
    should be greater than the number of features in input samples in
    order to achieve good performance. The optimal score / run time
    balance is typically achieved around `n_components` = 10 * `n_features`,
    but this depends on the specific dataset being used.

random_state : int, RandomState instance, default=None
    Determines random number generation for indexHash and bitHash
    initialization. Pass an int for reproducible results across multiple
    function calls. See :term:`Glossary <random_state>`.

Attributes
----------
indexHash_ : ndarray of shape (degree, n_features), dtype=int64
    Array of indexes in range [0, n_components) used to represent
    the 2-wise independent hash functions for Count Sketch computation.

bitHash_ : ndarray of shape (degree, n_features), dtype=float32
    Array with random entries in {+1, -1}, used to represent
    the 2-wise independent hash functions for Count Sketch computation.

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
--------
AdditiveChi2Sampler : Approximate feature map for additive chi2 kernel.
Nystroem : Approximate a kernel map using a subset of the training data.
RBFSampler : Approximate a RBF kernel feature map using random Fourier
    features.
SkewedChi2Sampler : Approximate feature map for "skewed chi-squared" kernel.
sklearn.metrics.pairwise.kernel_metrics : List of built-in kernels.

Examples
--------
>>> from sklearn.kernel_approximation import PolynomialCountSketch
>>> from sklearn.linear_model import SGDClassifier
>>> X = [[0, 0], [1, 1], [1, 0], [0, 1]]
>>> y = [0, 0, 1, 1]
>>> ps = PolynomialCountSketch(degree=3, random_state=1)
>>> X_features = ps.fit_transform(X)
>>> clf = SGDClassifier(max_iter=10, tol=1e-3)
>>> clf.fit(X_features, y)
SGDClassifier(max_iter=10)
>>> clf.score(X_features, y)
1.0

For a more detailed example of usage, see
:ref:`sphx_glr_auto_examples_kernel_approximation_plot_scalable_poly_kernels.py`
r   Nleftclosedr   neitherrandom_stategammadegreecoef0n_componentsr   _parameter_constraints      ?   d   c                @    Xl         X l        X0l        X@l        XPl        g Nr   )selfr    r!   r"   r#   r   s         O/var/www/html/venv/lib/python3.13/site-packages/sklearn/kernel_approximation.py__init__PolynomialCountSketch.__init__   s     

((    Tprefer_skip_nested_validationc                 L   [        XSS9n[        U R                  5      nUR                  S   nU R                  S:w  a  US-  nUR                  SU R                  U R                  U4S9U l        UR                  SS/U R                  U4S9U l
        U R                  U l        U $ )aA  Fit the model with X.

Initializes the internal variables. The method needs no information
about the distribution of data, so we only care about n_features in X.

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 : array-like of shape (n_samples,) or (n_samples, n_outputs),                 default=None
    Target values (None for unsupervised transformations).

Returns
-------
self : object
    Returns the instance itself.
cscaccept_sparser   r   )highsize)ar6   )r   r   r   shaper"   randintr#   r!   
indexHash_choicebitHash__n_features_out)r*   Xyr   
n_featuress        r+   fitPolynomialCountSketch.fit   s    , $7)$*;*;<WWQZ
::?!OJ&..D%%T[[*,E / 
 %++r1gT[[*<U+V#00r.   c           	      4   [        U 5        [        XSSS9n[        R                  " U R                  5      U-  n[
        R                  " U5      (       al  U R                  S:w  a\  [
        R                  " U[        R                  " U R                  5      [        R                  " UR                  S   S45      -  /SS9nO[
        R                  " U5      (       dl  U R                  S:w  a\  [        R                  " U[        R                  " U R                  5      [        R                  " UR                  S   S45      -  /5      nUR                  S   U R                  R                  S   :w  a  [        S5      e[        R                  " UR                  S   U R                  U R                  45      n[
        R                  " U5      (       a  [!        UR                  S   5       Hv  n[!        U R                  5       HZ  nU R                  XT4   nU R"                  XT4   nUSS2XV4==   XrSS2U/4   -  R%                  5       R'                  5       -  ss'   M\     Mx     Ou[!        UR                  S   5       HY  n[!        U R                  5       H=  nU R                  XT4   nU R"                  XT4   nUSS2XV4==   XrSS2U4   -  -  ss'   M?     M[     [)        US	S
S9n[        R*                  " USS9n	[        R,                  " [/        U	S
S95      n
U
$ )aD  Generate the feature map approximation for X.

Parameters
----------
X : {array-like}, 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 : array-like, shape (n_samples, n_components)
    Returns the instance itself.
r2   Fr4   resetr   r   )formatzKNumber of features of test samples does not match that of training samples.Nr&   T)axisoverwrite_x)rH   )rI   )r   r   npsqrtr    spissparser"   hstackonesr9   r;   
ValueErrorzerosr!   r#   ranger=   toarrayravelr   prodrealr   )r*   r?   X_gammacount_sketchesjd
iHashIndexiHashBitcount_sketches_fftcount_sketches_fft_proddata_sketchs              r+   	transformPolynomialCountSketch.transform   s    	$eD''$**%);;wDJJ!Oii"''$**-q9I18M0NNOG
 W%%$**/ii"''$**-q9I18M0NNOG ==t44Q773 
 7==#3T[[$BSBS"TU;;w7==+,t{{+A!%!6J#}}QT2H"1a#34!AsFO3<<>DDF4 , - 7==+,t{{+A!%!6J#}}QT2H"1a#341a4=8PP4 , - !aTJ"$''*<1"Eggd#:MNr.   c                 F   > [         TU ]  5       nSUR                  l        U$ )NT)super__sklearn_tags__
input_tagssparser*   tags	__class__s     r+   rd   &PolynomialCountSketch.__sklearn_tags__   s!    w')!%r.   )r>   r=   r"   r!   r    r;   r#   r   r)   __name__
__module____qualname____firstlineno____doc__r   r   r   r$   dict__annotations__r,   r   rB   r`   rd   __static_attributes____classcell__ri   s   @r+   r   r      s    Up 4D89Haf=>4tI>?!(AtFCD'($D  1ACd) 5" 6"H=~ r.   r   c                      ^  \ rS rSr% Sr\" S15      \" \SSSS9/\" \SSSS9/S	/S
.r	\
\S'   SSSS
.S jr\" SS9SS j5       rS rU 4S jrSrU =r$ )
RBFSampler   a
  Approximate a RBF kernel feature map using random Fourier features.

It implements a variant of Random Kitchen Sinks.[1]

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

Parameters
----------
gamma : 'scale' or float, default=1.0
    Parameter of RBF kernel: exp(-gamma * x^2).
    If ``gamma='scale'`` is passed then it uses
    1 / (n_features * X.var()) as value of gamma.

    .. versionadded:: 1.2
       The option `"scale"` was added in 1.2.

n_components : int, default=100
    Number of Monte Carlo samples per original feature.
    Equals the dimensionality of the computed feature space.

random_state : int, RandomState instance or None, default=None
    Pseudo-random number generator to control the generation of the random
    weights and random offset when fitting the training data.
    Pass an int for reproducible output across multiple function calls.
    See :term:`Glossary <random_state>`.

Attributes
----------
random_offset_ : ndarray of shape (n_components,), dtype={np.float64, np.float32}
    Random offset used to compute the projection in the `n_components`
    dimensions of the feature space.

random_weights_ : ndarray of shape (n_features, n_components),        dtype={np.float64, np.float32}
    Random projection directions drawn from the Fourier transform
    of the RBF kernel.

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
--------
AdditiveChi2Sampler : Approximate feature map for additive chi2 kernel.
Nystroem : Approximate a kernel map using a subset of the training data.
PolynomialCountSketch : Polynomial kernel approximation via Tensor Sketch.
SkewedChi2Sampler : Approximate feature map for
    "skewed chi-squared" kernel.
sklearn.metrics.pairwise.kernel_metrics : List of built-in kernels.

Notes
-----
See "Random Features for Large-Scale Kernel Machines" by A. Rahimi and
Benjamin Recht.

[1] "Weighted Sums of Random Kitchen Sinks: Replacing
minimization with randomization in learning" by A. Rahimi and
Benjamin Recht.
(https://people.eecs.berkeley.edu/~brecht/papers/08.rah.rec.nips.pdf)

Examples
--------
>>> from sklearn.kernel_approximation import RBFSampler
>>> from sklearn.linear_model import SGDClassifier
>>> X = [[0, 0], [1, 1], [1, 0], [0, 1]]
>>> y = [0, 0, 1, 1]
>>> rbf_feature = RBFSampler(gamma=1, random_state=1)
>>> X_features = rbf_feature.fit_transform(X)
>>> clf = SGDClassifier(max_iter=5, tol=1e-3)
>>> clf.fit(X_features, y)
SGDClassifier(max_iter=5)
>>> clf.score(X_features, y)
1.0
scale        Nr   r   r   r   r    r#   r   r$   r%   r'   c                (    Xl         X l        X0l        g r)   r{   )r*   r    r#   r   s       r+   r,   RBFSampler.__init__P  s    
((r.   Tr/   c                 V   [        XSS9n[        U R                  5      nUR                  S   n[        R
                  " U5      nU R                  S:X  a_  U(       a3  UR                  U5      R                  5       UR                  5       S-  -
  OUR                  5       nUS:w  a  SXF-  -  OSU l
        OU R                  U l
        SU R                  -  S	-  UR                  X@R                  4S
9-  U l        UR                  SS[        R                   -  U R                  S
9U l        UR$                  [        R&                  :X  aR  U R                  R)                  UR$                  SS9U l        U R"                  R)                  UR$                  SS9U l        U R                  U l        U $ )a  Fit the model with X.

Samples random projection according to n_features.

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

y : array-like, shape (n_samples,) or (n_samples, n_outputs),                 default=None
    Target values (None for unsupervised transformations).

Returns
-------
self : object
    Returns the instance itself.
csrr3   r   ry   r&   r   r%          @      ?r6   Fcopy)r   r   r   r9   rL   rM   r    multiplymeanvar_gammanormalr#   random_weights_uniformrJ   pirandom_offset_dtypefloat32astyper>   )r*   r?   r@   r   rA   rf   X_vars          r+   rB   RBFSampler.fitU  sd   * $7)$*;*;<WWQZ
Q:: @FQZZ]((*affh1_<AEEGE8=
#!34DK**DK #dkk 1c9L<O<O//0 =P =
  
 +221a"%%idFWFW2X77bjj  $(#7#7#>#>qwwU#>#SD "&"5"5"<"<QWW5"<"QD#00r.   c                     [        U 5        [        XSSS9n[        XR                  5      nX R                  -  n[
        R                  " X"5        USU R                  -  S-  -  nU$ )aM  Apply the approximate feature map to X.

Parameters
----------
X : {array-like, sparse matrix}, 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 : array-like, shape (n_samples, n_components)
    Returns the instance itself.
r   FrE   r   r   )r   r   r   r   r   rJ   cosr#   r*   r?   
projections      r+   r`   RBFSampler.transform  sd     	$eD$Q(<(<=
)))

z&sT...366
r.   c                 l   > [         TU ]  5       nSUR                  l        SS/UR                  l        U$ NTfloat64r   rc   rd   re   rf   transformer_tagspreserves_dtyperg   s     r+   rd   RBFSampler.__sklearn_tags__  4    w')!%1:I0F-r.   )r   r>   r    r#   r   r   r   r)   )rl   rm   rn   ro   rp   r   r   r   r   r$   rq   rr   r,   r   rB   r`   rd   rs   rt   ru   s   @r+   rw   rw      s    Ph y!T3V4
 "(AtFCD'($D  !$#D )
 5+ 6+Z. r.   rw   c                      ^  \ rS rSr% Sr\" \SSSS9/\" \SSSS9/S/S	.r\	\
S
'   SSSS	.S jr\" SS9SS j5       rS rU 4S jrSrU =r$ )SkewedChi2Sampleri  a	  Approximate feature map for "skewed chi-squared" kernel.

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

Parameters
----------
skewedness : float, default=1.0
    "skewedness" parameter of the kernel. Needs to be cross-validated.

n_components : int, default=100
    Number of Monte Carlo samples per original feature.
    Equals the dimensionality of the computed feature space.

random_state : int, RandomState instance or None, default=None
    Pseudo-random number generator to control the generation of the random
    weights and random offset when fitting the training data.
    Pass an int for reproducible output across multiple function calls.
    See :term:`Glossary <random_state>`.

Attributes
----------
random_weights_ : ndarray of shape (n_features, n_components)
    Weight array, sampled from a secant hyperbolic distribution, which will
    be used to linearly transform the log of the data.

random_offset_ : ndarray of shape (n_features, n_components)
    Bias term, which will be added to the data. It is uniformly distributed
    between 0 and 2*pi.

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
--------
AdditiveChi2Sampler : Approximate feature map for additive chi2 kernel.
Nystroem : Approximate a kernel map using a subset of the training data.
RBFSampler : Approximate a RBF kernel feature map using random Fourier
    features.
SkewedChi2Sampler : Approximate feature map for "skewed chi-squared" kernel.
sklearn.metrics.pairwise.chi2_kernel : The exact chi squared kernel.
sklearn.metrics.pairwise.kernel_metrics : List of built-in kernels.

References
----------
See "Random Fourier Approximations for Skewed Multiplicative Histogram
Kernels" by Fuxin Li, Catalin Ionescu and Cristian Sminchisescu.

Examples
--------
>>> from sklearn.kernel_approximation import SkewedChi2Sampler
>>> from sklearn.linear_model import SGDClassifier
>>> X = [[0, 0], [1, 1], [1, 0], [0, 1]]
>>> y = [0, 0, 1, 1]
>>> chi2_feature = SkewedChi2Sampler(skewedness=.01,
...                                  n_components=10,
...                                  random_state=0)
>>> X_features = chi2_feature.fit_transform(X, y)
>>> clf = SGDClassifier(max_iter=10, tol=1e-3)
>>> clf.fit(X_features, y)
SGDClassifier(max_iter=10)
>>> clf.score(X_features, y)
1.0
Nr   r   r   r   r   
skewednessr#   r   r$   r%   r'   c                (    Xl         X l        X0l        g r)   r   )r*   r   r#   r   s       r+   r,   SkewedChi2Sampler.__init__  s    $((r.   Tr/   c                    [        X5      n[        U R                  5      nUR                  S   nUR	                  X@R
                  4S9nS[        R                  -  [        R                  " [        R                  " [        R                  S-  U-  5      5      -  U l
        UR	                  SS[        R                  -  U R
                  S9U l        UR                  [        R                  :X  aR  U R                  R                  UR                  SS9U l
        U R                  R                  UR                  SS9U l        U R
                  U l        U $ )	a  Fit the model with X.

Samples random projection according to n_features.

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

y : array-like, shape (n_samples,) or (n_samples, n_outputs),                 default=None
    Target values (None for unsupervised transformations).

Returns
-------
self : object
    Returns the instance itself.
r   r   r%   r   r   r&   Fr   )r   r   r   r9   r   r#   rJ   r   logtanr   r   r   r   r   r>   )r*   r?   r@   r   rA   r   s         r+   rB   SkewedChi2Sampler.fit  s   * $")$*;*;<WWQZ
&&Z9J9J,K&L"RUU{RVVBFF2553;;P4Q-RR*221a"%%idFWFW2X77bjj  $(#7#7#>#>qwwU#>#SD "&"5"5"<"<QWW5"<"QD#00r.   c                    [        U 5        [        XS[        R                  [        R                  /SS9nXR
                  * :*  R                  5       (       a  [        S5      eXR
                  -  n[        R                  " X5        [        XR                  5      nX R                  -  n[        R                  " X"5        U[        R                  " S5      [        R                  " U R                  5      -  -  nU$ )a}  Apply the approximate feature map to X.

Parameters
----------
X : array-like, shape (n_samples, n_features)
    New data, where `n_samples` is the number of samples
    and `n_features` is the number of features. All values of X must be
    strictly greater than "-skewedness".

Returns
-------
X_new : array-like, shape (n_samples, n_components)
    Returns the instance itself.
TF)r   r   rF   z3X may not contain entries smaller than -skewedness.r   )r   r   rJ   r   r   r   anyrP   r   r   r   r   r   rK   r#   r   s      r+   r`   SkewedChi2Sampler.transform  s     	$rzz2::&>e
 //!!&&((RSS	__
q$Q(<(<=
)))

z&bggclRWWT->->%???
r.   c                 J   > [         TU ]  5       nSS/UR                  l        U$ )Nr   r   )rc   rd   r   r   rg   s     r+   rd   "SkewedChi2Sampler.__sklearn_tags__;  s(    w')1:I0F-r.   )r>   r#   r   r   r   r   r)   rk   ru   s   @r+   r   r     sz    FR  dDCD!(AtFCD'($D  &)s )
 5# 6#J< r.   r   c                      ^  \ rS rSr% Sr\" \SSSS9/\" \SSSS9S/S.r\	\
S	'   S
SS.S jr\" SS9SS j5       rS rSS jr\S 5       r\S 5       rU 4S jrSrU =r$ )AdditiveChi2SampleriA  a	  Approximate feature map for additive chi2 kernel.

Uses sampling the fourier transform of the kernel characteristic
at regular intervals.

Since the kernel that is to be approximated is additive, the components of
the input vectors can be treated separately.  Each entry in the original
space is transformed into 2*sample_steps-1 features, where sample_steps is
a parameter of the method. Typical values of sample_steps include 1, 2 and
3.

Optimal choices for the sampling interval for certain data ranges can be
computed (see the reference). The default values should be reasonable.

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

Parameters
----------
sample_steps : int, default=2
    Gives the number of (complex) sampling points.

sample_interval : float, default=None
    Sampling interval. Must be specified when sample_steps not in {1,2,3}.

Attributes
----------
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
--------
SkewedChi2Sampler : A Fourier-approximation to a non-additive variant of
    the chi squared kernel.

sklearn.metrics.pairwise.chi2_kernel : The exact chi squared kernel.

sklearn.metrics.pairwise.additive_chi2_kernel : The exact additive chi
    squared kernel.

Notes
-----
This estimator approximates a slightly different version of the additive
chi squared kernel then ``metric.additive_chi2`` computes.

This estimator is stateless and does not need to be fitted. However, we
recommend to call :meth:`fit_transform` instead of :meth:`transform`, as
parameter validation is only performed in :meth:`fit`.

References
----------
See `"Efficient additive kernels via explicit feature maps"
<http://www.robots.ox.ac.uk/~vedaldi/assets/pubs/vedaldi11efficient.pdf>`_
A. Vedaldi and A. Zisserman, Pattern Analysis and Machine Intelligence,
2011

Examples
--------
>>> from sklearn.datasets import load_digits
>>> from sklearn.linear_model import SGDClassifier
>>> from sklearn.kernel_approximation import AdditiveChi2Sampler
>>> X, y = load_digits(return_X_y=True)
>>> chi2sampler = AdditiveChi2Sampler(sample_steps=2)
>>> X_transformed = chi2sampler.fit_transform(X, y)
>>> clf = SGDClassifier(max_iter=5, random_state=0, tol=1e-3)
>>> clf.fit(X_transformed, y)
SGDClassifier(max_iter=5, random_state=0)
>>> clf.score(X_transformed, y)
0.9499...
r   Nr   r   r   sample_stepssample_intervalr$   r&   c                    Xl         X l        g r)   r   )r*   r   r   s      r+   r,   AdditiveChi2Sampler.__init__  s    (.r.   Tr/   c                 l    [        XSSS9nU R                  c  U R                  S;  a  [        S5      eU $ )a+  Only validates estimator's parameters.

This method allows to: (i) validate the estimator's parameters and
(ii) be consistent with the scikit-learn transformer API.

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

y : array-like, shape (n_samples,) or (n_samples, n_outputs),                 default=None
    Target values (None for unsupervised transformations).

Returns
-------
self : object
    Returns the transformer.
r   T)r4   ensure_non_negative)r   r&      HIf sample_steps is not in [1, 2, 3], you need to provide sample_interval)r   r   r   rP   )r*   r?   r@   s      r+   rB   AdditiveChi2Sampler.fit  sD    , $DQ'D,=,=Y,N7 
 r.   c                 d   [        XSSSS9n[        R                  " U5      nU R                  cD  U R                  S:X  a  SnO=U R                  S:X  a  SnO*U R                  S	:X  a  S
nO[        S5      eU R                  nU(       a  U R                  OU R                  nU" XR                  U5      $ )a  Apply approximate feature map to X.

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

Returns
-------
X_new : {ndarray, sparse matrix},                shape = (n_samples, n_features * (2*sample_steps - 1))
    Whether the return value is an array or sparse matrix depends on
    the type of the input X.
r   FT)r4   rF   r   r   g?r&   r   r   g?r   )r   rL   rM   r   r   rP   _transform_sparse_transform_dense)r*   r?   rf   r   transfs        r+   r`   AdditiveChi2Sampler.transform  s      54
 Q'
   A%"%""a'"%""a'"% ; 
 #22O
 ,2''t7L7La**O<<r.   c           	         [        U SS9  [        XSS9nU R                  R                  R	                  5       nU Vs/ s H
  o2 SU S3PM     nn[        SU R                  5       HH  nU Vs/ s H  o2 SU SU 3PM     nnU Vs/ s H  o2 SU S	U 3PM     nnUR                  Xg-   5        MJ     [        R                  " U[        S
9$ s  snf s  snf s  snf )a$  Get output feature names for transformation.

Parameters
----------
input_features : array-like of str or None, default=None
    Only used to validate feature names with the names seen in :meth:`fit`.

Returns
-------
feature_names_out : ndarray of str objects
    Transformed feature names.
n_features_in_)
attributesT)generate_names__sqrtr   _cos_sin)r   )r   r   ri   rl   lowerrR   r   extendrJ   asarrayobject)r*   input_featuresest_namename
names_listrY   	cos_names	sin_namess           r+   get_feature_names_out)AdditiveChi2Sampler.get_feature_names_out  s      	)9:0
 >>**002<JKND
!D6/N
Kq$++,AAOP:QtfD4IPAOP:QtfD4IPi34 -
 zz*F33 L QPs   C-CCc                    U S:g  nX   n[         R                  " U 5      n[         R                  " XB-  5      XS'   U/nU[         R                  " U5      -  nSU-  U-  n[	        SU5       H  n	[         R                  " U[         R
                  " [         R                  U	-  U-  5      -  5      n
[         R                  " U 5      nU
[         R                  " X-  5      -  XS'   UR                  U5        [         R                  " U 5      nU
[         R                  " X-  5      -  XS'   UR                  U5        M     [         R                  " U5      $ )Nrz   r&   r   )rJ   
zeros_likerK   r   rR   coshr   r   appendsinrN   )r?   r   r   non_zeroX_nzX_stepX_newlog_step_nzstep_nzrY   	factor_nzs              r+   r   $AdditiveChi2Sampler._transform_dense  s
   8{q!774#9:%t4d(_,q,'A"''"%%!)o2M*N NOI]]1%F(266!/+BBFLL ]]1%F(266!/+BBFLL  ( yyr.   c                    U R                   R                  5       nU R                  R                  5       n[        R                  " U R
                  U-  5      n[        R                  " XSU4U R                  U R                  SS9nU/nU[        R                  " U R
                  5      -  nSU R
                  -  U-  n	[        SU5       H  n
[        R                  " U	[        R                  " [        R                  U
-  U-  5      -  5      nU[        R                  " X-  5      -  n[        R                  " XSU4U R                  U R                  SS9nUR                  U5        U[        R                   " X-  5      -  n[        R                  " XSU4U R                  U R                  SS9nUR                  U5        M     [        R"                  " U5      $ )NF)r9   r   r   r&   r   )indicesr   indptrrJ   rK   datarL   
csr_matrixr9   r   r   rR   r   r   r   r   r   rN   )r?   r   r   r   r   	data_stepr   r   r   r   rY   r   s               r+   r   %AdditiveChi2Sampler._transform_sparse   sh   )).."GGAFF_45	(qwwU
 %qvv6aff*.q,'A"''"%%!)o2M*N NOI!BFF1?$;;I]]V,AGG177QVF LL !BFF1?$;;I]]V,AGG177QVF LL  ( yyr.   c                 v   > [         TU ]  5       nSUl        SUR                  l        SUR                  l        U$ )NFT)rc   rd   requires_fitre   positive_onlyrf   rg   s     r+   rd   $AdditiveChi2Sampler.__sklearn_tags__?  s5    w')!(,%!%r.   )r   r   r)   )rl   rm   rn   ro   rp   r   r   r   r$   rq   rr   r,   r   rB   r`   r   staticmethodr   r   rd   rs   rt   ru   s   @r+   r   r   A  s    L^ "(AtFCD$T1d6BDI$D 
 ()$ / 5 6>,=\4>    2    < r.   r   c                   (  ^  \ rS rSr% Sr\" \" \R                  " 5       5      S1-  5      \	/\
" \SSSS9S/\
" \SSSS9S/\
" \S	SSS9S/\S/\
" \S	SSS9/S
/\S/S.r\\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U 4S jrSrU =r$ )NystroemiG  a  Approximate a kernel map using a subset of the training data.

Constructs an approximate feature map for an arbitrary kernel
using a subset of the data as basis.

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

.. versionadded:: 0.13

Parameters
----------
kernel : str or callable, default='rbf'
    Kernel map to be approximated. A callable should accept two arguments
    and the keyword arguments passed to this object as `kernel_params`, and
    should return a floating point number.

gamma : float, default=None
    Gamma parameter for the RBF, laplacian, polynomial, exponential chi2
    and sigmoid kernels. Interpretation of the default value is left to
    the kernel; see the documentation for sklearn.metrics.pairwise.
    Ignored by other kernels.

coef0 : float, default=None
    Zero coefficient for polynomial and sigmoid kernels.
    Ignored by other kernels.

degree : float, default=None
    Degree of the polynomial kernel. Ignored by other kernels.

kernel_params : dict, default=None
    Additional parameters (keyword arguments) for kernel function passed
    as callable object.

n_components : int, default=100
    Number of features to construct.
    How many data points will be used to construct the mapping.

random_state : int, RandomState instance or None, default=None
    Pseudo-random number generator to control the uniform sampling without
    replacement of `n_components` of the training data to construct the
    basis kernel.
    Pass an int for reproducible output across multiple function calls.
    See :term:`Glossary <random_state>`.

n_jobs : int, default=None
    The number of jobs to use for the computation. This works by breaking
    down the kernel matrix into `n_jobs` even slices and computing them in
    parallel.

    ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
    ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
    for more details.

    .. versionadded:: 0.24

Attributes
----------
components_ : ndarray of shape (n_components, n_features)
    Subset of training points used to construct the feature map.

component_indices_ : ndarray of shape (n_components)
    Indices of ``components_`` in the training set.

normalization_ : ndarray of shape (n_components, n_components)
    Normalization matrix needed for embedding.
    Square root of the kernel matrix on ``components_``.

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
--------
AdditiveChi2Sampler : Approximate feature map for additive chi2 kernel.
PolynomialCountSketch : Polynomial kernel approximation via Tensor Sketch.
RBFSampler : Approximate a RBF kernel feature map using random Fourier
    features.
SkewedChi2Sampler : Approximate feature map for "skewed chi-squared" kernel.
sklearn.metrics.pairwise.kernel_metrics : List of built-in kernels.

References
----------
* Williams, C.K.I. and Seeger, M.
  "Using the Nystroem method to speed up kernel machines",
  Advances in neural information processing systems 2001

* T. Yang, Y. Li, M. Mahdavi, R. Jin and Z. Zhou
  "Nystroem Method vs Random Fourier Features: A Theoretical and Empirical
  Comparison",
  Advances in Neural Information Processing Systems 2012

Examples
--------
>>> from sklearn import datasets, svm
>>> from sklearn.kernel_approximation import Nystroem
>>> X, y = datasets.load_digits(n_class=9, return_X_y=True)
>>> data = X / 16.
>>> clf = svm.LinearSVC()
>>> feature_map_nystroem = Nystroem(gamma=.2,
...                                 random_state=1,
...                                 n_components=300)
>>> data_transformed = feature_map_nystroem.fit_transform(data)
>>> clf.fit(data_transformed, y)
LinearSVC()
>>> clf.score(data_transformed, y)
0.9987...
precomputedr   Nr   r   r   r   r   kernelr    r"   r!   kernel_paramsr#   r   n_jobsr$   r'   )r    r"   r!   r   r#   r   r   c                d    Xl         X l        X0l        X@l        XPl        X`l        Xpl        Xl        g r)   r   )	r*   r   r    r"   r!   r   r#   r   r   s	            r+   r,   Nystroem.__init__  s/     

*((r.   Tr/   c                 N   [        XSS9n[        U R                  5      nUR                  S   nU R                  U:  a  Un[
        R                  " S5        OU R                  n[        XE5      nUR                  U5      nUSU nX   n[        U4U R                  SU R                  S.U R                  5       D6n	[        U	5      u  pn[        R                  " US5      n[        R                   " U
[        R"                  " U5      -  U5      U l        Xl        Xpl        XPl        U $ )	a  Fit estimator to data.

Samples a subset of training points, computes kernel
on these and computes normalization matrix.

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

y : array-like, shape (n_samples,) or (n_samples, n_outputs),                 default=None
    Target values (None for unsupervised transformations).

Returns
-------
self : object
    Returns the instance itself.
r   r3   r   zn_components > n_samples. This is not possible.
n_components was set to n_samples, which results in inefficient evaluation of the full kernel.NTmetricfilter_paramsr   g-q=)r   r   r   r9   r#   warningswarnminpermutationr   r   r   _get_kernel_paramsr   rJ   maximumdotrK   normalization_components_component_indices_r>   )r*   r?   r@   rnd	n_samplesr#   inds
basis_indsbasisbasis_kernelUSVs                r+   rB   Nystroem.fit  s   , $7 !2!23GGAJ	 y($LMMA  ,,L93y)-<(
'
;;;;	

 %%'
 l#aJJq%  ffQ^Q7 ",+r.   c                     [        U 5        [        XSSS9nU R                  5       n[        UU R                  4U R
                  SU R                  S.UD6n[        R                  " X0R                  R                  5      $ )a2  Apply feature map to X.

Computes an approximate feature map using the kernel
between some training points and X.

Parameters
----------
X : array-like of shape (n_samples, n_features)
    Data to transform.

Returns
-------
X_transformed : ndarray of shape (n_samples, n_components)
    Transformed data.
r   FrE   Tr   )r   r   r   r   r  r   r   rJ   r   r  T)r*   r?   r   embeddeds       r+   r`   Nystroem.transform  s}      	$eD//1#
 ;;;;
 
 vvh 3 3 5 566r.   c                 N   U R                   nUc  0 n[        U R                  5      (       dG  U R                  S:w  a7  [        U R                      H  n[	        X5      c  M  [	        X5      X'   M      U$ U R
                  c  U R                  c  U R                  b  [        S5      eU$ )Nr   zWDon't pass gamma, coef0 or degree to Nystroem if using a callable or precomputed kernel)	r   callabler   r   getattrr    r"   r!   rP   )r*   paramsparams      r+   r   Nystroem._get_kernel_params8  s    ##>F$$)E&t{{34'3$+D$8FM 4  

&::);;* ,  r.   c                 l   > [         TU ]  5       nSUR                  l        SS/UR                  l        U$ r   r   rg   s     r+   rd   Nystroem.__sklearn_tags__N  r   r.   )r>   r"   r  r  r!   r    r   r   r#   r   r  r   )rbfr)   )rl   rm   rn   ro   rp   r   setr   keysr  r   r   rq   r   r$   rr   r,   r   rB   r`   r   rd   rs   rt   ru   s   @r+   r   r   G  s    qj s499;<NO
 4D8$?4tI>ED!T&94@!(AtFCD'(T"$D    * 59 69v7<, r.   r   )(rp   r   numbersr   r   numpyrJ   scipy.sparserf   rL   	scipy.fftr   r   scipy.linalgr   baser	   r
   r   r   metrics.pairwiser   r   r   utilsr   utils._param_validationr   r   utils.extmathr   utils.validationr   r   r   r   rw   r   r   r    r.   r+   <module>r)     s    U
  "      Y X % 9 * R#%5}Rjj02BM jZ]#%5}]@C*M CLK.0@- Kr.   