`L i@DdZddlZddlmZmZddlZddlZddlm Z ddl m Z m Z m Z mZmZddlmZmZmZddlmZdd lmZdd lmZmZmZmZdd lmZmZm Z dd l!m"Z"dd l#m$Z$m%Z%ddl&m'Z'm(Z(ddgZ)ddZ*dZ+ddZ,GddZ-Gdde eee Z.Gdde-e e Z/y)z+Linear and quadratic discriminant analysis.N)IntegralReal)linalg) BaseEstimatorClassifierMixinClassNamePrefixFeaturesOutMixinTransformerMixin _fit_context)empirical_covariance ledoit_wolfshrunk_covariance)LinearClassifierMixin)StandardScaler)_expitdevice get_namespacesize) HasMethodsInterval StrOptions)softmax)check_classification_targets unique_labels)check_is_fitted validate_dataLinearDiscriminantAnalysisQuadraticDiscriminantAnalysiscN||dn|}t|tr|dk(rqt}|j|}t |d}|j ddt jf|z|j t jddfz}|S|dk(r2t|}|St|trtt||}S||dk7r td|j|t|ds"td|jjz|j }|S)aqEstimate covariance matrix (using optional covariance_estimator). Parameters ---------- X : array-like of shape (n_samples, n_features) Input data. shrinkage : {'empirical', 'auto'} or float, default=None Shrinkage parameter, possible values: - None or 'empirical': no shrinkage (default). - 'auto': automatic shrinkage using the Ledoit-Wolf lemma. - float between 0 and 1: fixed shrinkage parameter. Shrinkage parameter is ignored if `covariance_estimator` is not None. covariance_estimator : estimator, default=None If not None, `covariance_estimator` is used to estimate the covariance matrices instead of relying on the empirical covariance estimator (with potential shrinkage). The object should have a fit method and a ``covariance_`` attribute like the estimators in :mod:`sklearn.covariance``. if None the shrinkage parameter drives the estimate. .. versionadded:: 0.24 Returns ------- s : ndarray of shape (n_features, n_features) Estimated covariance matrix. N empiricalautorz[covariance_estimator and shrinkage parameters are not None. Only one of the two can be set. covariance_z(%s does not have a covariance_ attribute) isinstancestrr fit_transformr scale_npnewaxisr rr ValueErrorfithasattr __class____name__r")X shrinkagecovariance_estimatorscss c/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sklearn/discriminant_analysis.py_covr4 s8>##,#4K) i %F"#%$$Q'N1%IIam,q0299RZZ]3KK$ H#k)(+ H 4 (!"6q"99EA H  Y!^@    #+];:&0099:  ! , , Hct|\}}|j|\}}|j|jd|jdft ||j }|r?t |jdD]"}|j|||k(d||ddf<$|Stj|}tjj|||||dddfz}|S)aACompute class means. Parameters ---------- X : array-like of shape (n_samples, n_features) Input data. y : array-like of shape (n_samples,) or (n_samples, n_targets) Target values. Returns ------- means : array-like of shape (n_classes, n_features) Class means. rr)rdtypeaxisN) runique_inversezerosshaperr7rangemeanr'bincountaddat)r.yxpis_array_api_compliantclassesmeansicnts r3 _class_meansrI\s "/q!1B""1%JGQ HHgmmA& 3F1IQWWH UEw}}Q'( 5A''!AF)!'4E!Q$K 5 Lkk!n  %A QW Lr5c $tj|}tj|jd|jdf}t |D]:\}}|||k(ddf} |||tj t | ||zz }<|S)a Compute weighted within-class covariance matrix. The per-class covariance are weighted by the class priors. Parameters ---------- X : array-like of shape (n_samples, n_features) Input data. y : array-like of shape (n_samples,) or (n_samples, n_targets) Target values. priors : array-like of shape (n_classes,) Class priors. shrinkage : 'auto' or float, default=None Shrinkage parameter, possible values: - None: no shrinkage (default). - 'auto': automatic shrinkage using the Ledoit-Wolf lemma. - float between 0 and 1: fixed shrinkage parameter. Shrinkage parameter is ignored if `covariance_estimator` is not None. covariance_estimator : estimator, default=None If not None, `covariance_estimator` is used to estimate the covariance matrices instead of relying the empirical covariance estimator (with potential shrinkage). The object should have a fit method and a ``covariance_`` attribute like the estimators in sklearn.covariance. If None, the shrinkage parameter drives the estimate. .. versionadded:: 0.24 Returns ------- cov : array-like of shape (n_features, n_features) Weighted within-class covariance matrix r)r<N)r'uniquer;r< enumerate atleast_2dr4) r.rBpriorsr/r0rEcovidxgroupXgs r3 _class_covrS|sNiilG ((!''!*aggaj1 2C(V U qEz1}  vc{R]]4I?S+TUUUV Jr5c(eZdZdZdZdZdZdZy)#DiscriminantAnalysisPredictionMixinzBMixin class for QuadraticDiscriminantAnalysis and NearestCentroid.c~|j|}t|jdk(r|dddf|dddfz S|S)a Apply decision function to an array of samples. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Array of samples (test vectors). Returns ------- y_scores : ndarray of shape (n_samples,) or (n_samples, n_classes) Decision function values related to each class, per sample. In the two-class case, the shape is `(n_samples,)`, giving the log likelihood ratio of the positive class. Nrr)_decision_functionlenclasses_)selfr.y_scoress r3decision_functionz5DiscriminantAnalysisPredictionMixin.decision_functionsE**1- t}}  "AqD>HQTN2 2r5cz|j|}|jj|jdS)aPerform classification on an array of vectors `X`. Returns the class label for each sample. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Input vectors, where `n_samples` is the number of samples and `n_features` is the number of features. Returns ------- y_pred : ndarray of shape (n_samples,) Class label for each sample. rr8)rXrZtakeargmax)r[r.scoress r3predictz+DiscriminantAnalysisPredictionMixin.predicts4 ((+}}!!&--Q-"788r5cJtj|j|S)aEstimate class probabilities. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Input data. Returns ------- y_proba : ndarray of shape (n_samples, n_classes) Probability estimate of the sample for each class in the model, where classes are ordered as they are in `self.classes_`. )r'exppredict_log_proba)r[r.s r3 predict_probaz1DiscriminantAnalysisPredictionMixin.predict_probasvvd,,Q/00r5c|j|}||jdddtjfz }|tjtj |j dddtjfz S)a:Estimate log class probabilities. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Input data. Returns ------- y_log_proba : ndarray of shape (n_samples, n_classes) Estimated log probabilities. rr8N)rXmaxr'r(logrdsum)r[r.ralog_likelihoods r3rez5DiscriminantAnalysisPredictionMixin.predict_log_probasu((+&**!*"4Q ]"CC FF> " & &A & .q"**} =!   r5N)r- __module__ __qualname____doc__r]rbrfrer5r3rUrUsL(9&1  r5rUc "eZdZUdZehdgedheeddddgeeddd dgd dgd geeddd ged dgd Z e e d< ddZ dZ dZdZeddZdZdZdZfdZfdZxZS)raLinear Discriminant Analysis. A classifier with a linear decision boundary, generated by fitting class conditional densities to the data and using Bayes' rule. The model fits a Gaussian density to each class, assuming that all classes share the same covariance matrix. The fitted model can also be used to reduce the dimensionality of the input by projecting it to the most discriminative directions, using the `transform` method. .. versionadded:: 0.17 For a comparison between :class:`~sklearn.discriminant_analysis.LinearDiscriminantAnalysis` and :class:`~sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis`, see :ref:`sphx_glr_auto_examples_classification_plot_lda_qda.py`. Read more in the :ref:`User Guide `. Parameters ---------- solver : {'svd', 'lsqr', 'eigen'}, default='svd' Solver to use, possible values: - 'svd': Singular value decomposition (default). Does not compute the covariance matrix, therefore this solver is recommended for data with a large number of features. - 'lsqr': Least squares solution. Can be combined with shrinkage or custom covariance estimator. - 'eigen': Eigenvalue decomposition. Can be combined with shrinkage or custom covariance estimator. .. versionchanged:: 1.2 `solver="svd"` now has experimental Array API support. See the :ref:`Array API User Guide ` for more details. shrinkage : 'auto' or float, default=None Shrinkage parameter, possible values: - None: no shrinkage (default). - 'auto': automatic shrinkage using the Ledoit-Wolf lemma. - float between 0 and 1: fixed shrinkage parameter. This should be left to None if `covariance_estimator` is used. Note that shrinkage works only with 'lsqr' and 'eigen' solvers. For a usage example, see :ref:`sphx_glr_auto_examples_classification_plot_lda.py`. priors : array-like of shape (n_classes,), default=None The class prior probabilities. By default, the class proportions are inferred from the training data. n_components : int, default=None Number of components (<= min(n_classes - 1, n_features)) for dimensionality reduction. If None, will be set to min(n_classes - 1, n_features). This parameter only affects the `transform` method. For a usage example, see :ref:`sphx_glr_auto_examples_decomposition_plot_pca_vs_lda.py`. store_covariance : bool, default=False If True, explicitly compute the weighted within-class covariance matrix when solver is 'svd'. The matrix is always computed and stored for the other solvers. .. versionadded:: 0.17 tol : float, default=1.0e-4 Absolute threshold for a singular value of X to be considered significant, used to estimate the rank of X. Dimensions whose singular values are non-significant are discarded. Only used if solver is 'svd'. .. versionadded:: 0.17 covariance_estimator : covariance estimator, default=None If not None, `covariance_estimator` is used to estimate the covariance matrices instead of relying on the empirical covariance estimator (with potential shrinkage). The object should have a fit method and a ``covariance_`` attribute like the estimators in :mod:`sklearn.covariance`. if None the shrinkage parameter drives the estimate. This should be left to None if `shrinkage` is used. Note that `covariance_estimator` works only with 'lsqr' and 'eigen' solvers. .. versionadded:: 0.24 Attributes ---------- coef_ : ndarray of shape (n_features,) or (n_classes, n_features) Weight vector(s). intercept_ : ndarray of shape (n_classes,) Intercept term. covariance_ : array-like of shape (n_features, n_features) Weighted within-class covariance matrix. It corresponds to `sum_k prior_k * C_k` where `C_k` is the covariance matrix of the samples in class `k`. The `C_k` are estimated using the (potentially shrunk) biased estimator of covariance. If solver is 'svd', only exists when `store_covariance` is True. explained_variance_ratio_ : ndarray of shape (n_components,) Percentage of variance explained by each of the selected components. If ``n_components`` is not set then all components are stored and the sum of explained variances is equal to 1.0. Only available when eigen or svd solver is used. means_ : array-like of shape (n_classes, n_features) Class-wise means. priors_ : array-like of shape (n_classes,) Class priors (sum to 1). scalings_ : array-like of shape (rank, n_classes - 1) Scaling of the features in the space spanned by the class centroids. Only available for 'svd' and 'eigen' solvers. xbar_ : array-like of shape (n_features,) Overall mean. Only present if solver is 'svd'. classes_ : array-like of shape (n_classes,) Unique class labels. 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 -------- QuadraticDiscriminantAnalysis : Quadratic Discriminant Analysis. Examples -------- >>> import numpy as np >>> from sklearn.discriminant_analysis import LinearDiscriminantAnalysis >>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]]) >>> y = np.array([1, 1, 1, 2, 2, 2]) >>> clf = LinearDiscriminantAnalysis() >>> clf.fit(X, y) LinearDiscriminantAnalysis() >>> print(clf.predict([[-0.8, -1]])) [1] >svdlsqreigenr!rrbothclosedNleft array-likebooleanr*)solverr/ n_componentsrNstore_covariancetolr0_parameter_constraintsFcf||_||_||_||_||_||_||_yN)rzr/rNr{r|r}r0)r[rzr/rNr{r|r}r0s r3__init__z#LinearDiscriminantAnalysis.__init__s8 " ( 0$8!r5ct|||_t|||j|||_t j |j|jjdj|_dtjtj|j|jjztj|jz|_ y)aLeast squares solver. The least squares solver computes a straightforward solution of the optimal decision rule based directly on the discriminant functions. It can only be used for classification (with any covariance estimator), because estimation of eigenvectors is not performed. Therefore, dimensionality reduction with the transform is not supported. Parameters ---------- X : array-like of shape (n_samples, n_features) Training data. y : array-like of shape (n_samples,) or (n_samples, n_classes) Target values. shrinkage : 'auto', float or None Shrinkage parameter, possible values: - None: no shrinkage. - 'auto': automatic shrinkage using the Ledoit-Wolf lemma. - float between 0 and 1: fixed shrinkage parameter. Shrinkage parameter is ignored if `covariance_estimator` i not None covariance_estimator : estimator, default=None If not None, `covariance_estimator` is used to estimate the covariance matrices instead of relying the empirical covariance estimator (with potential shrinkage). The object should have a fit method and a ``covariance_`` attribute like the estimators in sklearn.covariance. if None the shrinkage parameter drives the estimate. .. versionadded:: 0.24 Notes ----- This solver is based on [1]_, section 2.6.2, pp. 39-41. References ---------- .. [1] R. O. Duda, P. E. Hart, D. G. Stork. Pattern Classification (Second Edition). John Wiley & Sons, Inc., New York, 2001. ISBN 0-471-05669-3. rN)rImeans_rSpriors_r"rlstsqTcoef_r'diagdotri intercept_)r[r.rBr/r0s r3 _solve_lstsqz'LinearDiscriminantAnalysis._solve_lstsqs^#1a( % q$,, +? \\$"2"2DKKMMB1EGG  TZZ\\)J!KKbff LLO  r5ct|||_t|||j|||_|j}t |||}||z }t j||\}} tj|tj|z dddd|j|_ | ddtj|dddf} | |_tj|j| j| j |_dtj$tj|j|j"j ztj&|jz|_y)aEigenvalue solver. The eigenvalue solver computes the optimal solution of the Rayleigh coefficient (basically the ratio of between class scatter to within class scatter). This solver supports both classification and dimensionality reduction (with any covariance estimator). Parameters ---------- X : array-like of shape (n_samples, n_features) Training data. y : array-like of shape (n_samples,) or (n_samples, n_targets) Target values. shrinkage : 'auto', float or None Shrinkage parameter, possible values: - None: no shrinkage. - 'auto': automatic shrinkage using the Ledoit-Wolf lemma. - float between 0 and 1: fixed shrinkage constant. Shrinkage parameter is ignored if `covariance_estimator` i not None covariance_estimator : estimator, default=None If not None, `covariance_estimator` is used to estimate the covariance matrices instead of relying the empirical covariance estimator (with potential shrinkage). The object should have a fit method and a ``covariance_`` attribute like the estimators in sklearn.covariance. if None the shrinkage parameter drives the estimate. .. versionadded:: 0.24 Notes ----- This solver is based on [1]_, section 3.8.3, pp. 121-124. References ---------- .. [1] R. O. Duda, P. E. Hart, D. G. Stork. Pattern Classification (Second Edition). John Wiley & Sons, Inc., New York, 2001. ISBN 0-471-05669-3. Nr)rIrrSrr"r4reighr'sortrj_max_componentsexplained_variance_ratio_argsort scalings_rrrrrir) r[r.rBr/r0SwStSbevalsevecss r3 _solve_eigenz'LinearDiscriminantAnalysis._solve_eigens3Z#1a( % q$,, +?    !Y 4 5 "W{{2r* u)+1F)G")M "d""* &aE*4R4001VVDKK/33EGG<  TZZ\\)J!KKbff LLO  r5ct|\}}|r|jj}ntjj}|j\}}|j jd}t |||_|jrt|||j|_ g} t|j D]2\} } ||| k(} | j| |j| ddfz 4|j|jz|_|j| d} |j!| d} d| | dk(<|j#d||z z |j$t'|}|j)|| | z z}||d\}}}|j+|j-||j.kD|j0}|d|ddf| z j2|d|z }|dk(rdnd|dz z }|j)||jz|z|j|jz j2zj2|z}||d\}}}|j4dk(r#|j7d |j$ |_n,|d z|j+|d zz d|j4|_|j+|j-||j.|dzkD|j0}||j2ddd|fz|_|j|jz |j:z}d |j+|d zdz|j=|jz|_||j:j2z|_ |xj>|j|j@j2zzc_y) zSVD solver. Parameters ---------- X : array-like of shape (n_samples, n_features) Training data. y : array-like of shape (n_samples,) or (n_samples, n_targets) Target values. rNr8?)r7rF full_matricesr)rr7rWr)!rrrqscipyr<rZrIrr|rSrr"rLappendxbar_concatstdasarrayr7rsqrtrjastyper}int32rremptyrrrirr)r[r.rBrCrDrq n_samples n_features n_classesXcrPrQrRrfacUSVtrankscalings_coefs r3 _solve_svdz%LinearDiscriminantAnalysis._solve_svd1s>&31%5" " !))--C,,""C ! :MM''* "1a(  )!Q =D  #DMM2 0JC1:B IIb4;;sAv.. / 0\\DKK/ YYrY "ffRaf C1H jj I 56aggfUVijX GGCLBH %q.1bvvbiiDHH bhh78uuaxL3&))AetH4!^c A )> WWi$,,.#5 64;;;S:V:V V !h  q.1b   1 $-/XXd!''X-JD *./dRVVAqD\.A&$&&.D *vvbiiDHHqtO 3RXX>?!BDDETEN2 djj(DNN:aa!88266$,,;OODNN,,,  4:: 44r5prefer_skip_nested_validationc.t|\}}t|||d|j|jg\}}t ||_|j \}}|j j d}||k(r td|jO|j|\}}|j||jt|j dz |_ n,|j|j|j|_ |j|jdkr td|j!|j#|jdz d kDrFt%j&d t(|j|jj#z |_ t+|d z |j d }|j,||_n+|j,|kDr td |j,|_|j0d k(rA|j2 t5d|j6 td|j9||nq|j0dk(r*|j;|||j2|j6n8|j0dk(r)|j=|||j2|j6t?|j dk(r|j|j@d ddf|j@dddfz |j} |jC| d|_ |j|jDd |jDdz |j} |jC| d|_"|j.|_#|S)aFit the Linear Discriminant Analysis model. .. versionchanged:: 0.19 `store_covariance` and `tol` has been moved to main constructor. Parameters ---------- X : array-like of shape (n_samples, n_features) Training data. y : array-like of shape (n_samples,) Target values. Returns ------- self : object Fitted estimator. rW)ensure_min_samplesr7rz>The number of samples must be more than the number of classes.Nrzpriors must be non-negativergh㈵>z)The priors do not sum to 1. RenormalizingrzBn_components cannot be larger than min(n_features, n_classes - 1).rqz*shrinkage not supported with 'svd' solver.zIcovariance estimator is not supported with svd solver. Try another solverrr)r/r0rs)rr)r)$rrfloat64float32rrZr<r)rN unique_countsrr7floatrranyabsrjwarningswarn UserWarningminr{rrzr/NotImplementedErrorr0rrrrrreshaper_n_features_out) r[r.rBrCrrrcntsmax_componentsrrs r3r*zLinearDiscriminantAnalysis.fit{s.a A !Q1RZZ4L 1&a( ww 1MM''*  !P  ;; &&q)GAt99T1773eAGGAJ6GGDL::dkk:ADL 66$,," #:; ; 66"&&&, - 4 MME{ S<<$,,*:*:*<1 X$(#4#4D ;;% ~~))*VWW((4 : OOAq ! [[F "   ..%)%>%>   [[G #   ..%)%>%>    ! #JJtzz!Q$/$**QT2BB!''JREE73DJ"T__Q%77qww$J!jjT:DO#33 r5cB|jdk(r tdt|t|\}}t ||d}|jdk(r||j z |j z}n|jdk(r||j z}ddd|jfS)aProject data to maximize class separation. Parameters ---------- X : array-like of shape (n_samples, n_features) Input data. Returns ------- X_new : ndarray of shape (n_samples, n_components) or (n_samples, min(rank, n_components)) Transformed data. In the case of the 'svd' solver, the shape is (n_samples, min(rank, n_components)). rrzCtransform not implemented for 'lsqr' solver (use 'svd' or 'eigen').FresetrqrsN)rzrrrrrrr)r[r.rCrX_news r3 transformz$LinearDiscriminantAnalysis.transforms ;;& %U  a A $ / ;;% ^t~~5E [[G #&EQ.$....//r5ct|t|\}}|j|}t|jdk(r$t ||}|j d|z |gdSt|S)aEstimate probability. Parameters ---------- X : array-like of shape (n_samples, n_features) Input data. Returns ------- C : ndarray of shape (n_samples, n_classes) Estimated probabilities. rWrr8)rrr]rrZrstackr)r[r.rCrDdecisionprobas r3rfz(LinearDiscriminantAnalysis.predict_probasp %21%5" "))!,  ! #8R(E88QY.Q87 78$ $r5ct|\}}|j|}|j|j}t |dr |j }n |j }||dk(xx|z cc<|j|S)aEstimate log probability. Parameters ---------- X : array-like of shape (n_samples, n_features) Input data. Returns ------- C : ndarray of shape (n_samples, n_classes) Estimated log probabilities. smallest_normal)rrffinfor7r+rtinyri)r[r.rCr predictioninfors r3rez,LinearDiscriminantAnalysis.predict_log_probas{a A''* xx (() 4* +"22O#iiO:$%8%vvj!!r5c"t||S)aApply decision function to an array of samples. The decision function is equal (up to a constant factor) to the log-posterior of the model, i.e. `log p(y = k | x)`. In a binary classification setting this instead corresponds to the difference `log p(y = 1 | x) - log p(y = 0 | x)`. See :ref:`lda_qda_math`. Parameters ---------- X : array-like of shape (n_samples, n_features) Array of samples (test vectors). Returns ------- y_scores : ndarray of shape (n_samples,) or (n_samples, n_classes) Decision function values related to each class, per sample. In the two-class case, the shape is `(n_samples,)`, giving the log likelihood ratio of the positive class. superr]r[r.r,s r3r]z,LinearDiscriminantAnalysis.decision_function*s*w(++r5c2t|}d|_|S)NT)r__sklearn_tags__array_api_support)r[tagsr,s r3rz+LinearDiscriminantAnalysis.__sklearn_tags__Asw')!% r5)rqNNNF-C6?N)r-rlrmrnrrrrrr~dict__annotations__rrrrr r*rrfrer]r __classcell__r,s@r3rrs Zz678 &*HT1a,OQUV!(AtFCTJ&&Kq$v67!+E!2D 9$D !9$6 p@ DH5T&+[ [z0<%,"4,.r5c eZdZUdZddgeedddgdgeeddd gd Zeed <dd d dd dZ e ddZ dZ fdZ fdZfdZfdZxZS)raSQuadratic Discriminant Analysis. A classifier with a quadratic decision boundary, generated by fitting class conditional densities to the data and using Bayes' rule. The model fits a Gaussian density to each class. .. versionadded:: 0.17 For a comparison between :class:`~sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis` and :class:`~sklearn.discriminant_analysis.LinearDiscriminantAnalysis`, see :ref:`sphx_glr_auto_examples_classification_plot_lda_qda.py`. Read more in the :ref:`User Guide `. Parameters ---------- priors : array-like of shape (n_classes,), default=None Class priors. By default, the class proportions are inferred from the training data. reg_param : float, default=0.0 Regularizes the per-class covariance estimates by transforming S2 as ``S2 = (1 - reg_param) * S2 + reg_param * np.eye(n_features)``, where S2 corresponds to the `scaling_` attribute of a given class. store_covariance : bool, default=False If True, the class covariance matrices are explicitly computed and stored in the `self.covariance_` attribute. .. versionadded:: 0.17 tol : float, default=1.0e-4 Absolute threshold for the covariance matrix to be considered rank deficient after applying some regularization (see `reg_param`) to each `Sk` where `Sk` represents covariance matrix for k-th class. This parameter does not affect the predictions. It controls when a warning is raised if the covariance matrix is not full rank. .. versionadded:: 0.17 Attributes ---------- covariance_ : list of len n_classes of ndarray of shape (n_features, n_features) For each class, gives the covariance matrix estimated using the samples of that class. The estimations are unbiased. Only present if `store_covariance` is True. means_ : array-like of shape (n_classes, n_features) Class-wise means. priors_ : array-like of shape (n_classes,) Class priors (sum to 1). rotations_ : list of len n_classes of ndarray of shape (n_features, n_k) For each class k an array of shape (n_features, n_k), where ``n_k = min(n_features, number of elements in class k)`` It is the rotation of the Gaussian distribution, i.e. its principal axis. It corresponds to `V`, the matrix of eigenvectors coming from the SVD of `Xk = U S Vt` where `Xk` is the centered matrix of samples from class k. scalings_ : list of len n_classes of ndarray of shape (n_k,) For each class, contains the scaling of the Gaussian distributions along its principal axes, i.e. the variance in the rotated coordinate system. It corresponds to `S^2 / (n_samples - 1)`, where `S` is the diagonal matrix of singular values from the SVD of `Xk`, where `Xk` is the centered matrix of samples from class k. classes_ : ndarray of shape (n_classes,) Unique class labels. 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 -------- LinearDiscriminantAnalysis : Linear Discriminant Analysis. Examples -------- >>> from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis >>> import numpy as np >>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]]) >>> y = np.array([1, 1, 1, 2, 2, 2]) >>> clf = QuadraticDiscriminantAnalysis() >>> clf.fit(X, y) QuadraticDiscriminantAnalysis() >>> print(clf.predict([[-0.8, -1]])) [1] rxNrrrtruryrwrN reg_paramr|r}r~rFrc<||_||_||_||_yrr)r[rNrr|r}s r3rz&QuadraticDiscriminantAnalysis.__init__s! " 0r5TrcTt|||\}}t|tj|d\|_}|j \}}t |j}|dkrtd|z|j'tj|t|z |_ n$tj|j|_ d}|j}|rg}g}g} g} t|D]{} ||| k(ddf} | jd} |j!| t | dk(r$tdt#|j| z| | z }tj$j'|d \}}}|dzt | dz z }d|j(z |z|j(z}tj*||j,kD}||kr(t/j0d | d t$j2|js|r2|j!tj4||j6z|| j!|| j!|j6~|js|r||_tj:||_| |_| |_ |S) aFit the model according to the given training data and parameters. .. versionchanged:: 0.19 ``store_covariances`` has been moved to main constructor as ``store_covariance``. .. versionchanged:: 0.19 ``tol`` has been moved to main constructor. Parameters ---------- X : array-like of shape (n_samples, n_features) Training vector, where `n_samples` is the number of samples and `n_features` is the number of features. y : array-like of shape (n_samples,) Target values (integers). Returns ------- self : object Fitted estimator. T)return_inverserWz>The number of classes has to be greater than one; got %d classNrrz;y has only 1 sample in class %s, covariance is ill defined.FrzThe covariance matrix of class zf is not full rank. Increasing the value of parameter `reg_param` might help reducing the collinearity.)!rrr'rKrZr<rYr)rNr?rrarrayr|r=r>rr$rrqrrjr}rr LinAlgWarningrrr"rrr rotations_)r[r.rBrrrrOr|rFr rotationsindrRmeangXgcrrrS2rs r3r*z!QuadraticDiscriminantAnalysis.fitsc2T1a(1$Q'99Qt< q ! : & q=P  ;; ;;q>E),<HAq"Q$3r7Q;'Bt~~%+t~~=B66"txx-(Dj  5cU;22((  $$(8 266"rtt)R01 OOB    RTT "5 #6  $4"D jj' !# r5c t|t||d}g}tt|jD]w}|j |}|j |}||j|z }tj|||dzz}|jtj|dzdytj|j}tj|j Dcgc]*}tjtj|,c}} d|| zztj|j zScc}w)NFrrrWrr8)rrr=rYrZrrrr'rrrjrrrrir) r[r.norm2rGRrXmX2r2us r3rXz0QuadraticDiscriminantAnalysis._decision_functions $ /s4==)* 0A"Aq!AT[[^#BAt-.B LLAA. /  0 !! JJ4>>Barvvay)B Cuqy!BFF4<<$888Cs0/Ec"t||S)aApply decision function to an array of samples. The decision function is equal (up to a constant factor) to the log-posterior of the model, i.e. `log p(y = k | x)`. In a binary classification setting this instead corresponds to the difference `log p(y = 1 | x) - log p(y = 0 | x)`. See :ref:`lda_qda_math`. Parameters ---------- X : array-like of shape (n_samples, n_features) Array of samples (test vectors). Returns ------- C : ndarray of shape (n_samples,) or (n_samples, n_classes) Decision function values related to each class, per sample. In the two-class case, the shape is `(n_samples,)`, giving the log likelihood ratio of the positive class. rrs r3r]z/QuadraticDiscriminantAnalysis.decision_function"s(w(++r5c"t||S)aPerform classification on an array of test vectors X. The predicted class C for each sample in X is returned. Parameters ---------- X : array-like of shape (n_samples, n_features) Vector to be scored, where `n_samples` is the number of samples and `n_features` is the number of features. Returns ------- C : ndarray of shape (n_samples,) Estimated probabilities. )rrbrs r3rbz%QuadraticDiscriminantAnalysis.predict8s wq!!r5c"t||S)aZReturn posterior probabilities of classification. Parameters ---------- X : array-like of shape (n_samples, n_features) Array of samples/test vectors. Returns ------- C : ndarray of shape (n_samples, n_classes) Posterior probabilities of classification per class. )rrfrs r3rfz+QuadraticDiscriminantAnalysis.predict_probaJsw$Q''r5c"t||S)aeReturn log of posterior probabilities of classification. Parameters ---------- X : array-like of shape (n_samples, n_features) Array of samples/test vectors. Returns ------- C : ndarray of shape (n_samples, n_classes) Posterior log-probabilities of classification per class. )rrers r3rez/QuadraticDiscriminantAnalysis.predict_log_proba[sw(++r5)r-rlrmrnrrr~rrrr r*rXr]rbrfrerrs@r3rrGsfR &tQ&9:&Kq$v67 $De5N6N`9 ,,"$(",,r5)NN)0rnrnumbersrrnumpyr' scipy.linalgrrbaserrr r r covariancer r rlinear_model._baser preprocessingrutils._array_apirrrrutils._param_validationrrr utils.extmathrutils.multiclassrrutils.validationrr__all__r4rIrSrUrrror5r3r s1 "ML5)AAEE"I< ')H I9 x@,^K K \K # K \b,'-b,r5