
    0Ph=                    
   d Z ddlZddlmZmZ ddl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 dd	lmZmZmZmZ dd
lmZmZmZmZmZmZmZmZm Z m!Z!m"Z"m#Z# ddl$m%Z%m&Z&m'Z'm(Z(m)Z) ddl*m+Z+ ddl,m-Z- ddl.m/Z/m0Z0 ddl1m2Z2 ddl3m4Z4m5Z5m6Z6 d Z7d Z8 e)ddgddgdgddgdd          dddd            Z9 e)dgdgddgddg e(h d          dgdd          ddddd            Z: e)ddgddgddgddgdgdd          ddd d!d"            Z; e)dgdgddg e(d#d$h          dgddgd%d          dddd&d'            Z< e)ddgddgddgee=ddg e(h d(          dgddg e'edd)h           e(d*h          gd+d          dd)d,dd*d-d.            Z> e)dgdgddgd/d          dd0d1            Z? e)ddgddgdgddgdd          dddd2            Z@ e)ddgddgddgee=ddg e(h d(          dgddg e'ed3d4h          d5 e(d*h          gd+d          dd)d,dd*d-d6            ZA e)ddgddg e&ed3dd78          gddgee=ddg e(h d(          dgddg e'ed3d4h          d5 e(d*h          gd9d          dd)d,dd*d-d:            ZB	 d\d;ZCd< ZDd= ZE e)ddgddg e&ed3dd78          gddgee=ddg e(h d(          dgeFeGeHgddg e'ed3d4h          d5 e(d*h          gd>	d          d4dd)dd?dd*d@dA            ZI e)ddgddgddgddgdgdBd          ddddCdD            ZJ e)ddgddgddgee=ddg e(h d(          dgddg e'ed3d4h          d5 e(d*h          gd+d          dd)d,dd*d-dE            ZK e)ddgddgddgee=ddg e(h d(          dgddg e'ed3d4h          d5 e(d*h          gd+d          dd)d,dd*d-dF            ZL e)dgdgddgdgdGd          dd dHdI            ZM e)ddgddgddgddgddg e&edddJ8          gdg e'ed3d4h          d5 e(d*h          gdKd          ddddd d*dLdM            ZN e)ddgddgddgd/d          dd0dN            ZO e)dgdgdgddgddgdOd          ddddPdQ            ZP e)dgdgddgddgdRd          dddSdT            ZQ e)dgd e%d          gddgee=ddgd e% e(dUh                    gdVd          	 d]dddUdWdX            ZR e)dgdgddgddgdYd          dddZd[            ZSdS )^a  Metrics to assess performance on classification task given class prediction.

Functions named as ``*_score`` return a scalar value to maximize: the higher
the better.

Function named as ``*_error`` or ``*_loss`` return a scalar value to minimize:
the lower the better.
    N)IntegralReal)
coo_matrix
csr_matrixissparse)xlogy   )UndefinedMetricWarning)LabelBinarizerLabelEncoder)assert_all_finitecheck_arraycheck_consistent_lengthcolumn_or_1d)_average	_bincount_count_nonzero_find_matching_floating_dtype_is_numpy_namespace_searchsorted
_setdiff1d_tolist_union1ddeviceget_namespaceget_namespace_and_device)HiddenIntervalOptions
StrOptionsvalidate_params)attach_unique)_nanaverage)type_of_targetunique_labels)count_nonzero)_check_pos_label_consistency_check_sample_weight_num_samplesc                     t          | t                    r| dk    rt          j        d          S t          | t          t
          f          r| dv rt          j        |           S t          j        S )Nwarn        )r      )
isinstancestrnpfloat64intfloatnanzero_divisions    _/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sklearn/metrics/_classification.py_check_zero_divisionr8   =   sc    -%% -6*A*Az#	MC<	0	0 ]f5L5Lz-(((v    c           	      |   t          | |          \  }}t          | |           t          | d          }t          |d          }||h}|ddhk    rdh}t          |          dk    r#t	          d                    ||                    |                                }|dvr"t	          d	                    |                    |d
v rt          | |          \  }}t          |           } t          |          }|dk    ru	 t          | ||          }nO# t          $ rB}t          d|
                    |            d|
                    |           d          |d}~ww xY w|j        d         dk    rd}|                    d          r/t          |          rt          |           } t          |          }d}|| |fS )a5  Check that y_true and y_pred belong to the same classification task.

    This converts multiclass or binary types to a common shape, and raises a
    ValueError for a mix of multilabel and multiclass targets, a mix of
    multilabel formats, for the presence of continuous-valued or multioutput
    targets, or for targets of different lengths.

    Column vectors are squeezed to 1d, while multilabel formats are returned
    as CSR sparse label indicators.

    Parameters
    ----------
    y_true : array-like

    y_pred : array-like

    Returns
    -------
    type_true : one of {'multilabel-indicator', 'multiclass', 'binary'}
        The type of the true target data, as output by
        ``utils.multiclass.type_of_target``.

    y_true : array or indicator matrix

    y_pred : array or indicator matrix
    y_true
input_namey_predbinary
multiclassr-   z@Classification metrics can't handle a mix of {0} and {1} targetsr?   r@   multilabel-indicator{0} is not supportedr?   r@   zCLabels in y_true and y_pred should be of the same type. Got y_true=z and y_pred=z[. Make sure that the predictions provided by the classifier coincides with the true labels.Nr   r	   
multilabelrB   )r   r   r$   len
ValueErrorformatpopr   r   	TypeErroruniqueshape
startswithr   r   )	r;   r>   xp_	type_true	type_predy_typeunique_valueses	            r7   _check_targetsrU   F   s   6 &&))EBFF+++v(;;;Iv(;;;I#F(L)))
6{{QNUU9 
 
 	
 ZZ\\F EEE/66v>>???)))ff--Af%%f%%X ( < <   
  '"$))F"3"3' ' ii//' ' '   "1%))%&& (r"" 	(
  ''F''F'66!!s   D 
E=EEz
array-likezsparse matrixboolean)r;   r>   	normalizesample_weightT)prefer_skip_nested_validationrW   rX   c                   t          | ||          \  }}}t          | |          \  } }t          | |          \  }} }t          | ||           |                    d          rVt          |          rt          | |z
  d          }nt          | |z
  ||d          }|                    |dk    |          }	n| |k    }	t          t          |	||                    S )a  Accuracy classification score.

    In multilabel classification, this function computes subset accuracy:
    the set of labels predicted for a sample must *exactly* match the
    corresponding set of labels in y_true.

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

    Parameters
    ----------
    y_true : 1d array-like, or label indicator array / sparse matrix
        Ground truth (correct) labels.

    y_pred : 1d array-like, or label indicator array / sparse matrix
        Predicted labels, as returned by a classifier.

    normalize : bool, default=True
        If ``False``, return the number of correctly classified samples.
        Otherwise, return the fraction of correctly classified samples.

    sample_weight : array-like of shape (n_samples,), default=None
        Sample weights.

    Returns
    -------
    score : float or int
        If ``normalize == True``, return the fraction of correctly
        classified samples (float), else returns the number of correctly
        classified samples (int).

        The best performance is 1 with ``normalize == True`` and the number
        of samples with ``normalize == False``.

    See Also
    --------
    balanced_accuracy_score : Compute the balanced accuracy to deal with
        imbalanced datasets.
    jaccard_score : Compute the Jaccard similarity coefficient score.
    hamming_loss : Compute the average Hamming loss or Hamming distance between
        two sets of samples.
    zero_one_loss : Compute the Zero-one classification loss. By default, the
        function will return the percentage of imperfectly predicted subsets.

    Examples
    --------
    >>> from sklearn.metrics import accuracy_score
    >>> y_pred = [0, 2, 1, 3]
    >>> y_true = [0, 1, 2, 3]
    >>> accuracy_score(y_true, y_pred)
    0.5
    >>> accuracy_score(y_true, y_pred, normalize=False)
    2.0

    In the multilabel case with binary label indicators:

    >>> import numpy as np
    >>> accuracy_score(np.array([[0, 1], [1, 1]]), np.ones((2, 2)))
    0.5
    rE   r-   axis)rN   r   r]   r   r   weightsrW   )r   r"   rU   r   rM   r   r&   r   asarrayr3   r   )
r;   r>   rW   rX   rN   rO   r   rR   differing_labelsscores
             r7   accuracy_scorerd      s    J -VV]KKMB6"6622NFF+FF;;FFFFFM:::&& 	!r"" 	,Vf_1EEE-BvA      

+q0
@@& %)LLLMMMr9   >   allpredtrue)r;   r>   labelsrX   rW   )rh   rX   rW   c                  
 t          | |          \  } }t          | |          \  }} }|dvrt          d|z            |t          | |          }nt	          j        |          }|j        dk    rt          d          | j        dk    rt	          j        ft                    S t          t	          j
        | |                    dk    rt          d          |,t	          j        | j        d         t          j                  }nt	          j        |          }t          | ||           |j        |j        j        dv oYt	          j        |t	          j                  k              o/|                                 dk    o|                                dk     }|r[d	 t)          |          D             
t	          j        
fd
|D                       }t	          j        
fd| D                       } t	          j        |k     | k               }t	          j        |          s||         }| |         } ||         }|j        j        dv rt          j        }nt          j        }t1          || |fff|                                          }	t	          j        d          5  |dk    r|	|	                    dd          z  }	n>|dk    r|	|	                    dd          z  }	n|dk    r|	|	                                z  }	t	          j        |	          }	ddd           n# 1 swxY w Y   |	j        dk    rt;          j        dt>                     |	S )a  Compute confusion matrix to evaluate the accuracy of a classification.

    By definition a confusion matrix :math:`C` is such that :math:`C_{i, j}`
    is equal to the number of observations known to be in group :math:`i` and
    predicted to be in group :math:`j`.

    Thus in binary classification, the count of true negatives is
    :math:`C_{0,0}`, false negatives is :math:`C_{1,0}`, true positives is
    :math:`C_{1,1}` and false positives is :math:`C_{0,1}`.

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

    Parameters
    ----------
    y_true : array-like of shape (n_samples,)
        Ground truth (correct) target values.

    y_pred : array-like of shape (n_samples,)
        Estimated targets as returned by a classifier.

    labels : array-like of shape (n_classes), default=None
        List of labels to index the matrix. This may be used to reorder
        or select a subset of labels.
        If ``None`` is given, those that appear at least once
        in ``y_true`` or ``y_pred`` are used in sorted order.

    sample_weight : array-like of shape (n_samples,), default=None
        Sample weights.

        .. versionadded:: 0.18

    normalize : {'true', 'pred', 'all'}, default=None
        Normalizes confusion matrix over the true (rows), predicted (columns)
        conditions or all the population. If None, confusion matrix will not be
        normalized.

    Returns
    -------
    C : ndarray of shape (n_classes, n_classes)
        Confusion matrix whose i-th row and j-th
        column entry indicates the number of
        samples with true label being i-th class
        and predicted label being j-th class.

    See Also
    --------
    ConfusionMatrixDisplay.from_estimator : Plot the confusion matrix
        given an estimator, the data, and the label.
    ConfusionMatrixDisplay.from_predictions : Plot the confusion matrix
        given the true and predicted labels.
    ConfusionMatrixDisplay : Confusion Matrix visualization.

    References
    ----------
    .. [1] `Wikipedia entry for the Confusion matrix
           <https://en.wikipedia.org/wiki/Confusion_matrix>`_
           (Wikipedia and other references may use a different
           convention for axes).

    Examples
    --------
    >>> from sklearn.metrics import confusion_matrix
    >>> y_true = [2, 0, 2, 2, 0, 1]
    >>> y_pred = [0, 0, 2, 2, 0, 2]
    >>> confusion_matrix(y_true, y_pred)
    array([[2, 0, 0],
           [0, 0, 1],
           [1, 0, 2]])

    >>> y_true = ["cat", "ant", "cat", "cat", "ant", "bird"]
    >>> y_pred = ["ant", "ant", "cat", "cat", "ant", "cat"]
    >>> confusion_matrix(y_true, y_pred, labels=["ant", "bird", "cat"])
    array([[2, 0, 0],
           [0, 0, 1],
           [1, 0, 2]])

    In the binary case, we can extract true positives, etc. as follows:

    >>> tn, fp, fn, tp = confusion_matrix([0, 1, 0, 1], [1, 1, 1, 0]).ravel()
    >>> (tn, fp, fn, tp)
    (np.int64(0), np.int64(2), np.int64(1), np.int64(1))
    rD   %s is not supportedNr   z,'labels' should contains at least one label.dtypez.At least one label specified must be in y_true>   biuc                     i | ]\  }}||	S  rq   ).0xys      r7   
