
    0Ph.                     X   d Z ddlZddlmZmZ ddlZddlZddlm	Z	 ddl
mZmZmZmZmZ ddlmZmZmZ ddlmZ dd	lmZ dd
lmZmZmZmZ ddlmZmZm Z  ddl!m"Z" ddl#m$Z$m%Z% ddl&m'Z'm(Z( ddgZ)ddZ*d Z+ddZ, G d d          Z- G d deeee          Z. G d de-ee          Z/dS )z+Linear and quadratic discriminant analysis.    N)IntegralReal)linalg   )BaseEstimatorClassifierMixinClassNamePrefixFeaturesOutMixinTransformerMixin_fit_context)empirical_covarianceledoit_wolfshrunk_covariance)LinearClassifierMixin)StandardScaler)_expitdeviceget_namespacesize)
HasMethodsInterval
StrOptions)softmax)check_classification_targetsunique_labels)check_is_fittedvalidate_dataLinearDiscriminantAnalysisQuadraticDiscriminantAnalysisc                    ||dn|}t          |t                    r|dk    rst                      }|                    |           } t	          |           d         }|j        ddt          j        f         |z  |j        t          j        ddf         z  }n|dk    rt          |           }nt          |t                    rt          t          |           |          }n_||dk    rt          d          |                    |            t          |d          st          d|j        j        z            |j        }|S )aq  Estimate 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	empiricalautor   z[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)
isinstancestrr   fit_transformr   scale_npnewaxisr   r   r   
ValueErrorfithasattr	__class____name__r"   )X	shrinkagecovariance_estimatorscss        ]/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sklearn/discriminant_analysis.py_covr4       s]   > ##,#4KK)	i%% 
	FF""#%%$$Q''NN1%Iaaam,q029RZ]3KKk))(++	4(( 	F!"6q"9"99EEA Y!^^@   	  ###+];; 	:&09:   !,H    c                    t          |           \  }}|                    |          \  }}|                    |j        d         | j        d         ft	          |           | j                  }|rFt          |j        d                   D ]*}|                    | ||k             d          ||ddf<   +nDt          j	        |          }t          j
                            |||            ||dddf         z  }|S )aA  Compute 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.
    r   r   )r   dtypeaxisN)r   unique_inversezerosshaper   r7   rangemeanr'   bincountaddat)r.   yxpis_array_api_compliantclassesmeansicnts           r3   _class_meansrI   \   s      "/q!1!1B""1%%JGQHHgmA&
3F1IIQWHUUE w}Q'(( 	5 	5A''!AF)!'44E!QQQ$KK	5
 k!nn
		%AQQQWLr5   c           
      0   t          j        |          }t          j        | j        d         | j        d         f          }t	          |          D ]D\  }}| ||k    ddf         }	|||         t          j        t          |	||                    z  z  }E|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.   rB   priorsr/   r0   rE   covidxgroupXgs
             r3   
_class_covrS   |   s    N illG
(!'!*agaj1
2
2
2C(( V V
UqEz111}vc{R]4I?S+T+TUUUUJr5   c                   *    e Zd ZdZd Zd Zd Zd ZdS )#DiscriminantAnalysisPredictionMixinzBMixin class for QuadraticDiscriminantAnalysis and NearestCentroid.c                     |                      |          }t          | j                  dk    r|dddf         |dddf         z
  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.
           Nr   r   )_decision_functionlenclasses_)selfr.   y_scoress      r3   decision_functionz5DiscriminantAnalysisPredictionMixin.decision_function   sT     **1--t}""AAAqD>HQQQTN22r5   c                     |                      |          }| j                            |                    d                    S )a  Perform 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.
        r   r8   )rX   rZ   takeargmax)r[   r.   scoress      r3   predictz+DiscriminantAnalysisPredictionMixin.predict   s;      ((++}!!&--Q-"7"7888r5   c                 P    t          j        |                     |                    S )a  Estimate 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'   exppredict_log_proba)r[   r.   s     r3   predict_probaz1DiscriminantAnalysisPredictionMixin.predict_proba   s"     vd,,Q//000r5   c                 (   |                      |          }||                    d          ddt          j        f         z
  }|t          j        t          j        |                              d          ddt          j        f                   z
  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.
        r   r8   N)rX   maxr'   r(   logrd   sum)r[   r.   ra   log_likelihoods       r3   re   z5DiscriminantAnalysisPredictionMixin.predict_log_proba   s     ((++&**!*"4"4QQQ
]"CCF>""&&A&..qqq"*}=!
 !
 
 	
