`L i8dZddlZddlmZmZddlZddlmZ ddl m Z m Z ddl mZddlmZmZmZmZddlmZmZmZdd lmZdd lmZmZdd lmZdd lm Z m!Z!m"Z"Gd deeeZ#GddeeeZ$GddeeeZ%GddeeZ&GddeeeZ'y)zOApproximate kernel feature maps based on Fourier transforms and count sketches.N)IntegralReal)fftifft)svd) BaseEstimatorClassNamePrefixFeaturesOutMixinTransformerMixin _fit_context) KERNEL_PARAMSPAIRWISE_KERNEL_FUNCTIONSpairwise_kernels)check_random_state)Interval StrOptions)safe_sparse_dot)_check_feature_names_incheck_is_fitted validate_datac eZdZUdZeedddgeedddgeedddgeedddgdgd Zee d <d d dd dd dZ e dddZ dZ fdZxZS)PolynomialCountSketcha Polynomial kernel approximation via Tensor Sketch. Implements Tensor Sketch, which approximates the feature map of the polynomial kernel:: K(X, Y) = (gamma * + 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 `. .. 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 `. 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` rNleftclosedrneither random_stategammadegreecoef0 n_componentsr_parameter_constraints?dcJ||_||_||_||_||_yNr)selfrr r!r"rs b/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sklearn/kernel_approximation.py__init__zPolynomialCountSketch.__init__s)   ((Tprefer_skip_nested_validationc^t||d}t|j}|jd}|jdk7r|dz }|j d|j |j|f|_|jddg|j|f|_ |j |_ |S)aFit 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_sparserr)highsize)ar4) rrrshaper!randintr"r indexHash_choicebitHash__n_features_out)r)Xyr n_featuress r*fitzPolynomialCountSketch.fits, $ 7)$*;*;< WWQZ ::? !OJ&.. D%%T[[*,E/ %++r1gT[[*DDF4 7==+, Qt{{+QA!%A!6J#}}QT2H"1a#3471a4=8PP4Q Q!aTJ"$''*<1"Eggd#:MN r,cFt|}d|j_|S)NT)super__sklearn_tags__ input_tagssparser)tags __class__s r*r`z&PolynomialCountSketch.__sklearn_tags__s!w')!% r,r(__name__ __module__ __qualname____doc__rrrr#dict__annotations__r+r r@r]r` __classcell__res@r*rrsUp4D89Haf=>4tI>?!(AtFCD'( $D1ACd)5"6"H=~r,rceZdZUdZedheedddgeedddgdgd Ze e d <d d dd d Z e dddZ dZfdZxZS) RBFSamplera 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 `. 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 `. 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 scaleNrrrrrr"rr#r$r&c.||_||_||_yr(rs)r)rr"rs r*r+zRBFSampler.__init__Ps ((r,Tr-cht||d}t|j}|jd}t j |}|j dk(rZ|r3|j|j|jdzz n|j}|dk7rd||zz nd|_ n|j |_ d|jzd z|j||jf z|_ |jddtj z|j |_|j$tj&k(rX|jj)|j$d |_ |j"j)|j$d |_|j|_|S) aMFit 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. csrr1rrqr%rr$@?r4Fcopy)rrrr7rIrJrmultiplymeanvar_gammanormalr"random_weights_uniformrGpirandom_offset_dtypefloat32astyper<)r)r=r>rr?rbX_vars r*r@zRBFSampler.fitUsj* $ 7)$*;*;< WWQZ Q :: @FQZZ]((*affh1_#>qwwU#>#SD "&"5"5"<"`. 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 `. 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 Nrrrrr skewednessr"rr#r$r&c.||_||_||_yr(r)r)rr"rs r*r+zSkewedChi2Sampler.__init__s$((r,Tr-ct||}t|j}|jd}|j ||j f}dt jz t jt jt jdz |zz|_ |j ddt jz|j |_ |jt jk(rX|jj|jd|_ |jj|jd|_ |j |_|S) 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. rryr$rwrr%Frz)rrrr7rr"rGrlogtanrrrrrr<)r)r=r>rr?rs r*r@zSkewedChi2Sampler.fits* $ ")$*;*;< WWQZ &&Z9J9J,K&L"RUU{RVVBFF2553;;P4Q-RR*221a"%%idFWFW2X 77bjj $(#7#7#>#>qwwU#>#SD "&"5"5"<"e  $//! ! & & (RS S T__ q! $Q(<(<= d)))  z:&bggclRWWT->->%??? r,cJt|}ddg|j_|S)Nrr)r_r`rrrcs r*r`z"SkewedChi2Sampler.__sklearn_tags__;s(w')1:I0F- r,r(rfrns@r*rrszFR dDCD!(AtFCD'($D &)s) 5#6#J<r,rceZdZUdZeedddgeeddddgdZee d<d ddd Z e d dd Z dZ ddZedZedZfdZxZS)AdditiveChi2Samplera 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 `. 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" `_ 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... rNrrr sample_stepssample_intervalr#r%c ||_||_yr(r)r)rrs r*r+zAdditiveChi2Sampler.__init__s(.r,Tr-cnt||dd}|j|jdvr td|S)aOnly 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. rvT)r2ensure_non_negative)rr%HIf sample_steps is not in [1, 2, 3], you need to provide sample_interval)rrrrM)r)r=r>s r*r@zAdditiveChi2Sampler.fitsF, $D Q    'D,=,=Y,N7   r,cZt||ddd}tj|}|jA|jdk(rd}n;|jdk(rd}n)|jd k(rd }nt d |j}|r |j n |j}|||j|S) aApply 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. rvFT)r2rCrrg?r%rxrg?r)rrIrJrrrM_transform_sparse_transform_dense)r)r=rbrtransfs r*r]zAdditiveChi2Sampler.transforms  !54 Q    '   A%"%""a'"%""a'"% ; #22O ,2''t7L7La**O<>**002,=\4>  2  <r,rc 6eZdZUdZeeejdhzege e ddddge e ddddge e ddddge dge e dddgd ge dgd Z e ed < dddddd ddd dZedddZdZdZfdZxZS)NystroemaApproximate 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 `. .. 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 `. 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 ` 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... precomputedrNrrrrrkernelrr!r kernel_paramsr"rn_jobsr#r&)rr!r rr"rrct||_||_||_||_||_||_||_||_yr(r) r)rrr!r rr"rrs r*r+zNystroem.__init__s?    *(( r,Tr-cXt||d}t|j}|jd}|j|kDr|}t j dn |j}t||}|j|}|d|}||}t|f|jd|jd|j} t| \} } } tj| d} tj | tj"| z | |_||_||_||_|S) asFit 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. rvr1rzn_components > n_samples. This is not possible. n_components was set to n_samples, which results in inefficient evaluation of the full kernel.NTmetric filter_paramsrg-q=)rrrr7r"warningswarnmin permutationrrr_get_kernel_paramsrrGmaximumdotrHnormalization_ components_component_indices_r<) r)r=r>rnd n_samplesr"inds basis_indsbasis basis_kernelUSVs r*r@z Nystroem.fits&, $ 7 !2!23GGAJ    y ($L MMA  ,,L9l3 y)-<( * '  ;;;;  %%'  l#1a JJq%  ffQ^Q7 ",+ r,ct|t||dd}|j}t||jf|j d|j d|}tj||jjS)aApply 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. rvFrBTr) rrrrrrrrGrrT)r)r=rembeddeds r*r]zNystroem.transforms  $e D//1 #    ;;;;    vvh 3 3 5 566r,c8|j}|i}t|jsE|jdk7r6t|jD]}t ||t ||||< |S|j |j |j td|S)NrzWDon't pass gamma, coef0 or degree to Nystroem if using a callable or precomputed kernel) rcallablerr getattrrr!r rM)r)paramsparams r*rzNystroem._get_kernel_params8s## >F $ )E&t{{3 94'3$+D%$8F5M 9  &::);;* ,  r,clt|}d|j_ddg|j_|Srrrcs r*r`zNystroem.__sklearn_tags__Nrr,)rbfr()rgrhrirjrsetrkeysrrrrkrr#rlr+r r@r]rr`rmrns@r*rrGsqj s9499;< N O  4D8$?4tI>ED!T&94@!(AtFCD'(T" $D  *5969v7<,r,r)(rjrnumbersrrnumpyrG scipy.sparserbrI scipy.fftrr scipy.linalgrbaser r r r metrics.pairwiser rrutilsrutils._param_validationrr utils.extmathrutils.validationrrrrrprrrr,r*r sU " YX%9*R#%5}Rjj02BMjZ]#%5}]@C*MCLK.0@-Kr,