<dictcomp>z$confusion_matrix.<locals>.<dictcomp>u  s    ;;;A1;;;r9   c                 B    g | ]}                     |d z             S r-   getrr   rs   label_to_indn_labelss     r7   
<listcomp>z$confusion_matrix.<locals>.<listcomp>v  -    MMM<++Ax!|<<MMMr9   c                 B    g | ]}                     |d z             S rw   rx   rz   s     r7   r}   z$confusion_matrix.<locals>.<listcomp>w  r~   r9   )rL   rl   ignore)re   rg   r-   T)r]   keepdimsrf   re   r-   r-   zA single label was found in 'y_true' and 'y_pred'. For the confusion matrix to have the correct shape, use the 'labels' parameter to pass all known labels.) r"   rU   rG   r%   r0   ra   sizezerosr2   rF   intersect1donesrL   int64r   rl   kindre   arangemin	enumeratearraylogical_andr1   r   toarrayerrstatesum
nan_to_numwarningsr+   UserWarning)r;   r>   rh   rX   rW   rR   need_index_conversionindrl   cmr{   r|   s             @@r7   confusion_matrixr      s   ~ #6622NFF+FF;;FFF---.7888~vv..F##;q==KLLL[A8Xx0<<<<//00A55MNNNQrx@@@
=11FFM:::{H 	_, 	F6RYx00011	JJLLA	 JJLLA	  O;;6):):;;;MMMMMfMMMNNMMMMMfMMMNN .(*FX,=
>
>C6#;; +%c* ?22
		()"
 
 
 gii	  
	"	"	"  bff!df333BB&  bff!df333BB%bffhhB]2               
x6$ 	
 	
 	
 Is   /A4L//L36L3)r;   r>   rX   rh   
samplewiseFrX   rh   r   c          	      	   t          | |          \  } }t          | |          \  }}t          | |          }t          | |          \  }} }|t	          ||          }t          | ||           |dvrt          d|z            t          | |          }	||	}d}
nN|                    ||          }|j	        d         }
|
                    |t          |	|d|          gd	          }| j        d
k    r|rt          d          t                      }|                    |           |                    |           } |                    |          }|j        }| |k    }| |         }|	||         }nd}|j	        d         rt#          |||j	        d         |          }n$|                    |j	        d                   x}x}}|j	        d         rt#          |||j	        d         |          }| j	        d         rt#          | ||j	        d         |          }t'          ||d|
         |          }|                    ||d	          }|                    ||d	          }|                    ||d	          }n|rd
nd}|j	        |	j	        k    s)|                    |                    ||	                    r|                    |          |                    |	          k    r:t          d|                    |          |                    |	          fz            |                    |          dk     r%t          d|                    |          z            |
(| dd|d|
         f         } |dd|d|
         f         }t3          |           st3          |          r|                     |          }n|                    | |          }t7          |||||          }t7          |||||          }t7          | ||||          }||z
  }||z
  }|}|[|rY|                    |          }|                    |          }|                    |          }|| j	        d
         z  |z
  |z
  |z
  }nP||                    |          |z
  |z
  |z
  }n/|r| j	        d
         |z
  |z
  |z
  }n| j	        d         |z
  |z
  |z
  }|                    |                    ||||g          j        d          S )au  Compute a confusion matrix for each class or sample.

    .. versionadded:: 0.21

    Compute class-wise (default) or sample-wise (samplewise=True) multilabel
    confusion matrix to evaluate the accuracy of a classification, and output
    confusion matrices for each class or sample.

    In multilabel confusion matrix :math:`MCM`, the count of true negatives
    is :math:`MCM_{:,0,0}`, false negatives is :math:`MCM_{:,1,0}`,
    true positives is :math:`MCM_{:,1,1}` and false positives is
    :math:`MCM_{:,0,1}`.

    Multiclass data will be treated as if binarized under a one-vs-rest
    transformation. Returned confusion matrices will be in the order of
    sorted unique labels in the union of (y_true, y_pred).

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

    Parameters
    ----------
    y_true : {array-like, sparse matrix} of shape (n_samples, n_outputs) or             (n_samples,)
        Ground truth (correct) target values.

    y_pred : {array-like, sparse matrix} of shape (n_samples, n_outputs) or             (n_samples,)
        Estimated targets as returned by a classifier.

    sample_weight : array-like of shape (n_samples,), default=None
        Sample weights.

    labels : array-like of shape (n_classes,), default=None
        A list of classes or column indices to select some (or to force
        inclusion of classes absent from the data).

    samplewise : bool, default=False
        In the multilabel case, this calculates a confusion matrix per sample.

    Returns
    -------
    multi_confusion : ndarray of shape (n_outputs, 2, 2)
        A 2x2 confusion matrix corresponding to each output in the input.
        When calculating class-wise multi_confusion (default), then
        n_outputs = n_labels; when calculating sample-wise multi_confusion
        (samplewise=True), n_outputs = n_samples. If ``labels`` is defined,
        the results will be returned in the order specified in ``labels``,
        otherwise the results will be returned in sorted order by default.

    See Also
    --------
    confusion_matrix : Compute confusion matrix to evaluate the accuracy of a
        classifier.

    Notes
    -----
    The `multilabel_confusion_matrix` calculates class-wise or sample-wise
    multilabel confusion matrices, and in multiclass tasks, labels are
    binarized under a one-vs-rest way; while
    :func:`~sklearn.metrics.confusion_matrix` calculates one confusion matrix
    for confusion between every two classes.

    Examples
    --------
    Multilabel-indicator case:

    >>> import numpy as np
    >>> from sklearn.metrics import multilabel_confusion_matrix
    >>> y_true = np.array([[1, 0, 1],
    ...                    [0, 1, 0]])
    >>> y_pred = np.array([[1, 0, 0],
    ...                    [0, 1, 1]])
    >>> multilabel_confusion_matrix(y_true, y_pred)
    array([[[1, 0],
            [0, 1]],
    <BLANKLINE>
           [[1, 0],
            [0, 1]],
    <BLANKLINE>
           [[0, 1],
            [1, 0]]])

    Multiclass case:

    >>> y_true = ["cat", "ant", "cat", "cat", "ant", "bird"]
    >>> y_pred = ["ant", "ant", "cat", "cat", "ant", "cat"]
    >>> multilabel_confusion_matrix(y_true, y_pred,
    ...                             labels=["ant", "bird", "cat"])
    array([[[3, 1],
            [0, 2]],
    <BLANKLINE>
           [[5, 0],
            [1, 0]],
    <BLANKLINE>
           [[2, 1],
            [1, 2]]])
    Nr^   rA   rj   r   T)assume_uniquerN   r\   r-   zJSamplewise metrics are not available outside of multilabel classification.)r`   	minlengthrN   rN   zGAll labels must be in [0, n labels) for multilabel targets. Got %d > %dzFAll labels must be in [0, n labels) for multilabel targets. Got %d < 0)r]   rX   rN   r   )r   r	   r	   ) r"   r   r   rU   r   r   rG   r%   ra   rL   concatr   ndimr   fit	transformclasses_r   r   r   takeany	not_equalmaxr   r   multiplyr   r   reshapestackT)r;   r>   rX   rh   r   rN   rO   device_rR   present_labelsr|   lesorted_labelstptp_binstp_bins_weightstp_sumtrue_sumpred_sumindicessum_axistrue_and_predfpfntns                            r7   multilabel_confusion_matrixr     s   \ #6622NFF&&))EBVV$$G+FF;;FFF $]7CCCFFM:::EEE.7888"6622N~F733<?ZdrRRRS  
 

 {a 	-  
 ^^
vf%%f%% v*$+B/OO"O= 	EFLOPR  FF
 ,.88FLO+D+DDHDx&<? 	 aR  H <? 	 aR  H
  vixi/@RHHHq11778W1755778W1755 #)11 <>///266LL004
 4
/ vvf~~~ 6 666 "%'VVF^^RVVN5K5K$LM  
 vvf~~!! !#%66&>>2   AAAvixi001FAAAvixi001FF 	8x// 	8"OOF33MMKK77M  '
 
 
 "'
 
 
 "'
 
 
 
F	B	F	B	B Z ZZ^^ZZ^^ZZ^^V\!_,r1B6;		"VVM""R'",r1	 ,\!_r!B&+\!_r!B&+::bhhBB/002J???r9   linear	quadratic)y1y2rh   r`   rX   )rh   r`   rX   c                ~   t          | |||          }|j        d         }t          j        |d          }t          j        |d          }t          j        ||          t          j        |          z  }	|.t          j        ||gt                    }
d|
j        dd|dz   <   ndt          j        ||gt                    }
|
t          j	        |          z  }
|dk    rt          j
        |
|
j        z
            }
n|
|
j        z
  dz  }
t          j        |
|z            t          j        |
|	z            z  }d|z
  S )	a!
  Compute Cohen's kappa: a statistic that measures inter-annotator agreement.

    This function computes Cohen's kappa [1]_, a score that expresses the level
    of agreement between two annotators on a classification problem. It is
    defined as

    .. math::
        \kappa = (p_o - p_e) / (1 - p_e)

    where :math:`p_o` is the empirical probability of agreement on the label
    assigned to any sample (the observed agreement ratio), and :math:`p_e` is
    the expected agreement when both annotators assign labels randomly.
    :math:`p_e` is estimated using a per-annotator empirical prior over the
    class labels [2]_.

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

    Parameters
    ----------
    y1 : array-like of shape (n_samples,)
        Labels assigned by the first annotator.

    y2 : array-like of shape (n_samples,)
        Labels assigned by the second annotator. The kappa statistic is
        symmetric, so swapping ``y1`` and ``y2`` doesn't change the value.

    labels : array-like of shape (n_classes,), default=None
        List of labels to index the matrix. This may be used to select a
        subset of labels. If `None`, all labels that appear at least once in
        ``y1`` or ``y2`` are used.

    weights : {'linear', 'quadratic'}, default=None
        Weighting type to calculate the score. `None` means not weighted;
        "linear" means linear weighting; "quadratic" means quadratic weighting.

    sample_weight : array-like of shape (n_samples,), default=None
        Sample weights.

    Returns
    -------
    kappa : float
        The kappa statistic, which is a number between -1 and 1. The maximum
        value means complete agreement; zero or lower means chance agreement.

    References
    ----------
    .. [1] :doi:`J. Cohen (1960). "A coefficient of agreement for nominal scales".
           Educational and Psychological Measurement 20(1):37-46.
           <10.1177/001316446002000104>`
    .. [2] `R. Artstein and M. Poesio (2008). "Inter-coder agreement for
           computational linguistics". Computational Linguistics 34(4):555-596
           <https://www.mitpressjournals.org/doi/pdf/10.1162/coli.07-034-R2>`_.
    .. [3] `Wikipedia entry for the Cohen's kappa
            <https://en.wikipedia.org/wiki/Cohen%27s_kappa>`_.

    Examples
    --------
    >>> from sklearn.metrics import cohen_kappa_score
    >>> y1 = ["negative", "positive", "negative", "neutral", "positive"]
    >>> y2 = ["negative", "positive", "negative", "neutral", "negative"]
    >>> cohen_kappa_score(y1, y2)
    np.float64(0.6875)
    rh   rX   r   r\   r-   Nrk   r   r	   )r   rL   r0   r   outerr   r2   flatr   r   absr   )r   r   rh   r`   rX   	confusion	n_classessum0sum1expectedw_matks               r7   cohen_kappa_scorer     s7   T !RmTTTI"I6)!$$$D6)!$$$Dxd##bfTll2HI.c:::'(
##i!m#$$)Y/s;;;9%%%hF557?++EEUW_*E
uy !!BF58+;$<$<<Aq5Lr9   >   macromicror?   samplesweightedr-   r+   r;   r>   rh   	pos_labelaveragerX   r6   r?   )rh   r   r   rX   r6   c          	      Z   t          | ||||          }|dk    }t          | ||||          }|ddddf         }	|ddddf         |ddddf         z   |ddddf         z   }
|dk    rNt          j        |	                                g          }	t          j        |
                                g          }
t          |	|
dd|d	|
          }||S |dk    r2|ddddf         |ddddf         z   }t          j        |          sd}n|dk    r||}nd}t          j        ||          S )a  Jaccard similarity coefficient score.

    The Jaccard index [1], or Jaccard similarity coefficient, defined as
    the size of the intersection divided by the size of the union of two label
    sets, is used to compare set of predicted labels for a sample to the
    corresponding set of labels in ``y_true``.

    Support beyond term:`binary` targets is achieved by treating :term:`multiclass`
    and :term:`multilabel` data as a collection of binary problems, one for each
    label. For the :term:`binary` case, setting `average='binary'` will return the
    Jaccard similarity coefficient for `pos_label`. If `average` is not `'binary'`,
    `pos_label` is ignored and scores for both classes are computed, then averaged or
    both returned (when `average=None`). Similarly, for :term:`multiclass` and
    :term:`multilabel` targets, scores for all `labels` are either returned or
    averaged depending on the `average` parameter. Use `labels` specify the set of
    labels to calculate the score for.

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

    Parameters
    ----------
    y_true : 1d array-like, or label indicator array / sparse matrix
        Ground truth (correct) labels.

    y_pred : 1d array-like, or label indicator array / sparse matrix
        Predicted labels, as returned by a classifier.

    labels : array-like of shape (n_classes,), default=None
        The set of labels to include when `average != 'binary'`, and their
        order if `average is None`. Labels present in the data can be
        excluded, for example in multiclass classification to exclude a "negative
        class". Labels not present in the data can be included and will be
        "assigned" 0 samples. For multilabel targets, labels are column indices.
        By default, all labels in `y_true` and `y_pred` are used in sorted order.

    pos_label : int, float, bool or str, default=1
        The class to report if `average='binary'` and the data is binary,
        otherwise this parameter is ignored.
        For multiclass or multilabel targets, set `labels=[pos_label]` and
        `average != 'binary'` to report metrics for one label only.

    average : {'micro', 'macro', 'samples', 'weighted',             'binary'} or None, default='binary'
        If ``None``, the scores for each class are returned. Otherwise, this
        determines the type of averaging performed on the data:

        ``'binary'``:
            Only report results for the class specified by ``pos_label``.
            This is applicable only if targets (``y_{true,pred}``) are binary.
        ``'micro'``:
            Calculate metrics globally by counting the total true positives,
            false negatives and false positives.
        ``'macro'``:
            Calculate metrics for each label, and find their unweighted
            mean.  This does not take label imbalance into account.
        ``'weighted'``:
            Calculate metrics for each label, and find their average, weighted
            by support (the number of true instances for each label). This
            alters 'macro' to account for label imbalance.
        ``'samples'``:
            Calculate metrics for each instance, and find their average (only
            meaningful for multilabel classification).

    sample_weight : array-like of shape (n_samples,), default=None
        Sample weights.

    zero_division : "warn", {0.0, 1.0}, default="warn"
        Sets the value to return when there is a zero division, i.e. when there
        there are no negative values in predictions and labels. If set to
        "warn", this acts like 0, but a warning is also raised.

        .. versionadded:: 0.24

    Returns
    -------
    score : float or ndarray of shape (n_unique_labels,), dtype=np.float64
        The Jaccard score. When `average` is not `None`, a single scalar is
        returned.

    See Also
    --------
    accuracy_score : Function for calculating the accuracy score.
    f1_score : Function for calculating the F1 score.
    multilabel_confusion_matrix : Function for computing a confusion matrix                                  for each class or sample.

    Notes
    -----
    :func:`jaccard_score` may be a poor metric if there are no
    positives for some samples or classes. Jaccard is undefined if there are
    no true or predicted labels, and our implementation will return a score
    of 0 with a warning.

    References
    ----------
    .. [1] `Wikipedia entry for the Jaccard index
           <https://en.wikipedia.org/wiki/Jaccard_index>`_.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.metrics import jaccard_score
    >>> y_true = np.array([[0, 1, 1],
    ...                    [1, 1, 0]])
    >>> y_pred = np.array([[1, 1, 1],
    ...                    [1, 0, 0]])

    In the binary case:

    >>> jaccard_score(y_true[0], y_pred[0])
    np.float64(0.6666...)

    In the 2D comparison case (e.g. image similarity):

    >>> jaccard_score(y_true, y_pred, average="micro")
    np.float64(0.6)

    In the multilabel case:

    >>> jaccard_score(y_true, y_pred, average='samples')
    np.float64(0.5833...)
    >>> jaccard_score(y_true, y_pred, average='macro')
    np.float64(0.6666...)
    >>> jaccard_score(y_true, y_pred, average=None)
    array([0.5, 0.5, 1. ])

    In the multiclass case:

    >>> y_pred = [0, 2, 1, 2]
    >>> y_true = [0, 1, 2, 2]
    >>> jaccard_score(y_true, y_pred, average=None)
    array([1. , 0. , 0.33...])
    r   r   Nr-   r   r   jaccardztrue or predicted)r   r5   r   r`   )_check_set_wise_labelsr   r0   r   r   _prf_divider   r   )r;   r>   rh   r   r   rX   r6   r   MCM	numeratordenominatorr   r`   s                r7   jaccard_scorer     s   B $FFGVYOOFI%J