r5   N)r-   
__module____qualname____doc__r]   rb   rf   re    r5   r3   rU   rU      sV        LL  (9 9 9&1 1 1 
 
 
 
 
r5   rU   c                   R    e Zd ZU dZ eh d          g edh           eeddd          dg eeddd	          dgd
dgdg eeddd	          g ed          dgdZ	e
ed<   	 	 	 	 	 	 	 ddZd Zd Zd Z ed          d             Zd Zd Zd Z fdZ fdZ xZS )r   a  Linear 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 <lda_qda>`.

    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 <array_api>` 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]
    >   svdlsqreigenr!   r   r   bothclosedNleft
array-likebooleanr*   )solverr/   n_componentsrN   store_covariancetolr0   _parameter_constraintsrq   F-C6?c                 h    || _         || _        || _        || _        || _        || _        || _        d S N)rz   r/   rN   r{   r|   r}   r0   )r[   rz   r/   rN   r{   r|   r}   r0   s           r3   __init__z#LinearDiscriminantAnalysis.__init__  s>     "( 0$8!!!r5   c                    t          ||          | _        t          ||| j        ||          | _        t          j        | j        | j        j                  d         j        | _        dt          j
        t          j        | j        | j        j                            z  t          j        | j                  z   | _        dS )a  Least 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.
        r         N)rI   means_rS   priors_r"   r   lstsqTcoef_r'   diagdotri   
intercept_)r[   r.   rB   r/   r0   s        r3   _solve_lstsqz'LinearDiscriminantAnalysis._solve_lstsq  s    ^ #1a((%q$,	+?
 
 \$"2DKMBB1EG
TZ\)J)J!K!KKbfLO
 O
 
r5   c                    t          ||          | _        t          ||| j        ||          | _        | j        }t          |||          }||z
  }t          j        ||          \  }}	t          j	        |t          j
        |          z            ddd         d| j                 | _        |	ddt          j        |          ddd         f         }	|	| _        t          j        | j        |	                              |	j                  | _        dt          j        t          j        | j        | j        j                            z  t          j        | j                  z   | _        dS )a  Eigenvalue 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   )rI   r   rS   r   r"   r4   r   eighr'   sortrj   _max_componentsexplained_variance_ratio_argsort	scalings_r   r   r   r   ri   r   )
r[   r.   rB   r/   r0   SwStSbevalsevecss
             r3   _solve_eigenz'LinearDiscriminantAnalysis._solve_eigen  sF   Z #1a((%q$,	+?
 
 !Y 455"W{2r**u)+1F)G)G")M"d""*
& aaaE**44R4001VDK//33EG<<
TZ\)J)J!K!KKbfLO
 O
 
r5   c                    t          |          \  }}|r|j        j        }nt          j        j        }|j        \  }}| j        j        d         }t          ||          | _        | j        rt          ||| j
                  | _        g }	t          | j                  D ]8\  }
}|||k             }|	                    || j        |
ddf         z
             9| j
        | j        z  | _        |                    |	d          }	|                    |	d          }d||dk    <   |                    d||z
  z  |j                  }|                    |          |	|z  z  } ||d          \  }}}|                    |                    || j        k    |j                            }|d|ddf         |z  j        |d|         z  }|dk    rdnd|dz
  z  }|                    || j
        z  |z            | j        | j        z
  j        z  j        |z  } ||d          \  }}}| j        dk    r"|                    d	|j                  | _        n0|d