%#  C AAAq!GIaaaAg,QQQ1W-AAAq!G<K'Himmoo.//	h 1 1233#  G *aaaAg,QQQ1W-vg 	G	I		-";:gw////r9   )r;   r>   rX   rX   c                \   t          | |          \  } }t          | |          \  }} }t          | ||           |dvrt          d|z            t	                      }|                    t          j        | |g                     |                    |           } |                    |          }t          | ||          }|
                    dt          j                  }|
                    dt          j                  }t          j        |t          j                  }|
                                }	||	z  t          j        ||          z
  }
|	dz  t          j        ||          z
  }|	dz  t          j        ||          z
  }||z  dk    rd	S |
t          j        ||z            z  S )
a	  Compute the Matthews correlation coefficient (MCC).

    The Matthews correlation coefficient is used in machine learning as a
    measure of the quality of binary and multiclass classifications. It takes
    into account true and false positives and negatives and is generally
    regarded as a balanced measure which can be used even if the classes are of
    very different sizes. The MCC is in essence a correlation coefficient value
    between -1 and +1. A coefficient of +1 represents a perfect prediction, 0
    an average random prediction and -1 an inverse prediction.  The statistic
    is also known as the phi coefficient. [source: Wikipedia]

    Binary and multiclass labels are supported.  Only in the binary case does
    this relate to information about true and false positives and negatives.
    See references below.

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

    Parameters
    ----------
    y_true : array-like of shape (n_samples,)
        Ground truth (correct) target values.

    y_pred : array-like of shape (n_samples,)
        Estimated targets as returned by a classifier.

    sample_weight : array-like of shape (n_samples,), default=None
        Sample weights.

        .. versionadded:: 0.18

    Returns
    -------
    mcc : float
        The Matthews correlation coefficient (+1 represents a perfect
        prediction, 0 an average random prediction and -1 and inverse
        prediction).

    References
    ----------
    .. [1] :doi:`Baldi, Brunak, Chauvin, Andersen and Nielsen, (2000). Assessing the
       accuracy of prediction algorithms for classification: an overview.
       <10.1093/bioinformatics/16.5.412>`

    .. [2] `Wikipedia entry for the Matthews Correlation Coefficient (phi coefficient)
       <https://en.wikipedia.org/wiki/Phi_coefficient>`_.

    .. [3] `Gorodkin, (2004). Comparing two K-category assignments by a
        K-category correlation coefficient
        <https://www.sciencedirect.com/science/article/pii/S1476927104000799>`_.

    .. [4] `Jurman, Riccadonna, Furlanello, (2012). A Comparison of MCC and CEN
        Error Measures in MultiClass Prediction
        <https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0041882>`_.

    Examples
    --------
    >>> from sklearn.metrics import matthews_corrcoef
    >>> y_true = [+1, +1, +1, -1]
    >>> y_pred = [+1, -1, +1, +1]
    >>> matthews_corrcoef(y_true, y_pred)
    np.float64(-0.33...)
    >   r?   r@   rj   r   r-   )r]   rl   r   rk   r	   r,   )r"   rU   r   rG   r   r   r0   hstackr   r   r   r1   tracedotsqrt)r;   r>   rX   rR   lbCt_sump_sum	n_correct	n_samplescov_ytypcov_ypypcov_ytyts                r7   matthews_corrcoefr     s   N #6622NFF+FF;;FFFFFM:::---.7888	BFF29ff%&&'''\\&!!F\\&!!F}EEEAEEq
E++EEEq
E++E"*---I		I9$rveU';';;H!|bfUE222H!|bfUE222H(as"'(X"56666r9   c                    t          | |          \  }}t          | |||          }|rd|z
  S ||                    |          }nt          |           }||z
  S )a  Zero-one classification loss.

    If normalize is ``True``, return the fraction of misclassifications
    (float), else it returns the number of misclassifications (int). The best
    performance is 0.

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

    Parameters
    ----------
    y_true : 1d array-like, or label indicator array / sparse matrix
        Ground truth (correct) labels.

    y_pred : 1d array-like, or label indicator array / sparse matrix
        Predicted labels, as returned by a classifier.

    normalize : bool, default=True
        If ``False``, return the number of misclassifications.
        Otherwise, return the fraction of misclassifications.

    sample_weight : array-like of shape (n_samples,), default=None
        Sample weights.

    Returns
    -------
    loss : float or int,
        If ``normalize == True``, return the fraction of misclassifications
        (float), else it returns the number of misclassifications (int).

    See Also
    --------
    accuracy_score : Compute the accuracy score. By default, the function will
        return the fraction of correct predictions divided by the total number
        of predictions.
    hamming_loss : Compute the average Hamming loss or Hamming distance between
        two sets of samples.
    jaccard_score : Compute the Jaccard similarity coefficient score.

    Notes
    -----
    In multilabel classification, the zero_one_loss function corresponds to
    the subset zero-one loss: for each sample, the entire set of labels must be
    correctly predicted, otherwise the loss for that sample is equal to one.

    Examples
    --------
    >>> from sklearn.metrics import zero_one_loss
    >>> y_pred = [1, 2, 3, 4]
    >>> y_true = [2, 2, 3, 4]
    >>> zero_one_loss(y_true, y_pred)
    0.25
    >>> zero_one_loss(y_true, y_pred, normalize=False)
    1.0

    In the multilabel case with binary label indicators:

    >>> import numpy as np
    >>> zero_one_loss(np.array([[0, 1], [1, 1]]), np.ones((2, 2)))
    0.5
    rZ   r-   )r   rd   r   r)   )r;   r>   rW   rX   rN   rO   rc   r   s           r7   zero_one_lossr   #  sz    L &&))EB)=  E  !5y$}--II$V,,I5  r9   r,         ?r4   c          
      0    t          | |d|||||          S )a  Compute the F1 score, also known as balanced F-score or F-measure.

    The F1 score can be interpreted as a harmonic mean of the precision and
    recall, where an F1 score reaches its best value at 1 and worst score at 0.
    The relative contribution of precision and recall to the F1 score are
    equal. The formula for the F1 score is:

    .. math::
        \text{F1} = \frac{2 * \text{TP}}{2 * \text{TP} + \text{FP} + \text{FN}}

    Where :math:`\text{TP}` is the number of true positives, :math:`\text{FN}` is the
    number of false negatives, and :math:`\text{FP}` is the number of false positives.
    F1 is by default
    calculated as 0.0 when there are no true positives, false negatives, or
    false positives.

    Support beyond :term:`binary` targets is achieved by treating :term:`multiclass`
    and :term:`multilabel` data as a collection of binary problems, one for each
    label. For the :term:`binary` case, setting `average='binary'` will return
    F1 score for `pos_label`. If `average` is not `'binary'`, `pos_label` is ignored
    and F1 score for both classes are computed, then averaged or both returned (when
    `average=None`). Similarly, for :term:`multiclass` and :term:`multilabel` targets,
    F1 score for all `labels` are either returned or averaged depending on the
    `average` parameter. Use `labels` specify the set of labels to calculate F1 score
    for.

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

    Parameters
    ----------
    y_true : 1d array-like, or label indicator array / sparse matrix
        Ground truth (correct) target values.

    y_pred : 1d array-like, or label indicator array / sparse matrix
        Estimated targets as returned by a classifier.

    labels : array-like, default=None
        The set of labels to include when `average != 'binary'`, and their
        order if `average is None`. Labels present in the data can be
        excluded, for example in multiclass classification to exclude a "negative
        class". Labels not present in the data can be included and will be
        "assigned" 0 samples. For multilabel targets, labels are column indices.
        By default, all labels in `y_true` and `y_pred` are used in sorted order.

        .. versionchanged:: 0.17
           Parameter `labels` improved for multiclass problem.

    pos_label : int, float, bool or str, default=1
        The class to report if `average='binary'` and the data is binary,
        otherwise this parameter is ignored.
        For multiclass or multilabel targets, set `labels=[pos_label]` and
        `average != 'binary'` to report metrics for one label only.

    average : {'micro', 'macro', 'samples', 'weighted', 'binary'} or None,             default='binary'
        This parameter is required for multiclass/multilabel targets.
        If ``None``, the metrics for each class are returned. Otherwise, this
        determines the type of averaging performed on the data:

        ``'binary'``:
            Only report results for the class specified by ``pos_label``.
            This is applicable only if targets (``y_{true,pred}``) are binary.
        ``'micro'``:
            Calculate metrics globally by counting the total true positives,
            false negatives and false positives.
        ``'macro'``:
            Calculate metrics for each label, and find their unweighted
            mean.  This does not take label imbalance into account.
        ``'weighted'``:
            Calculate metrics for each label, and find their average weighted
            by support (the number of true instances for each label). This
            alters 'macro' to account for label imbalance; it can result in an
            F-score that is not between precision and recall.
        ``'samples'``:
            Calculate metrics for each instance, and find their average (only
            meaningful for multilabel classification where this differs from
            :func:`accuracy_score`).

    sample_weight : array-like of shape (n_samples,), default=None
        Sample weights.

    zero_division : {"warn", 0.0, 1.0, np.nan}, default="warn"
        Sets the value to return when there is a zero division, i.e. when all
        predictions and labels are negative.

        Notes:
        - If set to "warn", this acts like 0, but a warning is also raised.
        - If set to `np.nan`, such values will be excluded from the average.

        .. versionadded:: 1.3
           `np.nan` option was added.

    Returns
    -------
    f1_score : float or array of float, shape = [n_unique_labels]
        F1 score of the positive class in binary classification or weighted
        average of the F1 scores of each class for the multiclass task.

    See Also
    --------
    fbeta_score : Compute the F-beta score.
    precision_recall_fscore_support : Compute the precision, recall, F-score,
        and support.
    jaccard_score : Compute the Jaccard similarity coefficient score.
    multilabel_confusion_matrix : Compute a confusion matrix for each class or
        sample.

    Notes
    -----
    When ``true positive + false positive + false negative == 0`` (i.e. a class
    is completely absent from both ``y_true`` or ``y_pred``), f-score is
    undefined. In such cases, by default f-score will be set to 0.0, and
    ``UndefinedMetricWarning`` will be raised. This behavior can be modified by
    setting the ``zero_division`` parameter.

    References
    ----------
    .. [1] `Wikipedia entry for the F1-score
           <https://en.wikipedia.org/wiki/F1_score>`_.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.metrics import f1_score
    >>> y_true = [0, 1, 2, 0, 1, 2]
    >>> y_pred = [0, 2, 1, 0, 0, 1]
    >>> f1_score(y_true, y_pred, average='macro')
    0.26...
    >>> f1_score(y_true, y_pred, average='micro')
    0.33...
    >>> f1_score(y_true, y_pred, average='weighted')
    0.26...
    >>> f1_score(y_true, y_pred, average=None)
    array([0.8, 0. , 0. ])

    >>> # binary classification
    >>> y_true_empty = [0, 0, 0, 0, 0, 0]
    >>> y_pred_empty = [0, 0, 0, 0, 0, 0]
    >>> f1_score(y_true_empty, y_pred_empty)
    0.0...
    >>> f1_score(y_true_empty, y_pred_empty, zero_division=1.0)
    1.0...
    >>> f1_score(y_true_empty, y_pred_empty, zero_division=np.nan)
    nan...

    >>> # multilabel classification
    >>> y_true = [[0, 0, 0], [1, 1, 1], [0, 1, 1]]
    >>> y_pred = [[0, 0, 0], [1, 1, 1], [1, 1, 0]]
    >>> f1_score(y_true, y_pred, average=None)
    array([0.66666667, 1.        , 0.66666667])
    r-   )betarh   r   r   rX   r6   )fbeta_scorer   s          r7   f1_scorer   x  s4    h ##	 	 	 	r9   both)closed)r;   r>   r   rh   r   r   rX   r6   c                @    t          | |||||d||	  	        \  }}}	}|	S )a+  Compute the F-beta score.

    The F-beta score is the weighted harmonic mean of precision and recall,
    reaching its optimal value at 1 and its worst value at 0.

    The `beta` parameter represents the ratio of recall importance to
    precision importance. `beta > 1` gives more weight to recall, while
    `beta < 1` favors precision. For example, `beta = 2` makes recall twice
    as important as precision, while `beta = 0.5` does the opposite.
    Asymptotically, `beta -> +inf` considers only recall, and `beta -> 0`
    only precision.

    The formula for F-beta score is:

    .. math::

       F_\beta = \frac{(1 + \beta^2) \text{tp}}
                        {(1 + \beta^2) \text{tp} + \text{fp} + \beta^2 \text{fn}}

    Where :math:`\text{tp}` is the number of true positives, :math:`\text{fp}` is the
    number of false positives, and :math:`\text{fn}` is the number of false negatives.

    Support beyond term:`binary` targets is achieved by treating :term:`multiclass`
    and :term:`multilabel` data as a collection of binary problems, one for each
    label. For the :term:`binary` case, setting `average='binary'` will return
    F-beta score for `pos_label`. If `average` is not `'binary'`, `pos_label` is
    ignored and F-beta score for both classes are computed, then averaged or both
    returned (when `average=None`). Similarly, for :term:`multiclass` and
    :term:`multilabel` targets, F-beta score for all `labels` are either returned or
    averaged depending on the `average` parameter. Use `labels` specify the set of
    labels to calculate F-beta score for.

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

    Parameters
    ----------
    y_true : 1d array-like, or label indicator array / sparse matrix
        Ground truth (correct) target values.

    y_pred : 1d array-like, or label indicator array / sparse matrix
        Estimated targets as returned by a classifier.

    beta : float
        Determines the weight of recall in the combined score.

    labels : array-like, default=None
        The set of labels to include when `average != 'binary'`, and their
        order if `average is None`. Labels present in the data can be
        excluded, for example in multiclass classification to exclude a "negative
        class". Labels not present in the data can be included and will be
        "assigned" 0 samples. For multilabel targets, labels are column indices.
        By default, all labels in `y_true` and `y_pred` are used in sorted order.

        .. versionchanged:: 0.17
           Parameter `labels` improved for multiclass problem.

    pos_label : int, float, bool or str, default=1
        The class to report if `average='binary'` and the data is binary,
        otherwise this parameter is ignored.
        For multiclass or multilabel targets, set `labels=[pos_label]` and
        `average != 'binary'` to report metrics for one label only.

    average : {'micro', 'macro', 'samples', 'weighted', 'binary'} or None,             default='binary'
        This parameter is required for multiclass/multilabel targets.
        If ``None``, the metrics for each class are returned. Otherwise, this
        determines the type of averaging performed on the data:

        ``'binary'``:
            Only report results for the class specified by ``pos_label``.
            This is applicable only if targets (``y_{true,pred}``) are binary.
        ``'micro'``:
            Calculate metrics globally by counting the total true positives,
            false negatives and false positives.
        ``'macro'``:
            Calculate metrics for each label, and find their unweighted
            mean.  This does not take label imbalance into account.
        ``'weighted'``:
            Calculate metrics for each label, and find their average weighted
            by support (the number of true instances for each label). This
            alters 'macro' to account for label imbalance; it can result in an
            F-score that is not between precision and recall.
        ``'samples'``:
            Calculate metrics for each instance, and find their average (only
            meaningful for multilabel classification where this differs from
            :func:`accuracy_score`).

    sample_weight : array-like of shape (n_samples,), default=None
        Sample weights.

    zero_division : {"warn", 0.0, 1.0, np.nan}, default="warn"
        Sets the value to return when there is a zero division, i.e. when all
        predictions and labels are negative.

        Notes:

        - If set to "warn", this acts like 0, but a warning is also raised.
        - If set to `np.nan`, such values will be excluded from the average.

        .. versionadded:: 1.3
           `np.nan` option was added.

    Returns
    -------
    fbeta_score : float (if average is not None) or array of float, shape =        [n_unique_labels]
        F-beta score of the positive class in binary classification or weighted
        average of the F-beta score of each class for the multiclass task.

    See Also
    --------
    precision_recall_fscore_support : Compute the precision, recall, F-score,
        and support.
    multilabel_confusion_matrix : Compute a confusion matrix for each class or
        sample.

    Notes
    -----
    When ``true positive + false positive + false negative == 0``, f-score
    returns 0.0 and raises ``UndefinedMetricWarning``. This behavior can be
    modified by setting ``zero_division``.

    References
    ----------
    .. [1] R. Baeza-Yates and B. Ribeiro-Neto (2011).
           Modern Information Retrieval. Addison Wesley, pp. 327-328.

    .. [2] `Wikipedia entry for the F1-score
           <https://en.wikipedia.org/wiki/F1_score>`_.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.metrics import fbeta_score
    >>> y_true = [0, 1, 2, 0, 1, 2]
    >>> y_pred = [0, 2, 1, 0, 0, 1]
    >>> fbeta_score(y_true, y_pred, average='macro', beta=0.5)
    0.23...
    >>> fbeta_score(y_true, y_pred, average='micro', beta=0.5)
    0.33...
    >>> fbeta_score(y_true, y_pred, average='weighted', beta=0.5)
    0.23...
    >>> fbeta_score(y_true, y_pred, average=None, beta=0.5)
    array([0.71..., 0.        , 0.        ])
    >>> y_pred_empty = [0, 0, 0, 0, 0, 0]
    >>> fbeta_score(y_true, y_pred_empty,
    ...             average="macro", zero_division=np.nan, beta=0.5)
    0.12...
    )f-scorer   rh   r   r   warn_forrX   r6   precision_recall_fscore_support)
r;   r>   r   rh   r   r   rX   r6   rO   fs
             r7   r   r   8  sC    j 1##
 
 
JAq!Q Hr9   c                    t          | |          \  }}t          | ||          }	|dk    }
|                    |d|	          }d||
<   |                    | |	          |z  }|                    |
          s|S t	          |          }|||
<   |dk    s||vr|S ||v r4t          |||                                 dt          |                     |S )	aS  Performs division and handles divide-by-zero.

    On zero-division, sets the corresponding result elements equal to
    0, 1 or np.nan (according to ``zero_division``). Plus, if
    ``zero_division != "warn"`` raises a warning.

    The metric, modifier and average arguments are used only for determining
    an appropriate warning.
    r   r   T)copyrl   r-   rk   r+   z is)r   r   ra   r   r8   	_warn_prf
capitalizerF   )r   r   metricmodifierr   r   r6   rN   rO   dtype_floatmaskresultzero_division_values                r7   r   r     s     )[11EB/	;2NNNK!D**[t;*GGKKZZ	Z55CF66$<<  /}==&F4L
 &"8"8 '8(9(9(;(;%@%@%@#f++NNNMr9   c                    d\  }}| dk    r||}}d                     |||          }|dk    r|                     d          }n(|                     d                     |                    }t          j        |t          d           d S )	N)samplelabelr   zo{0} ill-defined and being set to 0.0 {{0}} no {1} {2}s. Use `zero_division` parameter to control this behavior.r-   zdue tozin {0}s withr	   
stacklevel)rH   r   r+   r
   )r   r  	msg_startresult_sizeaxis0axis1msgs          r7   r   r   "  s    $LE5)eu	 &He<< 
 ajj""jj..u5566M#-!<<<<<<r9   c                 &   d}||vr%|dk    rt          dt          |          z             t          | |          \  } }t          | |          \  }} }t	          t          | |                    }|dk    rv|dk    r0||vr(t          |          dk    rt          d| d|           |g}net          |          }|dk    r|                    d           t          d	|d
|d          |dvr!t          j
        d|d|dt                     |S )zQValidation associated with set-wise metrics.

    Returns identified labels.
    )Nr   r   r   r   r?   zaverage has to be one of r	   z
pos_label=z+ is not a valid label. It should be one of r@   r   z
Target is zE but average='binary'. Please choose another average setting, one of .)Nr-   zNote that pos_label (set to z+) is ignored when average != 'binary' (got zE). You may use labels=[pos_label] to specify a single positive class.)rG   r/   r"   rU   r   r%   rF   listremover   r+   r   )r;   r>   r   rh   r   average_optionsrR   r   s           r7   r   r   2  s   
 FOo%%'X*=*=4s?7K7KKLLL"6622NFF+FF;;FFF ]66::;;N(X..~&&!++$=Y = =,:= =    [FF"?33O%%&&y111*@FY   
)	#	# yy'''# 	
 	
 	
 Mr9   )	r;   r>   r   rh   r   r   r   rX   r6   )	precisionrecallr   r   c          	         t          |           t          | ||||          }|dk    }	t          | ||||	          }