z  |                    |d
z            z  d| j                 | _        |                    |                    || j        |d         z  k    |j                            }||j        ddd|f         z  | _        | j        | j        z
  | j        z  }d|                    |d
z  d          z  |                    | j
                  z   | _        || j        j        z  | _        | xj        | j        | j        j        z  z  c_        dS )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.
        r   Nr8         ?r7   Ffull_matricesr   )r   rW   r   ) r   r   rq   scipyr<   rZ   rI   r   r|   rS   r   r"   rL   appendxbar_concatstdasarrayr7   sqrtrj   astyper}   int32r   r   emptyr   r   ri   r   r   )r[   r.   rB   rC   rD   rq   	n_samples
n_features	n_classesXcrP   rQ   rR   r   facUSVtrankscalings_coefs                         r3   
_solve_svdz%LinearDiscriminantAnalysis._solve_svd1  sZ    &31%5%5""! 	#)-CC,"C !	:M'*	"1a((  	>)!Q==D#DM22 	0 	0JC1:BIIb4;sAAAv..////\DK/
YYrY"" ffRaf  C1Hjj	I 56agjFF GGCLLBH%3q...1bvvbiiDHbh7788uuaaaxL3&)AeteH4!^^cc	A)>
 WWi$,.#5664;;S:VV
h 3q...1b1$$-/XXd!'X-J-JD**./dRVVAqD\\.A&$&&.D* vvbiiDHqtO 3RX>>??!BDETEN2dj(DN:aa!8!88266$,;O;OODN,,
4:
44r5   prefer_skip_nested_validationc                    t          |          \  }}t          | ||d|j        |j        g          \  }}t	          |          | _        |j        \  }}| j        j        d         }||k    rt          d          | j        T|	                    |          \  }}|
                    ||j                  t          |j        d                   z  | _        n&|                    | j        |j                  | _        |                    | j        dk               rt          d          |                    |                    | j                  dz
            d	k    r@t%          j        d
t(                     | j        | j                                        z  | _        t+          |dz
  |j        d                   }| j        || _        n&| j        |k    rt          d          | j        | _        | j        dk    rC| j        t5          d          | j        t          d          |                     ||           n]| j        dk    r$|                     ||| j        | j                   n.| j        dk    r#|                     ||| j        | j                   t?          | j                  dk    r|                    | j         dddf         | j         dddf         z
  |j                  }	|!                    |	d          | _         |                    | j"        d         | j"        d         z
  |j                  }
|!                    |
d          | _"        | j        | _#        | S )a  Fit 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_samplesr7   r   z>The number of samples must be more than the number of classes.Nr   zpriors must be non-negativer   gh㈵>z)The priors do not sum to 1. Renormalizingr   zBn_components cannot be larger than min(n_features, n_classes - 1).rq   z*shrinkage not supported with 'svd' solver.zIcovariance estimator is not supported with svd solver. Try another solverrr   )r/   r0   rs   )r   r   )r   )$r   r   float64float32r   rZ   r<   r)   rN   unique_countsr   r7   floatr   r   anyabsrj   warningswarnUserWarningminr{   r   rz   r/   NotImplementedErrorr0   r   r   r   r   r   reshaper   _n_features_out)r[   r.   rB   rC   r   r   r   cntsmax_componentsr   r   s              r3   r*   zLinearDiscriminantAnalysis.fit{  so   . a  A!Q1RZ4L
 
 
1 &a((w	1M'*		!!P   ;&&q))GAt99T1733eAGAJ6G6GGDLL::dk:AADL66$,"## 	<:;;;66"&&&&,--44ME{SSS<$,*:*:*<*<<DL Y]AGAJ77$#1D   >11 X   $(#4D ;%~))*VWWW(4 :  
 OOAq!!!![F"".%)%>	      [G##.%)%>	     !##JJtz!QQQ$/$*QT2BB!'JRREE733DJ"T_Q%77qw $  J !jjT::DO#3r5   c                 (   | j         dk    rt          d          t          |            t          |          \  }}t	          | |d          }| j         dk    r|| j        z
  | j        z  }n| j         dk    r
|| j        z  }|ddd| j        f         S )a  Project 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)).
        rr   zCtransform not implemented for 'lsqr' solver (use 'svd' or 'eigen').Fresetrq   rs   N)rz   r   r   r   r   r   r   r   )r[   r.   rC   r   X_news        r3   	transformz$LinearDiscriminantAnalysis.transform  s     ;&  %U   	a  A$///;%^t~5EE[G##&EQQQ.$...//r5   c                    t          |            t          |          \  }}|                     |          }t          | j                  dk    r,t          ||          }|                    d|z
  |gd          S t          |          S )a  Estimate probability.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            Input data.

        Returns
        -------
        C : ndarray of shape (n_samples, n_classes)
            Estimated probabilities.
        rW   r   r8   )r   r   r]   r   rZ   r   stackr   )r[   r.   rC   rD   decisionprobas         r3   rf   z(LinearDiscriminantAnalysis.predict_proba  s     	%21%5%5""))!,,!##8R((E88QY.Q87778$$$r5   c                    t          |          \  }}|                     |          }|                    |j                  }t	          |d          r|j        }n|j        }||dk    xx         |z  cc<   |                    |          S )a  Estimate 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        )r   rf   finfor7   r+   r   tinyri   )r[   r.   rC   r   