|
ddddf         }||
ddddf         z   }||
ddddf         z   }t          | |          \  }}|dk    r{|                    |                    |          d          }|                    |                    |          d          }|                    |                    |          d          }|dz  }t          ||d	d
|||          }t          ||dd|||          }t          j        |          r|}n,|dk    r|}n#||z  |z   }t          d|z   |z  |dd|||          }|dk    r|}n|dk    r|}nd}|u|dk    s|j	        d         dk    sJ t          t          ||                    }t          t          ||                    }t          t          ||                    }d}||||fS )a~  Compute precision, recall, F-measure and support for each class.

    The precision is the ratio ``tp / (tp + fp)`` where ``tp`` is the number of
    true positives and ``fp`` the number of false positives. The precision is
    intuitively the ability of the classifier not to label a negative sample as
    positive.

    The recall is the ratio ``tp / (tp + fn)`` where ``tp`` is the number of
    true positives and ``fn`` the number of false negatives. The recall is
    intuitively the ability of the classifier to find all the positive samples.

    The F-beta score can be interpreted as a weighted harmonic mean of
    the precision and recall, where an F-beta score reaches its best
    value at 1 and worst score at 0.

    The F-beta score weights recall more than precision by a factor of
    ``beta``. ``beta == 1.0`` means recall and precision are equally important.

    The support is the number of occurrences of each class in ``y_true``.

    Support beyond term:`binary` targets is achieved by treating :term:`multiclass`
    and :term:`multilabel` data as a collection of binary problems, one for each
    label. For the :term:`binary` case, setting `average='binary'` will return
    metrics for `pos_label`. If `average` is not `'binary'`, `pos_label` is ignored
    and metrics for both classes are computed, then averaged or both returned (when
    `average=None`). Similarly, for :term:`multiclass` and :term:`multilabel` targets,
    metrics for all `labels` are either returned or averaged depending on the `average`
    parameter. Use `labels` specify the set of labels to calculate metrics for.

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

    Parameters
    ----------
    y_true : 1d array-like, or label indicator array / sparse matrix
        Ground truth (correct) target values.

    y_pred : 1d array-like, or label indicator array / sparse matrix
        Estimated targets as returned by a classifier.

    beta : float, default=1.0
        The strength of recall versus precision in the F-score.

    labels : array-like, default=None
        The set of labels to include when `average != 'binary'`, and their
        order if `average is None`. Labels present in the data can be
        excluded, for example in multiclass classification to exclude a "negative
        class". Labels not present in the data can be included and will be
        "assigned" 0 samples. For multilabel targets, labels are column indices.
        By default, all labels in `y_true` and `y_pred` are used in sorted order.

        .. versionchanged:: 0.17
           Parameter `labels` improved for multiclass problem.

    pos_label : int, float, bool or str, default=1
        The class to report if `average='binary'` and the data is binary,
        otherwise this parameter is ignored.
        For multiclass or multilabel targets, set `labels=[pos_label]` and
        `average != 'binary'` to report metrics for one label only.

    average : {'micro', 'macro', 'samples', 'weighted', 'binary'} or None,             default='binary'
        This parameter is required for multiclass/multilabel targets.
        If ``None``, the metrics for each class are returned. Otherwise, this
        determines the type of averaging performed on the data:

        ``'binary'``:
            Only report results for the class specified by ``pos_label``.
            This is applicable only if targets (``y_{true,pred}``) are binary.
        ``'micro'``:
            Calculate metrics globally by counting the total true positives,
            false negatives and false positives.
        ``'macro'``:
            Calculate metrics for each label, and find their unweighted
            mean.  This does not take label imbalance into account.
        ``'weighted'``:
            Calculate metrics for each label, and find their average weighted
            by support (the number of true instances for each label). This
            alters 'macro' to account for label imbalance; it can result in an
            F-score that is not between precision and recall.
        ``'samples'``:
            Calculate metrics for each instance, and find their average (only
            meaningful for multilabel classification where this differs from
            :func:`accuracy_score`).

    warn_for : list, tuple or set, for internal use
        This determines which warnings will be made in the case that this
        function is being used to return only one of its metrics.

    sample_weight : array-like of shape (n_samples,), default=None
        Sample weights.

    zero_division : {"warn", 0.0, 1.0, np.nan}, default="warn"
        Sets the value to return when there is a zero division:

        - recall: when there are no positive labels
        - precision: when there are no positive predictions
        - f-score: both

        Notes:

        - If set to "warn", this acts like 0, but a warning is also raised.
        - If set to `np.nan`, such values will be excluded from the average.

        .. versionadded:: 1.3
           `np.nan` option was added.

    Returns
    -------
    precision : float (if average is not None) or array of float, shape =        [n_unique_labels]
        Precision score.

    recall : float (if average is not None) or array of float, shape =        [n_unique_labels]
        Recall score.

    fbeta_score : float (if average is not None) or array of float, shape =        [n_unique_labels]
        F-beta score.

    support : None (if average is not None) or array of int, shape =        [n_unique_labels]
        The number of occurrences of each label in ``y_true``.

    Notes
    -----
    When ``true positive + false positive == 0``, precision is undefined.
    When ``true positive + false negative == 0``, recall is undefined. When
    ``true positive + false negative + false positive == 0``, f-score is
    undefined. In such cases, by default the metric will be set to 0, and
    ``UndefinedMetricWarning`` will be raised. This behavior can be modified
    with ``zero_division``.

    References
    ----------
    .. [1] `Wikipedia entry for the Precision and recall
           <https://en.wikipedia.org/wiki/Precision_and_recall>`_.

    .. [2] `Wikipedia entry for the F1-score
           <https://en.wikipedia.org/wiki/F1_score>`_.

    .. [3] `Discriminative Methods for Multi-labeled Classification Advances
           in Knowledge Discovery and Data Mining (2004), pp. 22-30 by Shantanu
           Godbole, Sunita Sarawagi
           <http://www.godbole.net/shantanu/pubs/multilabelsvm-pakdd04.pdf>`_.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.metrics import precision_recall_fscore_support
    >>> y_true = np.array(['cat', 'dog', 'pig', 'cat', 'dog', 'pig'])
    >>> y_pred = np.array(['cat', 'pig', 'dog', 'cat', 'cat', 'dog'])
    >>> precision_recall_fscore_support(y_true, y_pred, average='macro')
    (0.22..., 0.33..., 0.26..., None)
    >>> precision_recall_fscore_support(y_true, y_pred, average='micro')
    (0.33..., 0.33..., 0.33..., None)
    >>> precision_recall_fscore_support(y_true, y_pred, average='weighted')
    (0.22..., 0.33..., 0.26..., None)

    It is possible to compute per-label precisions, recalls, F1-scores and
    supports instead of averaging:

    >>> precision_recall_fscore_support(y_true, y_pred, average=None,
    ... labels=['pig', 'dog', 'cat'])
    (array([0.        , 0.        , 0.66...]),
     array([0., 0., 1.]), array([0. , 0. , 0.8]),
     array([2, 2, 2]))
    r   r   Nr-   r   r   rw   r	   r  	predictedr  rg   r   ztrue nor predictedr   r?   r   )r8   r   r   r   r   r   r   r0   isposinfrL   r3   r#   )r;   r>   r   rh   r   r   r   rX   r6   r   r   r   r   r   rN   rO   beta2r  r  f_scoredenomr`   s                         r7   r   r   \  s~   R '''#FFGVYOOF I%J
%#  C Aq\FAAAq!G$HAAAq!G$H&&))EB'BFF6NND11::bffX..55::bffX..55 !GE +{GX} I (FGX} F 
{4 
	  8+Y&  
 
 *	I		(""ioa&8A&=&=&=&=+iAAABB	{67;;;<<GW===>>fgx//r9   )r;   r>   rh   rX   raise_warning)rh   rX   r  c                   t          | |          \  } }t          | |          \  }} }|dk    rt          d|           t          | |||          }|j        dk    r9d}|rt          j        |t          d           t          j	        }t          j	        }	n|
                                \  }
}}}||z   }|
|z   }||z  }||z  }||z  }|
|z  }|dk    r8d	}|rt          j        |t          d           t          j	        }t          j	        }	|dk    r6|dk    rd
}nd}|rt          j        |t          d           t          j	        }n||z  }|
dk    r-d}|rt          j        |t          d           t          j	        }	n||z  }	||	fS )aa  Compute binary classification positive and negative likelihood ratios.

    The positive likelihood ratio is `LR+ = sensitivity / (1 - specificity)`
    where the sensitivity or recall is the ratio `tp / (tp + fn)` and the
    specificity is `tn / (tn + fp)`. The negative likelihood ratio is `LR- = (1
    - sensitivity) / specificity`. Here `tp` is the number of true positives,
    `fp` the number of false positives, `tn` is the number of true negatives and
    `fn` the number of false negatives. Both class likelihood ratios can be used
    to obtain post-test probabilities given a pre-test probability.

    `LR+` ranges from 1 to infinity. A `LR+` of 1 indicates that the probability
    of predicting the positive class is the same for samples belonging to either
    class; therefore, the test is useless. The greater `LR+` is, the more a
    positive prediction is likely to be a true positive when compared with the
    pre-test probability. A value of `LR+` lower than 1 is invalid as it would
    indicate that the odds of a sample being a true positive decrease with
    respect to the pre-test odds.

    `LR-` ranges from 0 to 1. The closer it is to 0, the lower the probability
    of a given sample to be a false negative. A `LR-` of 1 means the test is
    useless because the odds of having the condition did not change after the
    test. A value of `LR-` greater than 1 invalidates the classifier as it
    indicates an increase in the odds of a sample belonging to the positive
    class after being classified as negative. This is the case when the
    classifier systematically predicts the opposite of the true label.

    A typical application in medicine is to identify the positive/negative class
    to the presence/absence of a disease, respectively; the classifier being a
    diagnostic test; the pre-test probability of an individual having the
    disease can be the prevalence of such disease (proportion of a particular
    population found to be affected by a medical condition); and the post-test
    probabilities would be the probability that the condition is truly present
    given a positive test result.

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

    Parameters
    ----------
    y_true : 1d array-like, or label indicator array / sparse matrix
        Ground truth (correct) target values.

    y_pred : 1d array-like, or label indicator array / sparse matrix
        Estimated targets as returned by a classifier.

    labels : array-like, default=None
        List of labels to index the matrix. This may be used to select the
        positive and negative classes with the ordering `labels=[negative_class,
        positive_class]`. If `None` is given, those that appear at least once in
        `y_true` or `y_pred` are used in sorted order.

    sample_weight : array-like of shape (n_samples,), default=None
        Sample weights.

    raise_warning : bool, default=True
        Whether or not a case-specific warning message is raised when there is a
        zero division. Even if the error is not raised, the function will return
        nan in such cases.

    Returns
    -------
    (positive_likelihood_ratio, negative_likelihood_ratio) : tuple
        A tuple of two float, the first containing the Positive likelihood ratio
        and the second the Negative likelihood ratio.

    Warns
    -----
    When `false positive == 0`, the positive likelihood ratio is undefined.
    When `true negative == 0`, the negative likelihood ratio is undefined.
    When `true positive + false negative == 0` both ratios are undefined.
    In such cases, `UserWarning` will be raised if raise_warning=True.

    References
    ----------
    .. [1] `Wikipedia entry for the Likelihood ratios in diagnostic testing
           <https://en.wikipedia.org/wiki/Likelihood_ratios_in_diagnostic_testing>`_.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.metrics import class_likelihood_ratios
    >>> class_likelihood_ratios([0, 1, 0, 1, 0], [1, 1, 0, 0, 0])
    (np.float64(1.5), np.float64(0.75))
    >>> y_true = np.array(["non-cat", "cat", "non-cat", "cat", "non-cat"])
    >>> y_pred = np.array(["cat", "cat", "non-cat", "non-cat", "non-cat"])
    >>> class_likelihood_ratios(y_true, y_pred)
    (np.float64(1.33...), np.float64(0.66...))
    >>> y_true = np.array(["non-zebra", "zebra", "non-zebra", "zebra", "non-zebra"])
    >>> y_pred = np.array(["zebra", "zebra", "non-zebra", "non-zebra", "non-zebra"])
    >>> class_likelihood_ratios(y_true, y_pred)
    (np.float64(1.5), np.float64(0.75))

    To avoid ambiguities, use the notation `labels=[negative_class,
    positive_class]`

    >>> y_true = np.array(["non-cat", "cat", "non-cat", "cat", "non-cat"])
    >>> y_pred = np.array(["cat", "cat", "non-cat", "non-cat", "non-cat"])
    >>> class_likelihood_ratios(y_true, y_pred, labels=["non-cat", "cat"])
    (np.float64(1.5), np.float64(0.75))
    r?   z[class_likelihood_ratios only supports binary classification problems, got targets of type: rX   rh   r   z3samples of only one class were seen during testing r	   r  r   zAno samples of the positive class were present in the testing set z+no samples predicted for the positive classz;positive_likelihood_ratio ill-defined and being set to nan z;negative_likelihood_ratio ill-defined and being set to nan )r"   rU   rG   r   rL   r   r+   r   r0   r4   ravel)r;   r>   rh   rX   r  rR   r   r  positive_likelihood_rationegative_likelihood_ratior   r   r   r   support_possupport_negpos_num	pos_denomneg_num	neg_denoms                       r7   class_likelihood_ratiosr+  m  s   j #6622NFF+FF;;FFF7.47 7
 
 	

 