predictioninfor   s          r3   re   z,LinearDiscriminantAnalysis.predict_log_proba  s     a  A''**
xx
())4*++ 	("2OO #iO:$%%%8%%%vvj!!!r5   c                 F    t                                          |          S )a  Apply 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     r3   r]   z,LinearDiscriminantAnalysis.decision_function*  s    * ww((+++r5   c                 V    t                                                      }d|_        |S )NT)r   __sklearn_tags__array_api_support)r[   tagsr,   s     r3   r   z+LinearDiscriminantAnalysis.__sklearn_tags__A  s%    ww''))!%r5   )rq   NNNFr   N)r-   rl   rm   rn   r   r   r   r   r   r~   dict__annotations__r   r   r   r   r   r*   r   rf   re   r]   r   __classcell__r,   s   @r3   r   r      s        Z Zz :666778 j&**HHT1a,O,O,OQUV!(AtFCCCTJ&&Kq$v6667!+E!2!2D 9$ $D    !9 9 9 9$6
 6
 6
p@
 @
 @
DH5 H5 H5T \&+  [ [	 [z0 0 0<% % %," " "4, , , , ,.        r5   c            	            e Zd ZU dZddg eeddd          gdg eeddd	          gd
Zeed<   ddddd
dZ	 e
d          d             Zd Z fdZ fdZ fdZ fdZ xZS )r   aS  Quadratic 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 <lda_qda>`.

    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]
    rx   Nr   r   rt   ru   ry   rw   rN   	reg_paramr|   r}   r~   r   Fr   c                >    || _         || _        || _        || _        d S r   r   )r[   rN   r   r|   r}   s        r3   r   z&QuadraticDiscriminantAnalysis.__init__  s%     " 0r5   Tr   c                 F   t          | ||          \  }}t          |           t          j        |d          \  | _        }|j        \  }}t          | j                  }|dk     rt          d|z            | j        *t          j	        |          t          |          z  | _        nt          j        | j                  | _        d}| j        }|rg }g }g }	g }
t          |          D ]}|||k    ddf         }|                    d          }|                    |           t          |          dk    r*t          dt#          | j        |                   z            ||z
  }t          j                            |d	
          \  }}}|dz  t          |          dz
  z  }d| j        z
  |z  | j        z   }t          j        || j        k              }||k     r#t/          j        d| dt$          j                   | j        s|r0|                    t          j        ||j        z  |                     |	                    |           |
                    |j                   | j        s|r|| _        t          j        |          | _        |	| _        |
| _         | S )a  Fit 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_inverserW   z>The number of classes has to be greater than one; got %d classNr   r   z;y has only 1 sample in class %s, covariance is ill defined.Fr   zThe covariance matrix of class zf is not full rank. Increasing the value of parameter `reg_param` might help reducing the collinearity.)!r   r   r'   rK   rZ   r<   rY   r)   rN   r?   r   r   arrayr|   r=   r>   r   r$   r   rq   r   rj   r}   r   r   LinAlgWarningr   r   r"   r   r   r   
rotations_)r[   r.   rB   r   r   r   rO   r|   rF   r   	rotationsindrR   meangXgcr   r   r   S2r   s                       r3   r*   z!QuadraticDiscriminantAnalysis.fit  s   2 T1a((1$Q'''9Qt<<<q !	:&&	q==P   ;;q>>E),<,<<DLL8DK00DL0 	C	## 	# 	#C18QQQ;BGGAJJELL2ww!|| Q$-,--.   u*Cy}}S}>>HAq"Q$3r77Q;'Bt~%+t~=B6"tx-((Dj  2c 2 2 2 (	   $ 2(8 2

26"rt)R00111OOBRT""""  	#$4 	#"Dj''!#r5   c                 .   t          |            t          | |d          }g }t          t          | j                            D ]s}| j        |         }| j        |         }|| j        |         z
  }t          j	        |||dz  z            }|
                    t          j        |dz  d                     tt          j        |          j        }t          j        d | j        D                       }d||z   z  t          j        | j                  z   S )NFr   r   rW   r   r8   c                 Z    g | ](}t          j        t          j        |                    )S ro   )r'   rj   ri   ).0r2   s     r3   
<listcomp>zDQuadraticDiscriminantAnalysis._decision_function.<locals>.<listcomp>  s*    BBBarvayy))BBBr5   )r   r   r=   rY   rZ   r   r   r   r'   r   r   rj   r   r   r   ri   r   )	r[   r.   norm2rG   Rr   XmX2us	            r3   rX   z0QuadraticDiscriminantAnalysis._decision_function  s   $///s4=))** 	0 	0A"Aq!AT[^#BAt-..BLLAA...////!JBB4>BBBCCuqy!BF4<$8$888r5   c                 F    t                                          |          S )a  Apply 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.
        r   r   s     r3   r]   z/QuadraticDiscriminantAnalysis.decision_function"  s    ( ww((+++r5   c                 F    t                                          |          S )a  Perform 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.
        )r   rb   r   s     r3   rb   z%QuadraticDiscriminantAnalysis.predict8  s      wwq!!!r5   c                 F    t                                          |          S )aZ  Return 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.
        )r   rf   r   s     r3   rf   z+QuadraticDiscriminantAnalysis.predict_probaJ  s     ww$$Q'''r5   c                 F    t                                          |          S )ae  Return 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.
        )r   re   r   s     r3   re   z/QuadraticDiscriminantAnalysis.predict_log_proba[  s     ww((+++r5   )r-   rl   rm   rn   r   r   r~   r   r   r   r   r*   rX   r]   rb   rf   re   r   r   s   @r3   r   r   G  sQ        f fR  &htQ&999:&Kq$v6667	$ $D    e     \555N N 65N`9 9 9 , , , , ,," " " " "$( ( ( ( (", , , , , , , , ,r5   )NN)0rn   r   numbersr   r   numpyr'   scipy.linalgr   r   baser   r   r	   r
   r   
covariancer   r   r   linear_model._baser   preprocessingr   utils._array_apir   r   r   r   utils._param_validationr   r   r   utils.extmathr   utils.multiclassr   r   utils.validationr   r   __all__r4   rI   rS   rU   r   r   ro   r5   r3   <module>r     s]   1 1
  " " " " " " " "                            M L L L L L L L L L 5 5 5 5 5 5 ) ) ) ) ) ) A A A A A A A A A A A A E E E E E E E E E E " " " " " " I I I I I I I I < < < < < < < <')H
I9 9 9 9x  @, , , ,^K
 K
 K
 K
 K
 K
 K
 K
\K	 K	 K	 K	 K	#	K	 K	 K	\b, b, b, b, b,'-b, b, b, b, b,r5   