#	
 
 
B 
x6C 	:M#{q9999$&F!$&F!!BB2g2g{"$	{"$	 !UC >c;1====(*%(*%77QwwCS >c;1====(*%%(/)(;%77OC >c;1====(*%%(/)(;%$&???r9   c          
      >    t          | ||||d||          \  }}}}|S )ac  Compute the precision.

    The precision is the ratio ``tp / (tp + fp)`` where ``tp`` is the number of
    true positives and ``fp`` the number of false positives. The precision is
    intuitively the ability of the classifier not to label as positive a sample
    that is negative.

    The best value is 1 and the worst value is 0.

    Support beyond term:`binary` targets is achieved by treating :term:`multiclass`
    and :term:`multilabel` data as a collection of binary problems, one for each
    label. For the :term:`binary` case, setting `average='binary'` will return
    precision for `pos_label`. If `average` is not `'binary'`, `pos_label` is ignored
    and precision for both classes are computed, then averaged or both returned (when
    `average=None`). Similarly, for :term:`multiclass` and :term:`multilabel` targets,
    precision for all `labels` are either returned or averaged depending on the
    `average` parameter. Use `labels` specify the set of labels to calculate precision
    for.

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

    Parameters
    ----------
    y_true : 1d array-like, or label indicator array / sparse matrix
        Ground truth (correct) target values.

    y_pred : 1d array-like, or label indicator array / sparse matrix
        Estimated targets as returned by a classifier.

    labels : array-like, default=None
        The set of labels to include when `average != 'binary'`, and their
        order if `average is None`. Labels present in the data can be
        excluded, for example in multiclass classification to exclude a "negative
        class". Labels not present in the data can be included and will be
        "assigned" 0 samples. For multilabel targets, labels are column indices.
        By default, all labels in `y_true` and `y_pred` are used in sorted order.

        .. versionchanged:: 0.17
           Parameter `labels` improved for multiclass problem.

    pos_label : int, float, bool or str, default=1
        The class to report if `average='binary'` and the data is binary,
        otherwise this parameter is ignored.
        For multiclass or multilabel targets, set `labels=[pos_label]` and
        `average != 'binary'` to report metrics for one label only.

    average : {'micro', 'macro', 'samples', 'weighted', 'binary'} or None,             default='binary'
        This parameter is required for multiclass/multilabel targets.
        If ``None``, the metrics for each class are returned. Otherwise, this
        determines the type of averaging performed on the data:

        ``'binary'``:
            Only report results for the class specified by ``pos_label``.
            This is applicable only if targets (``y_{true,pred}``) are binary.
        ``'micro'``:
            Calculate metrics globally by counting the total true positives,
            false negatives and false positives.
        ``'macro'``:
            Calculate metrics for each label, and find their unweighted
            mean.  This does not take label imbalance into account.
        ``'weighted'``:
            Calculate metrics for each label, and find their average weighted
            by support (the number of true instances for each label). This
            alters 'macro' to account for label imbalance; it can result in an
            F-score that is not between precision and recall.
        ``'samples'``:
            Calculate metrics for each instance, and find their average (only
            meaningful for multilabel classification where this differs from
            :func:`accuracy_score`).

    sample_weight : array-like of shape (n_samples,), default=None
        Sample weights.

    zero_division : {"warn", 0.0, 1.0, np.nan}, default="warn"
        Sets the value to return when there is a zero division.

        Notes:

        - If set to "warn", this acts like 0, but a warning is also raised.
        - If set to `np.nan`, such values will be excluded from the average.

        .. versionadded:: 1.3
           `np.nan` option was added.

    Returns
    -------
    precision : float (if average is not None) or array of float of shape                 (n_unique_labels,)
        Precision of the positive class in binary classification or weighted
        average of the precision of each class for the multiclass task.

    See Also
    --------
    precision_recall_fscore_support : Compute precision, recall, F-measure and
        support for each class.
    recall_score :  Compute the ratio ``tp / (tp + fn)`` where ``tp`` is the
        number of true positives and ``fn`` the number of false negatives.
    PrecisionRecallDisplay.from_estimator : Plot precision-recall curve given
        an estimator and some data.
    PrecisionRecallDisplay.from_predictions : Plot precision-recall curve given
        binary class predictions.
    multilabel_confusion_matrix : Compute a confusion matrix for each class or
        sample.

    Notes
    -----
    When ``true positive + false positive == 0``, precision returns 0 and
    raises ``UndefinedMetricWarning``. This behavior can be
    modified with ``zero_division``.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.metrics import precision_score
    >>> y_true = [0, 1, 2, 0, 1, 2]
    >>> y_pred = [0, 2, 1, 0, 0, 1]
    >>> precision_score(y_true, y_pred, average='macro')
    0.22...
    >>> precision_score(y_true, y_pred, average='micro')
    0.33...
    >>> precision_score(y_true, y_pred, average='weighted')
    0.22...
    >>> precision_score(y_true, y_pred, average=None)
    array([0.66..., 0.        , 0.        ])
    >>> y_pred = [0, 0, 0, 0, 0, 0]
    >>> precision_score(y_true, y_pred, average=None)
    array([0.33..., 0.        , 0.        ])
    >>> precision_score(y_true, y_pred, average=None, zero_division=1)
    array([0.33..., 1.        , 1.        ])
    >>> precision_score(y_true, y_pred, average=None, zero_division=np.nan)
    array([0.33...,        nan,        nan])

    >>> # multilabel classification
    >>> y_true = [[0, 0, 0], [1, 1, 1], [0, 1, 1]]
    >>> y_pred = [[0, 0, 0], [1, 1, 1], [1, 1, 0]]
    >>> precision_score(y_true, y_pred, average=None)
    array([0.5, 1. , 1. ])
    )r  rh   r   r   r   rX   r6   r   )	r;   r>   rh   r   r   rX   r6   prO   s	            r7   precision_scorer/    s@    P 1##	 	 	JAq!Q Hr9   c          
      >    t          | ||||d||          \  }}}}|S )aT  Compute the recall.

    The recall is the ratio ``tp / (tp + fn)`` where ``tp`` is the number of
    true positives and ``fn`` the number of false negatives. The recall is
    intuitively the ability of the classifier to find all the positive samples.

    The best value is 1 and the worst value is 0.

    Support beyond term:`binary` targets is achieved by treating :term:`multiclass`
    and :term:`multilabel` data as a collection of binary problems, one for each
    label. For the :term:`binary` case, setting `average='binary'` will return
    recall for `pos_label`. If `average` is not `'binary'`, `pos_label` is ignored
    and recall for both classes are computed then averaged or both returned (when
    `average=None`). Similarly, for :term:`multiclass` and :term:`multilabel` targets,
    recall for all `labels` are either returned or averaged depending on the `average`
    parameter. Use `labels` specify the set of labels to calculate recall for.

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

    Parameters
    ----------
    y_true : 1d array-like, or label indicator array / sparse matrix
        Ground truth (correct) target values.

    y_pred : 1d array-like, or label indicator array / sparse matrix
        Estimated targets as returned by a classifier.

    labels : array-like, default=None
        The set of labels to include when `average != 'binary'`, and their
        order if `average is None`. Labels present in the data can be
        excluded, for example in multiclass classification to exclude a "negative
        class". Labels not present in the data can be included and will be
        "assigned" 0 samples. For multilabel targets, labels are column indices.
        By default, all labels in `y_true` and `y_pred` are used in sorted order.

        .. versionchanged:: 0.17
           Parameter `labels` improved for multiclass problem.

    pos_label : int, float, bool or str, default=1
        The class to report if `average='binary'` and the data is binary,
        otherwise this parameter is ignored.
        For multiclass or multilabel targets, set `labels=[pos_label]` and
        `average != 'binary'` to report metrics for one label only.

    average : {'micro', 'macro', 'samples', 'weighted', 'binary'} or None,             default='binary'
        This parameter is required for multiclass/multilabel targets.
        If ``None``, the metrics for each class are returned. Otherwise, this
        determines the type of averaging performed on the data:

        ``'binary'``:
            Only report results for the class specified by ``pos_label``.
            This is applicable only if targets (``y_{true,pred}``) are binary.
        ``'micro'``:
            Calculate metrics globally by counting the total true positives,
            false negatives and false positives.
        ``'macro'``:
            Calculate metrics for each label, and find their unweighted
            mean.  This does not take label imbalance into account.
        ``'weighted'``:
            Calculate metrics for each label, and find their average weighted
            by support (the number of true instances for each label). This
            alters 'macro' to account for label imbalance; it can result in an
            F-score that is not between precision and recall. Weighted recall
            is equal to accuracy.
        ``'samples'``:
            Calculate metrics for each instance, and find their average (only
            meaningful for multilabel classification where this differs from
            :func:`accuracy_score`).

    sample_weight : array-like of shape (n_samples,), default=None
        Sample weights.

    zero_division : {"warn", 0.0, 1.0, np.nan}, default="warn"
        Sets the value to return when there is a zero division.

        Notes:

        - If set to "warn", this acts like 0, but a warning is also raised.
        - If set to `np.nan`, such values will be excluded from the average.

        .. versionadded:: 1.3
           `np.nan` option was added.

    Returns
    -------
    recall : float (if average is not None) or array of float of shape              (n_unique_labels,)
        Recall of the positive class in binary classification or weighted
        average of the recall of each class for the multiclass task.

    See Also
    --------
    precision_recall_fscore_support : Compute precision, recall, F-measure and
        support for each class.
    precision_score : Compute the ratio ``tp / (tp + fp)`` where ``tp`` is the
        number of true positives and ``fp`` the number of false positives.
    balanced_accuracy_score : Compute balanced accuracy to deal with imbalanced
        datasets.
    multilabel_confusion_matrix : Compute a confusion matrix for each class or
        sample.
    PrecisionRecallDisplay.from_estimator : Plot precision-recall curve given
        an estimator and some data.
    PrecisionRecallDisplay.from_predictions : Plot precision-recall curve given
        binary class predictions.

    Notes
    -----
    When ``true positive + false negative == 0``, recall returns 0 and raises
    ``UndefinedMetricWarning``. This behavior can be modified with
    ``zero_division``.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.metrics import recall_score
    >>> y_true = [0, 1, 2, 0, 1, 2]
    >>> y_pred = [0, 2, 1, 0, 0, 1]
    >>> recall_score(y_true, y_pred, average='macro')
    0.33...
    >>> recall_score(y_true, y_pred, average='micro')
    0.33...
    >>> recall_score(y_true, y_pred, average='weighted')
    0.33...
    >>> recall_score(y_true, y_pred, average=None)
    array([1., 0., 0.])
    >>> y_true = [0, 0, 0, 0, 0, 0]
    >>> recall_score(y_true, y_pred, average=None)
    array([0.5, 0. , 0. ])
    >>> recall_score(y_true, y_pred, average=None, zero_division=1)
    array([0.5, 1. , 1. ])
    >>> recall_score(y_true, y_pred, average=None, zero_division=np.nan)
    array([0.5, nan, nan])

    >>> # multilabel classification
    >>> y_true = [[0, 0, 0], [1, 1, 1], [0, 1, 1]]
    >>> y_pred = [[0, 0, 0], [1, 1, 1], [1, 1, 0]]
    >>> recall_score(y_true, y_pred, average=None)
    array([1. , 1. , 0.5])
    )r  r-  r   )	r;   r>   rh   r   r   rX   r6   rO   rs	            r7   recall_scorer2    s@    R 1##	 	 	JAq!Q Hr9   )r;   r>   rX   adjusted)rX   r3  c                   t          | ||          }t          j        dd          5  t          j        |          |                    d          z  }ddd           n# 1 swxY w Y   t          j        t          j        |                    r/t          j        d           |t          j        |                    }t          j	        |          }|r!t          |          }d|z  }||z  }|d|z
  z  }|S )a	  Compute the balanced accuracy.

    The balanced accuracy in binary and multiclass classification problems to
    deal with imbalanced datasets. It is defined as the average of recall
    obtained on each class.

    The best value is 1 and the worst value is 0 when ``adjusted=False``.

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

    .. versionadded:: 0.20

    Parameters
    ----------
    y_true : array-like of shape (n_samples,)
        Ground truth (correct) target values.

    y_pred : array-like of shape (n_samples,)
        Estimated targets as returned by a classifier.

    sample_weight : array-like of shape (n_samples,), default=None
        Sample weights.

    adjusted : bool, default=False
        When true, the result is adjusted for chance, so that random
        performance would score 0, while keeping perfect performance at a score
        of 1.

    Returns
    -------
    balanced_accuracy : float
        Balanced accuracy score.

    See Also
    --------
    average_precision_score : Compute average precision (AP) from prediction
        scores.
    precision_score : Compute the precision score.
    recall_score : Compute the recall score.
    roc_auc_score : Compute Area Under the Receiver Operating Characteristic
        Curve (ROC AUC) from prediction scores.

    Notes
    -----
    Some literature promotes alternative definitions of balanced accuracy. Our
    definition is equivalent to :func:`accuracy_score` with class-balanced
    sample weights, and shares desirable properties with the binary case.
    See the :ref:`User Guide <balanced_accuracy_score>`.

    References
    ----------
    .. [1] Brodersen, K.H.; Ong, C.S.; Stephan, K.E.; Buhmann, J.M. (2010).
           The balanced accuracy and its posterior distribution.
           Proceedings of the 20th International Conference on Pattern
           Recognition, 3121-24.
    .. [2] John. D. Kelleher, Brian Mac Namee, Aoife D'Arcy, (2015).
           `Fundamentals of Machine Learning for Predictive Data Analytics:
           Algorithms, Worked Examples, and Case Studies
           <https://mitpress.mit.edu/books/fundamentals-machine-learning-predictive-data-analytics>`_.

    Examples
    --------
    >>> from sklearn.metrics import balanced_accuracy_score
    >>> y_true = [0, 1, 0, 0, 1, 0]
    >>> y_pred = [0, 1, 0, 0, 0, 1]
    >>> balanced_accuracy_score(y_true, y_pred)
    np.float64(0.625)
    r   r   )divideinvalidr-   r\   Nz%y_pred contains classes not in y_true)r   r0   r   diagr   r   isnanr   r+   meanrF   )	r;   r>   rX   r3  r   	per_classrc   r   chances	            r7   balanced_accuracy_scorer<  	  s,   \ 	}EEEA	Hh	7	7	7 / /GAJJA.	/ / / / / / / / / / / / / / /	vbhy!!"" 4=>>>rx	2223	GIE 	NN	YVLs   ,A!!A%(A%left)r;   r>   rh   target_namesrX   digitsoutput_dictr6   )rh   r>  rX   r?  r@  r6   c          	         t          | |          \  } }t          | |          \  }} }|t          | |          }d}	nt          j        |          }d}	|dk    s|dk    o0|	 p-t          |          t          t          | |                    k    }
|t          |          t          |          k    r|	rCt          j        d	                    t          |          t          |                               n=t          d	                    t          |          t          |                              |d |D             }g d	}t          | ||d||
          \  }}}}t          |||||          }|                    d          rd}nd}|rQd |D             }|                                D ]/\  }}t          t          |d |D                                 ||<   0nd}t!          d |D                       }t!          |t          |          |          }ddt          |          z  z   } |j	        dg|R d|i}|dz  }d}|D ]}| |j	        |||dz  }|dz  }|D ]}|                    d          r|
rd}n|dz   }t          | |||||
          \  }}} }!||| t          j        |          g}"|r+t          t          |d |"D                                 ||<   |dk    r"d}#| |#j	        |ddg|"dd         R ||dz  }| |j	        |g|"R ||dz  }|r)d|                                v r|d         d          |d<   |S |S )!av  Build a text report showing the main classification metrics.

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

    Parameters
    ----------
    y_true : 1d array-like, or label indicator array / sparse matrix
        Ground truth (correct) target values.

    y_pred : 1d array-like, or label indicator array / sparse matrix
        Estimated targets as returned by a classifier.

    labels : array-like of shape (n_labels,), default=None
        Optional list of label indices to include in the report.

    target_names : array-like of shape (n_labels,), default=None
        Optional display names matching the labels (same order).

    sample_weight : array-like of shape (n_samples,), default=None
        Sample weights.

    digits : int, default=2
        Number of digits for formatting output floating point values.
        When ``output_dict`` is ``True``, this will be ignored and the
        returned values will not be rounded.

    output_dict : bool, default=False
        If True, return output as dict.

        .. versionadded:: 0.20

    zero_division : {"warn", 0.0, 1.0, np.nan}, default="warn"
        Sets the value to return when there is a zero division. If set to
        "warn", this acts as 0, but warnings are also raised.

        .. versionadded:: 1.3
           `np.nan` option was added.

    Returns
    -------
    report : str or dict
        Text summary of the precision, recall, F1 score for each class.
        Dictionary returned if output_dict is True. Dictionary has the
        following structure::

            {'label 1': {'precision':0.5,
                         'recall':1.0,
                         'f1-score':0.67,
                         'support':1},
             'label 2': { ... },
              ...
            }

        The reported averages include macro average (averaging the unweighted
        mean per label), weighted average (averaging the support-weighted mean
        per label), and sample average (only for multilabel classification).
        Micro average (averaging the total true positives, false negatives and
        false positives) is only shown for multi-label or multi-class
        with a subset of classes, because it corresponds to accuracy
        otherwise and would be the same for all metrics.
        See also :func:`precision_recall_fscore_support` for more details
        on averages.

        Note that in binary classification, recall of the positive class
        is also known as "sensitivity"; recall of the negative class is
        "specificity".

    See Also
    --------
    precision_recall_fscore_support: Compute precision, recall, F-measure and
        support for each class.
    confusion_matrix: Compute confusion matrix to evaluate the accuracy of a
        classification.
    multilabel_confusion_matrix: Compute a confusion matrix for each class or sample.

    Examples
    --------
    >>> from sklearn.metrics import classification_report
    >>> y_true = [0, 1, 2, 2, 2]
    >>> y_pred = [0, 0, 2, 2, 1]
    >>> target_names = ['class 0', 'class 1', 'class 2']
    >>> print(classification_report(y_true, y_pred, target_names=target_names))
                  precision    recall  f1-score   support
    <BLANKLINE>
         class 0       0.50      1.00      0.67         1
         class 1       0.00      0.00      0.00         1
         class 2       1.00      0.67      0.80         3
    <BLANKLINE>
        accuracy                           0.60         5
       macro avg       0.50      0.56      0.49         5
    weighted avg       0.70      0.60      0.61         5
    <BLANKLINE>
    >>> y_pred = [1, 1, 0]
    >>> y_true = [1, 1, 1]
    >>> print(classification_report(y_true, y_pred, labels=[1, 2, 3]))
                  precision    recall  f1-score   support
    <BLANKLINE>
               1       1.00      0.67      0.80         3
               2       0.00      0.00      0.00         0
               3       0.00      0.00      0.00         0
    <BLANKLINE>
       micro avg       1.00      0.67      0.80         3
       macro avg       0.33      0.22      0.27         3
    weighted avg       1.00      0.67      0.80         3
    <BLANKLINE>
    NFTr@   r?   z:labels size, {0}, does not match size of target_names, {1}zeNumber of classes, {0}, does not match size of target_names, {1}. Try specifying the labels parameterc                     g | ]}d |z  S )z%srq   )rr   ls     r7   r}   z)classification_report.<locals>.<listcomp>
  s    111Qq111r9   )r  r  zf1-scoresupport)rh   r   rX   r6   rE   )r   r   r   r   )r   r   r   c                 0    i | ]}|d          |dd         S )r   r-   Nrq   )rr   r
  s     r7   ru   z)classification_report.<locals>.<dictcomp>
  s&    ===uuQxqrr===r9   c                 ,    g | ]}t          |          S rq   r3   rr   rn   s     r7   r}   z)classification_report.<locals>.<listcomp>
  s    3M3M3ME!HH3M3M3Mr9   zweighted avgc              3   4   K   | ]}t          |          V  d S N)rF   )rr   cns     r7   	<genexpr>z(classification_report.<locals>.<genexpr>
  s(      88RR888888r9   z{:>{width}s} z {:>9} widthz

zD{:>{width}s}  {:>9.{digits}f} {:>9.{digits}f} {:>9.{digits}f} {:>9}
)rN  r?  
r   accuracyz avgc                 ,    g | ]}t          |          S rq   rG  rH  s     r7   r}   z)classification_report.<locals>.<listcomp>
  s    :Q:Q:Q588:Q:Q:Qr9   zB{:>{width}s}  {:>9.{digits}} {:>9.{digits}} {:>9.{digits}f} {:>9}
r	   r  )r"   rU   r%   r0   ra   setrF   r   r+   rH   rG   r   ziprM   itemsdictr   r   keys)$r;   r>   rh   r>  rX   r?  r@  r6   rR   labels_givenmicro_is_accuracyheadersr.  r1  f1srowsr  report_dictr
  scoreslongest_last_line_heading
name_widthrN  head_fmtreportrow_fmtrowr   line_headingavg_pavg_ravg_f1rO   avgrow_fmt_accuracys$                                       r7   classification_reportrk  	  s   N #6622NFF+FF;;FFF~vv..F##  </E6X3E OS[[Cff0M0M,N,NN  CKK3|3D3D$D$D 	MLSSKK\!2!2     "F3v;;L0A0ABB  
 11&111<<<G1##  KAq"a |Q2q))D&& 9C8 =====(..00 	P 	PME6!%c'3M3Mf3M3M3M&N&N!O!OK	P %3!88<88888
J$= > >GG"XG%<< ;g;;;U;;&G 	G 	GCngncvFFFFFF$ # Y Yg&& 	,+< 	,%LL"V+L #B''#
 #
 #
ufa eVRVAYY/ 	Y(,S:Q:QS:Q:Q:Q-R-R(S(SK%%z))! ! 1*1 "b+.qrr7 :?    .'.XXX5QWXXXX ))++++&1*&=k&JK
#r9   c                   t          | |          \  } }t          | |          \  }} }t          | ||           |d}nt          j        |          }|                    d          r5t          | |z
  |          }|| j        d         | j        d         z  |z  z  S |dv r#t          t          | |k    |d	                    S t          d
                    |                    )a
  Compute the average Hamming loss.

    The Hamming loss is the fraction of labels that are incorrectly predicted.

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

    Parameters
    ----------
    y_true : 1d array-like, or label indicator array / sparse matrix
        Ground truth (correct) labels.

    y_pred : 1d array-like, or label indicator array / sparse matrix
        Predicted labels, as returned by a classifier.

    sample_weight : array-like of shape (n_samples,), default=None
        Sample weights.

        .. versionadded:: 0.18

    Returns
    -------
    loss : float or int
        Return the average Hamming loss between element of ``y_true`` and
        ``y_pred``.

    See Also
    --------
    accuracy_score : Compute the accuracy score. By default, the function will
        return the fraction of correct predictions divided by the total number
        of predictions.
    jaccard_score : Compute the Jaccard similarity coefficient score.
    zero_one_loss : Compute the Zero-one classification loss. By default, the
        function will return the percentage of imperfectly predicted subsets.

    Notes
    -----
    In multiclass classification, the Hamming loss corresponds to the Hamming
    distance between ``y_true`` and ``y_pred`` which is equivalent to the
    subset ``zero_one_loss`` function, when `normalize` parameter is set to
    True.

    In multilabel classification, the Hamming loss is different from the
    subset zero-one loss. The zero-one loss considers the entire set of labels
    for a given sample incorrect if it does not entirely match the true set of
    labels. Hamming loss is more forgiving in that it penalizes only the
    individual labels.

    The Hamming loss is upperbounded by the subset zero-one loss, when
    `normalize` parameter is set to True. It is always between 0 and 1,
    lower being better.

    References
    ----------
    .. [1] Grigorios Tsoumakas, Ioannis Katakis. Multi-Label Classification:
           An Overview. International Journal of Data Warehousing & Mining,
           3(3), 1-13, July-September 2007.

    .. [2] `Wikipedia entry on the Hamming distance
           <https://en.wikipedia.org/wiki/Hamming_distance>`_.

    Examples
    --------
    >>> from sklearn.metrics import hamming_loss
    >>> y_pred = [1, 2, 3, 4]
    >>> y_true = [2, 2, 3, 4]
    >>> hamming_loss(y_true, y_pred)
    0.25

    In the multilabel case with binary label indicators:

    >>> import numpy as np
    >>> hamming_loss(np.array([[0, 1], [1, 1]]), np.zeros((2, 2)))
    0.75
    Nr   rE   r   r   r-   rD   Tr_   rC   )r"   rU   r   r0   r9  rM   r&   rL   r3   r   rG   rH   )r;   r>   rX   rR   weight_averagen_differencess         r7   hamming_lossro  
  s    f #6622NFF+FF;;FFFFFM::://&& @%fvo]SSSQ&,q/ AN RSS	+	+	+Xf.QUVVVWWW/66v>>???r9   r;   r>   rW   rX   rh   )rW   rX   rh   c                   t          |dt          j        t          j        t          j        g          }t          || |           t                      }||                    |           n|                    |            t          |j	                  dk    rV|-t          d                    |j	        d                             t          d                    |j	                            |                    |           }|j        d         dk    rt          j        d|z
  |d          }|j        dk    r|ddt          j        f         }|j        d         dk    rt          j        d|z
  |d          }t          j        |j                  j        }|                    d          }t          j        |dt          j        |          	          st/          j        d
t2                     t          j        ||d|z
            }t          |          }t          |j	                  |j        d         k    rh|?t          d                    |j        d         |j        d         |j	                            t          d                    |j	                            t7          ||                              d           }	t9          t;          |	||                    S )aI	  Log loss, aka logistic loss or cross-entropy loss.

    This is the loss function used in (multinomial) logistic regression
    and extensions of it such as neural networks, defined as the negative
    log-likelihood of a logistic model that returns ``y_pred`` probabilities
    for its training data ``y_true``.
    The log loss is only defined for two or more labels.
    For a single sample with true label :math:`y \in \{0,1\}` and
    a probability estimate :math:`p = \operatorname{Pr}(y = 1)`, the log
    loss is:

    .. math::
        L_{\log}(y, p) = -(y \log (p) + (1 - y) \log (1 - p))

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

    Parameters
    ----------
    y_true : array-like or label indicator matrix
        Ground truth (correct) labels for n_samples samples.

    y_pred : array-like of float, shape = (n_samples, n_classes) or (n_samples,)
        Predicted probabilities, as returned by a classifier's
        predict_proba method. If ``y_pred.shape = (n_samples,)``
        the probabilities provided are assumed to be that of the
        positive class. The labels in ``y_pred`` are assumed to be
        ordered alphabetically, as done by
        :class:`~sklearn.preprocessing.LabelBinarizer`.

        `y_pred` values are clipped to `[eps, 1-eps]` where `eps` is the machine
        precision for `y_pred`'s dtype.

    normalize : bool, default=True
        If true, return the mean loss per sample.
        Otherwise, return the sum of the per-sample losses.

    sample_weight : array-like of shape (n_samples,), default=None
        Sample weights.

    labels : array-like, default=None
        If not provided, labels will be inferred from y_true. If ``labels``
        is ``None`` and ``y_pred`` has shape (n_samples,) the labels are
        assumed to be binary and are inferred from ``y_true``.

        .. versionadded:: 0.18

    Returns
    -------
    loss : float
        Log loss, aka logistic loss or cross-entropy loss.

    Notes
    -----
    The logarithm used is the natural logarithm (base-e).

    References
    ----------
    C.M. Bishop (2006). Pattern Recognition and Machine Learning. Springer,
    p. 209.

    Examples
    --------
    >>> from sklearn.metrics import log_loss
    >>> log_loss(["spam", "ham", "ham", "spam"],
    ...          [[.1, .9], [.9, .1], [.8, .2], [.35, .65]])
    0.21616...
    F	ensure_2drl   Nr-   zly_true contains only one label ({0}). Please provide the true labels explicitly through the labels argument.r   zLThe labels array needs to contain at least two labels for log_loss, got {0}.r\   )rtolzEThe y_pred values do not sum to one. Make sure to pass probabilities.zy_true and y_pred contain different number of classes {0}, {1}. Please provide the true labels explicitly through the labels argument. Classes found in y_true: {2}z^The number of classes in labels is different from that in y_pred. Classes found in labels: {0}r_   )r   r0   r1   float32float16r   r   r   rF   r   rG   rH   r   rL   appendr   newaxisfinforl   epsr   allcloser   r   r+   r   clipr   r3   r   )
r;   r>   rW   rX   rh   r   transformed_labelsrz  
y_pred_sumlosss
             r7   log_lossr  >  s   \ %
BJ
'K  F FFM:::			B
v
v
2;1>##)6"+a.#9#9   !6"+..   f--"a''Y""$6Q
 
 
 {a2:&|A!1v:vA666
(6<
 
 
$C ##J;z1273<<888 
S	
 	
 	
 WVS!c'**F %%788
2;6<?**> %f&,Q/a"+    $fR[11   $f--11q1999D$KKKLLLr9   )r;   pred_decisionrh   rX   r   c                   t          | ||           t          |d          }t          |           } t          j        ||n|           }|j        dk    rO|j        dk    r-t          d| j        d          d|j         d	|j                   |j        |j        d         k    r>|t          d
          t          d| j        d          d|j         d	|j                   ||}t                      }|
                    |           |                    |           } t          j        |t                    }d|t          j        | j        d                   | f<   ||          }|t          j        ||                             | j        d         d          d          z  }nvt          |          }t          j        |          }t%          d          }|                    |           dddf         } 	 | |z  }n# t(          $ r t)          d          w xY wd|z
  }	t          j        |	dd|	           t          j        |	|          S )aG  Average hinge loss (non-regularized).

    In binary class case, assuming labels in y_true are encoded with +1 and -1,
    when a prediction mistake is made, ``margin = y_true * pred_decision`` is
    always negative (since the signs disagree), implying ``1 - margin`` is
    always greater than 1.  The cumulated hinge loss is therefore an upper
    bound of the number of mistakes made by the classifier.

    In multiclass case, the function expects that either all the labels are
    included in y_true or an optional labels argument is provided which
    contains all the labels. The multilabel margin is calculated according
    to Crammer-Singer's method. As in the binary case, the cumulated hinge loss
    is an upper bound of the number of mistakes made by the classifier.

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

    Parameters
    ----------
    y_true : array-like of shape (n_samples,)
        True target, consisting of integers of two values. The positive label
        must be greater than the negative label.

    pred_decision : array-like of shape (n_samples,) or (n_samples, n_classes)
        Predicted decisions, as output by decision_function (floats).

    labels : array-like, default=None
        Contains all the labels for the problem. Used in multiclass hinge loss.

    sample_weight : array-like of shape (n_samples,), default=None
        Sample weights.

    Returns
    -------
    loss : float
        Average hinge loss.

    References
    ----------
    .. [1] `Wikipedia entry on the Hinge loss
           <https://en.wikipedia.org/wiki/Hinge_loss>`_.

    .. [2] Koby Crammer, Yoram Singer. On the Algorithmic
           Implementation of Multiclass Kernel-based Vector
           Machines. Journal of Machine Learning Research 2,
           (2001), 265-292.

    .. [3] `L1 AND L2 Regularization for Multiclass Hinge Loss Models
           by Robert C. Moore, John DeNero
           <https://storage.googleapis.com/pub-tools-public-publication-data/pdf/37362.pdf>`_.

    Examples
    --------
    >>> from sklearn import svm
    >>> from sklearn.metrics import hinge_loss
    >>> X = [[0], [1]]
    >>> y = [-1, 1]
    >>> est = svm.LinearSVC(random_state=0)
    >>> est.fit(X, y)
    LinearSVC(random_state=0)
    >>> pred_decision = est.decision_function([[-2], [3], [0.5]])
    >>> pred_decision
    array([-2.18...,  2.36...,  0.09...])
    >>> hinge_loss([-1, 1, 1], pred_decision)
    np.float64(0.30...)

    In the multiclass case:

    >>> import numpy as np
    >>> X = np.array([[0], [1], [2], [3]])
    >>> Y = np.array([0, 1, 2, 3])
    >>> labels = np.array([0, 1, 2, 3])
    >>> est = svm.LinearSVC()
    >>> est.fit(X, Y)
    LinearSVC()
    >>> pred_decision = est.decision_function([[-1], [2], [3]])
    >>> y_true = [0, 2, 3]
    >>> hinge_loss(y_true, pred_decision, labels=labels)
    np.float64(0.56...)
    F)rs  Nr	   r-   zThe shape of pred_decision cannot be 1d arraywith a multiclass target. pred_decision shape must be (n_samples, n_classes), that is (r   z, z). Got: zDPlease include all labels in y_true or pass labels as third argumentzThe shape of pred_decision is not consistent with the number of classes. With a multiclass target, pred_decision shape must be (n_samples, n_classes), that is (rk   r   r\   )	neg_labelz+pred_decision should be an array of floats.)outr   )r   r   r   r0   rK   r   r   rG   rL   r   r   r   	ones_likeboolr   r   r   r"  r   fit_transformrJ   r|  r   )
r;   r  rh   rX   y_true_uniquer   r  marginlbinlossess
             r7   
hinge_lossr    s   r FM=AAA???M&!!FI(:ffGGMA""/ LO/ / (5'9/ / ',	/ /   !4Q!777~ 7  
 !2
 Q2 2
 ,9+=2 2 */2 2   >"F^^
vf%%|M66638RYv|A''/0u%"&t,44V\!_bIIPQRRRR %]33//+++##F++AAAqD1	Km+FF 	K 	K 	KIJJJ	K ZFGFAt((((:fm4444s   8G> >H
deprecated)r;   y_probarX   r   y_prob)rX   r   r  c                $   |$t          |t                    st          d          |t          j        dt
                     |}t          |           } t          |          }t          |            t          |           t          | ||           t          | d          }|dk    rt          d| d          |
                                d	k    rt          d
          |                                dk     rt          d          	 t          ||           }n<# t          $ r/ t          j        |           }|j        j        dvr	|d         }n Y nw xY wt          j        | |k    t$                    } t          j        | |z
  dz  |          S )ao  Compute the Brier score loss.

    The smaller the Brier score loss, the better, hence the naming with "loss".
    The Brier score measures the mean squared difference between the predicted
    probability and the actual outcome. The Brier score always
    takes on a value between zero and one, since this is the largest
    possible difference between a predicted probability (which must be
    between zero and one) and the actual outcome (which can take on values
    of only 0 and 1). It can be decomposed as the sum of refinement loss and
    calibration loss.

    The Brier score is appropriate for binary and categorical outcomes that
    can be structured as true or false, but is inappropriate for ordinal
    variables which can take on three or more values (this is because the
    Brier score assumes that all possible outcomes are equivalently
    "distant" from one another). Which label is considered to be the positive
    label is controlled via the parameter `pos_label`, which defaults to
    the greater label unless `y_true` is all 0 or all -1, in which case
    `pos_label` defaults to 1.

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

    Parameters
    ----------
    y_true : array-like of shape (n_samples,)
        True targets.

    y_proba : array-like of shape (n_samples,)
        Probabilities of the positive class.

    sample_weight : array-like of shape (n_samples,), default=None
        Sample weights.

    pos_label : int, float, bool or str, default=None
        Label of the positive class. `pos_label` will be inferred in the
        following manner:

        * if `y_true` in {-1, 1} or {0, 1}, `pos_label` defaults to 1;
        * else if `y_true` contains string, an error will be raised and
          `pos_label` should be explicitly specified;
        * otherwise, `pos_label` defaults to the greater label,
          i.e. `np.unique(y_true)[-1]`.

    y_prob : array-like of shape (n_samples,)
        Probabilities of the positive class.

        .. deprecated:: 1.5
            `y_prob` is deprecated and will be removed in 1.7. Use
            `y_proba` instead.

    Returns
    -------
    score : float
        Brier score loss.

    References
    ----------
    .. [1] `Wikipedia entry for the Brier score
            <https://en.wikipedia.org/wiki/Brier_score>`_.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.metrics import brier_score_loss
    >>> y_true = np.array([0, 1, 1, 0])
    >>> y_true_categorical = np.array(["spam", "ham", "ham", "spam"])
    >>> y_prob = np.array([0.1, 0.9, 0.8, 0.3])
    >>> brier_score_loss(y_true, y_prob)
    np.float64(0.037...)
    >>> brier_score_loss(y_true, 1-y_prob, pos_label=0)
    np.float64(0.037...)
    >>> brier_score_loss(y_true_categorical, y_prob, pos_label="ham")
    np.float64(0.037...)
    >>> brier_score_loss(y_true, np.array(y_prob) > 0.5)
    np.float64(0.0)
    Nz`y_prob` and `y_proba` cannot be both specified. Please use `y_proba` only as `y_prob` is deprecated in v1.5 and will be removed in v1.7.z_y_prob was deprecated in version 1.5 and will be removed in 1.7.Please use ``y_proba`` instead.r;   r<   r?   zCOnly binary classification is supported. The type of the target is r  r-   z'y_proba contains values greater than 1.r   z$y_proba contains values less than 0.)OUSr   r	   r   )r.   r/   rG   r   r+   FutureWarningr   r   r   r$   r   r   r'   r0   rK   rl   r   r   r2   r   )r;   r  rX   r   r  rR   classess          r7   brier_score_lossr  r  s   x :fc#:#:N
 
 	
 2 	
 	
 	
 &!!F7##GfgFG];;;Fx888F  
 
 	

 {{}}qBCCC{{}}q?@@@	0FCC		   )F##=_44  II I Xf	)3//F:v'A-}EEEEs   D 6EE)r;   r>   rX   rh   r!  c                   t          |dd          }t          || |           t          |          dk     r+d}t          j        |t
                     t          d          S t          | |d||          }t          ||           }t          j
        | d	          \  }}t          j        ||
          }	|	|                                z  }
t          j        |
t          |           df          }t          | |d||          }d||z  z
  S )a  
    :math:`D^2` score function, fraction of log loss explained.

    Best possible score is 1.0 and it can be negative (because the model can be
    arbitrarily worse). A model that always predicts the per-class proportions
    of `y_true`, disregarding the input features, gets a D^2 score of 0.0.

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

    .. versionadded:: 1.5

    Parameters
    ----------
    y_true : array-like or label indicator matrix
        The actuals labels for the n_samples samples.

    y_pred : array-like of shape (n_samples, n_classes) or (n_samples,)
        Predicted probabilities, as returned by a classifier's
        predict_proba method. If ``y_pred.shape = (n_samples,)``
        the probabilities provided are assumed to be that of the
        positive class. The labels in ``y_pred`` are assumed to be
        ordered alphabetically, as done by
        :class:`~sklearn.preprocessing.LabelBinarizer`.

    sample_weight : array-like of shape (n_samples,), default=None
        Sample weights.

    labels : array-like, default=None
        If not provided, labels will be inferred from y_true. If ``labels``
        is ``None`` and ``y_pred`` has shape (n_samples,) the labels are
        assumed to be binary and are inferred from ``y_true``.

    Returns
    -------
    d2 : float or ndarray of floats
        The D^2 score.

    Notes
    -----
    This is not a symmetric function.

    Like R^2, D^2 score may be negative (it need not actually be the square of
    a quantity D).

    This metric is not well-defined for a single sample and will return a NaN
    value if n_samples is less than two.
    Fnumericrr  r	   z9D^2 score is not well-defined with less than two samples.r4   rp  T)return_inverser   r-   )r   r   r)   r   r+   r
   r3   r  r(   r0   rK   bincountr   tilerF   )r;   r>   rX   rh   r  r   r`   rO   y_value_indicescountsr  y_pred_nullr   s                r7   d2_log_loss_scorer    s*   r 5	BBBFFFM:::FaIc1222U|| #  I #=&99G6$???A[':::Fgkkmm#F'&3v;;"233K #  K 	K'((r9   )r+   rJ  )T__doc__r   numbersr   r   numpyr0   scipy.sparser   r   r   scipy.specialr   
exceptionsr
   preprocessingr   r   utilsr   r   r   r   utils._array_apir   r   r   r   r   r   r   r   r   r   r   r   utils._param_validationr   r   r   r    r!   utils._uniquer"   utils.extmathr#   utils.multiclassr$   r%   utils.sparsefuncsr&   utils.validationr'   r(   r)   r8   rU   rd   r   r   r   r/   r   r   r   r   r   r   r   r   r  tuplerR  r   r+  r/  r2  r<  rk  ro  r  r  r  r  rq   r9   r7   <module>r     s     " " " " " " " "     9 9 9 9 9 9 9 9 9 9       / / / / / / 8 8 8 8 8 8 8 8                                                    * ) ) ) ) ) ' ' ' ' ' ' < < < < < < < < - - - - - -           R" R" R"j 11[&-	  #'   15D MN MN MN MN MN` ..&&- j!8!8!8994@  #'	 	 	 #$$b b b b	 	bJ 11&-& k  #'	 	 	 &*$5k@ k@ k@ k@	 	k@\ nn&J+677>&-  #'	 	 	 )-d$ R R R R	 	Rj 11&CD1JJJJKK
 '-GD1a&!!Jx  
  #'!  , s0 s0 s0 s0% $s0l ..&- 
 #'   8< V7 V7 V7 V7 V7r 11[&-	  #'   044 I! I! I! I! I!X 11&CD1JJJJKK
 '-GD3*%%Jx  
   #'#  . j j j j' &jZ 11$T&999:&CD1JJJJKK
 '-GD3*%%Jx  
 " #'%  2 l l l l) (l` PV$ $ $ $N= = = ' ' 'T 11$T&999:&CD1JJJJKK
 5#&&-GD3*%%Jx  
 $ #''  2 
/y0 y0 y0 y0+ *y0x 11&&-#  #'	 	 	 e@ e@ e@ e@	 	e@P 11&CD1JJJJKK
 '-GD3*%%Jx  
   #'#  . _ _ _ _' &_D 11&CD1JJJJKK
 '-GD3*%%Jx  
   #'#  . ` ` ` `' &`F ..&-K	  #'   >BE Q Q Q Q Qh 11&%t,&-8Haf===>!{GD3*%%Jx  
  #'  * ] ] ] ]# "]@ 11&- 
 #'   37 [@ [@ [@ [@ [@| ..[&-&  #'	 	 	 +/d4 OM OM OM OM	 	OMd .&&&-	  #'   15D L5 L5 L5 L5 L5^ . &&,,/&-CD1

L>(B(B!C!CD  #'	 	 	 ~F+/4~F ~F ~F ~F	 	~FB ..&-&	  #'   8<D Q) Q) Q) Q) Q) Q) Q)r9   