ó
‡ˆ\c           @   s|  d  Z  d d l m Z d d l Z d d l m Z d d l Z d d l m	 Z	 d d l
 m Z d d l m Z d d	 l m Z d d
 l m Z m Z d d l m Z d d l m Z d d l m Z d d l m Z d d l m Z d d l m Z d d „ Z d d d d „ Z d d d d „ Z  d d d „ Z! d d d „ Z" d d e# d „ Z$ d d „ Z% d d „ Z& d d „ Z' d S(   s   Metrics to assess performance on classification task given scores

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
iÿÿÿÿ(   t   divisionN(   t   partial(   t
   csr_matrix(   t   rankdatai   (   t   assert_all_finite(   t   check_consistent_length(   t   column_or_1dt   check_array(   t   type_of_target(   t   stable_cumsum(   t   count_nonzero(   t   UndefinedMetricWarning(   t   label_binarizei   (   t   _average_binary_scoret
   deprecatedc         C   sG  t  |  | ƒ t |  ƒ }  t | ƒ } |  j d d k  rN t d |  j ƒ ‚ n  | d k rm t j d t ƒ n  d } | t k r¬ t j	 | |  f ƒ } |  | | | }  } nZ t j
 |  ƒ } t j | d k  ƒ rt j | d k ƒ rî d } qt d j |  ƒ ƒ ‚ n  | t j | |  ƒ } t | t j ƒ rC| j j | ƒ } n  | S(	   s  Compute Area Under the Curve (AUC) using the trapezoidal rule

    This is a general function, given points on a curve.  For computing the
    area under the ROC-curve, see :func:`roc_auc_score`.  For an alternative
    way to summarize a precision-recall curve, see
    :func:`average_precision_score`.

    Parameters
    ----------
    x : array, shape = [n]
        x coordinates. These must be either monotonic increasing or monotonic
        decreasing.
    y : array, shape = [n]
        y coordinates.
    reorder : boolean, optional (default='deprecated')
        Whether to sort x before computing. If False, assume that x must be
        either monotonic increasing or monotonic decreasing. If True, y is
        used to break ties when sorting x. Make sure that y has a monotonic
        relation to x when setting reorder to True.

        .. deprecated:: 0.20
           Parameter ``reorder`` has been deprecated in version 0.20 and will
           be removed in 0.22. It's introduced for roc_auc_score (not for
           general use) and is no longer used there. What's more, the result
           from auc will be significantly influenced if x is sorted
           unexpectedly due to slight floating point error (See issue #9786).
           Future (and default) behavior is equivalent to ``reorder=False``.

    Returns
    -------
    auc : float

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn import metrics
    >>> y = np.array([1, 1, 2, 2])
    >>> pred = np.array([0.1, 0.4, 0.35, 0.8])
    >>> fpr, tpr, thresholds = metrics.roc_curve(y, pred, pos_label=2)
    >>> metrics.auc(fpr, tpr)
    0.75

    See also
    --------
    roc_auc_score : Compute the area under the ROC curve
    average_precision_score : Compute average precision from prediction scores
    precision_recall_curve :
        Compute precision-recall pairs for different probability thresholds
    i    i   sJ   At least 2 points are needed to compute area under curve, but x.shape = %sR   sÂ   The 'reorder' parameter has been deprecated in version 0.20 and will be removed in 0.22. It is recommended not to set 'reorder' and ensure that x is monotonic increasing or monotonic decreasing.i   iÿÿÿÿs,   x is neither increasing nor decreasing : {}.(   R   R   t   shapet
   ValueErrort   warningst   warnt   DeprecationWarningt   Truet   npt   lexsortt   difft   anyt   allt   formatt   trapzt
   isinstancet   memmapt   dtypet   type(   t   xt   yt   reordert	   directiont   ordert   dxt   area(    (    s6   lib/python2.7/site-packages/sklearn/metrics/ranking.pyt   auc)   s.    2	
		t   macroc   	      C   s¼   d d
 d „ } t |  ƒ } | d k rB | d k rB t d ƒ ‚ nO | d k r‘ t j |  ƒ } t | ƒ d k r‘ | | k r‘ t d | ƒ ‚ q‘ n  t | d | ƒ} t | |  | | d	 | ƒS(   sþ  Compute average precision (AP) from prediction scores

    AP summarizes a precision-recall curve as the weighted mean of precisions
    achieved at each threshold, with the increase in recall from the previous
    threshold used as the weight:

    .. math::
        \text{AP} = \sum_n (R_n - R_{n-1}) P_n

    where :math:`P_n` and :math:`R_n` are the precision and recall at the nth
    threshold [1]_. This implementation is not interpolated and is different
    from computing the area under the precision-recall curve with the
    trapezoidal rule, which uses linear interpolation and can be too
    optimistic.

    Note: this implementation is restricted to the binary classification task
    or multilabel classification task.

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

    Parameters
    ----------
    y_true : array, shape = [n_samples] or [n_samples, n_classes]
        True binary labels or binary label indicators.

    y_score : array, shape = [n_samples] or [n_samples, n_classes]
        Target scores, can either be probability estimates of the positive
        class, confidence values, or non-thresholded measure of decisions
        (as returned by "decision_function" on some classifiers).

    average : string, [None, 'micro', 'macro' (default), 'samples', 'weighted']
        If ``None``, the scores for each class are returned. Otherwise,
        this determines the type of averaging performed on the data:

        ``'micro'``:
            Calculate metrics globally by considering each element of the label
            indicator matrix as a label.
        ``'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).
        ``'samples'``:
            Calculate metrics for each instance, and find their average.

        Will be ignored when ``y_true`` is binary.

    pos_label : int or str (default=1)
        The label of the positive class. Only applied to binary ``y_true``.
        For multilabel-indicator ``y_true``, ``pos_label`` is fixed to 1.

    sample_weight : array-like of shape = [n_samples], optional
        Sample weights.

    Returns
    -------
    average_precision : float

    References
    ----------
    .. [1] `Wikipedia entry for the Average precision
           <https://en.wikipedia.org/w/index.php?title=Information_retrieval&
           oldid=793358396#Average_precision>`_

    See also
    --------
    roc_auc_score : Compute the area under the ROC curve

    precision_recall_curve :
        Compute precision-recall pairs for different probability thresholds

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.metrics import average_precision_score
    >>> y_true = np.array([0, 0, 1, 1])
    >>> y_scores = np.array([0.1, 0.4, 0.35, 0.8])
    >>> average_precision_score(y_true, y_scores)  # doctest: +ELLIPSIS
    0.83...

    Notes
    -----
    .. versionchanged:: 0.19
      Instead of linearly interpolating between operating points, precisions
      are weighted by the change in recall since the last operating point.
    i   c         S   sL   t  |  | d | d | ƒ\ } } } t j t j | ƒ t j | ƒ d  ƒ S(   Nt	   pos_labelt   sample_weightiÿÿÿÿ(   t   precision_recall_curveR   t   sumR   t   array(   t   y_truet   y_scoreR)   R*   t	   precisiont   recallt   _(    (    s6   lib/python2.7/site-packages/sklearn/metrics/ranking.pyt(   _binary_uninterpolated_average_precisionÛ   s    !s   multilabel-indicatorsn   Parameter pos_label is fixed to 1 for multilabel-indicator y_true. Do not set pos_label or set pos_label to 1.t   binaryi   s5   pos_label=%r is invalid. Set it to a label in y_true.R)   R*   N(   t   NoneR   R   R   t   uniquet   lenR   R   (	   R.   R/   t   averageR)   R*   R3   t   y_typet   present_labelst   average_precision(    (    s6   lib/python2.7/site-packages/sklearn/metrics/ranking.pyt   average_precision_score‚   s    Z		c            st   d ‡  f d † } t |  ƒ } | d k r[ t j |  ƒ } t |  | ƒ d d … d f }  n  t | |  | | d | ƒS(   sù
  Compute Area Under the Receiver Operating Characteristic Curve (ROC AUC)
    from prediction scores.

    Note: this implementation is restricted to the binary classification task
    or multilabel classification task in label indicator format.

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

    Parameters
    ----------
    y_true : array, shape = [n_samples] or [n_samples, n_classes]
        True binary labels or binary label indicators.

    y_score : array, shape = [n_samples] or [n_samples, n_classes]
        Target scores, can either be probability estimates of the positive
        class, confidence values, or non-thresholded measure of decisions
        (as returned by "decision_function" on some classifiers). For binary
        y_true, y_score is supposed to be the score of the class with greater
        label.

    average : string, [None, 'micro', 'macro' (default), 'samples', 'weighted']
        If ``None``, the scores for each class are returned. Otherwise,
        this determines the type of averaging performed on the data:

        ``'micro'``:
            Calculate metrics globally by considering each element of the label
            indicator matrix as a label.
        ``'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).
        ``'samples'``:
            Calculate metrics for each instance, and find their average.

        Will be ignored when ``y_true`` is binary.

    sample_weight : array-like of shape = [n_samples], optional
        Sample weights.

    max_fpr : float > 0 and <= 1, optional
        If not ``None``, the standardized partial AUC [3]_ over the range
        [0, max_fpr] is returned.

    Returns
    -------
    auc : float

    References
    ----------
    .. [1] `Wikipedia entry for the Receiver operating characteristic
            <https://en.wikipedia.org/wiki/Receiver_operating_characteristic>`_

    .. [2] Fawcett T. An introduction to ROC analysis[J]. Pattern Recognition
           Letters, 2006, 27(8):861-874.

    .. [3] `Analyzing a portion of the ROC curve. McClish, 1989
            <https://www.ncbi.nlm.nih.gov/pubmed/2668680>`_

    See also
    --------
    average_precision_score : Area under the precision-recall curve

    roc_curve : Compute Receiver operating characteristic (ROC) curve

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.metrics import roc_auc_score
    >>> y_true = np.array([0, 0, 1, 1])
    >>> y_scores = np.array([0.1, 0.4, 0.35, 0.8])
    >>> roc_auc_score(y_true, y_scores)
    0.75

    c            sS  t  t j |  ƒ ƒ d k r* t d ƒ ‚ n  t |  | d | ƒ\ } } } ˆ  d  k s` ˆ  d k rm t | | ƒ Sˆ  d k s… ˆ  d k r˜ t d ˆ  ƒ ‚ n  t j | ˆ  d ƒ } | | d | | g } | | d | | g } t j | |  t j	 ˆ  | | ƒ ƒ } t j | |  ˆ  ƒ } t | | ƒ }	 d ˆ  d }
 ˆ  } d d |	 |
 | |
 S(	   Ni   sL   Only one class present in y_true. ROC AUC score is not defined in that case.R*   i   i    s)   Expected max_frp in range ]0, 1], got: %rt   rightg      à?(
   R7   R   R6   R   t	   roc_curveR5   R'   t   searchsortedt   appendt   interp(   R.   R/   R*   t   fprt   tprR2   t   stopt   x_interpt   y_interpt   partial_auct   min_areat   max_area(   t   max_fpr(    s6   lib/python2.7/site-packages/sklearn/metrics/ranking.pyt   _binary_roc_auc_scoreB  s$    %R4   Ni    R*   (   R5   R   R   R6   R   R   (   R.   R/   R8   R*   RJ   RK   R9   t   labels(    (   RJ   s6   lib/python2.7/site-packages/sklearn/metrics/ranking.pyt   roc_auc_scoreô   s    N"c         C   s?  t  |  ƒ } | d k p- | d k o- | d k	 sH t d j | ƒ ƒ ‚ n  t |  | | ƒ t |  ƒ }  t | ƒ } t |  ƒ t | ƒ | d k	 rŸ t | ƒ } n  t j |  ƒ } | d k r9t j	 | d d g ƒ p&t j	 | d d g ƒ p&t j	 | d g ƒ p&t j	 | d g ƒ p&t j	 | d g ƒ r9t d ƒ ‚ n | d k rNd } n  |  | k }  t j
 | d	 d
 ƒd d d … } | | } |  | }  | d k	 r©| | } n d } t j t j | ƒ ƒ d } t j | |  j d f }	 t |  | ƒ |	 }
 | d k	 r t d |  | ƒ |	 } n d |	 |
 } | |
 | |	 f S(   s¡  Calculate true and false positives per binary classification threshold.

    Parameters
    ----------
    y_true : array, shape = [n_samples]
        True targets of binary classification

    y_score : array, shape = [n_samples]
        Estimated probabilities or decision function

    pos_label : int or str, default=None
        The label of the positive class

    sample_weight : array-like of shape = [n_samples], optional
        Sample weights.

    Returns
    -------
    fps : array, shape = [n_thresholds]
        A count of false positives, at index i being the number of negative
        samples assigned a score >= thresholds[i]. The total number of
        negative samples is equal to fps[-1] (thus true negatives are given by
        fps[-1] - fps).

    tps : array, shape = [n_thresholds <= len(np.unique(y_score))]
        An increasing count of true positives, at index i being the number
        of positive samples assigned a score >= thresholds[i]. The total
        number of positive samples is equal to tps[-1] (thus false negatives
        are given by tps[-1] - tps).

    thresholds : array, shape = [n_thresholds]
        Decreasing score values.
    R4   t
   multiclasss   {0} format is not supportedi    i   iÿÿÿÿs1   Data is not binary and pos_label is not specifiedg      ð?t   kindt	   mergesortN(   R   R5   R   R   R   R   R   R   R6   t   array_equalt   argsortt   whereR   t   r_t   sizeR	   (   R.   R/   R)   R*   R9   t   classest   desc_score_indicest   weightt   distinct_value_indicest   threshold_idxst   tpst   fps(    (    s6   lib/python2.7/site-packages/sklearn/metrics/ranking.pyt   _binary_clf_curveg  sF    #

	"

c         C   s«   t  |  | d | d | ƒ\ } } } | | | } d | t j | ƒ <| | d } | j | d ƒ }	 t |	 d d ƒ }
 t j | |
 d f t j | |
 d f | |
 f S(   s
  Compute precision-recall pairs for different probability thresholds

    Note: this implementation is restricted to the binary classification task.

    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 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 last precision and recall values are 1. and 0. respectively and do not
    have a corresponding threshold.  This ensures that the graph starts on the
    y axis.

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

    Parameters
    ----------
    y_true : array, shape = [n_samples]
        True targets of binary classification in range {-1, 1} or {0, 1}.

    probas_pred : array, shape = [n_samples]
        Estimated probabilities or decision function.

    pos_label : int or str, default=None
        The label of the positive class

    sample_weight : array-like of shape = [n_samples], optional
        Sample weights.

    Returns
    -------
    precision : array, shape = [n_thresholds + 1]
        Precision values such that element i is the precision of
        predictions with score >= thresholds[i] and the last element is 1.

    recall : array, shape = [n_thresholds + 1]
        Decreasing recall values such that element i is the recall of
        predictions with score >= thresholds[i] and the last element is 0.

    thresholds : array, shape = [n_thresholds <= len(np.unique(probas_pred))]
        Increasing thresholds on the decision function used to compute
        precision and recall.

    See also
    --------
    average_precision_score : Compute average precision from prediction scores

    roc_curve : Compute Receiver operating characteristic (ROC) curve

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.metrics import precision_recall_curve
    >>> y_true = np.array([0, 0, 1, 1])
    >>> y_scores = np.array([0.1, 0.4, 0.35, 0.8])
    >>> precision, recall, thresholds = precision_recall_curve(
    ...     y_true, y_scores)
    >>> precision  # doctest: +ELLIPSIS
    array([0.66666667, 0.5       , 1.        , 1.        ])
    >>> recall
    array([1. , 0.5, 0.5, 0. ])
    >>> thresholds
    array([0.35, 0.4 , 0.8 ])

    R)   R*   i    iÿÿÿÿi   N(   R]   R   t   isnanR?   t   sliceR5   RT   (   R.   t   probas_predR)   R*   R\   R[   t
   thresholdsR0   R1   t   last_indt   sl(    (    s6   lib/python2.7/site-packages/sklearn/metrics/ranking.pyR+   Á  s    Gc         C   s¶  t  |  | d | d | ƒ\ } } } | r¤ t | ƒ d k r¤ t j t j t t j t j | d ƒ t j | d ƒ ƒ t f ƒ d } | | } | | } | | } n  | j d k sÓ | d d k sÓ | d d k rt j d | f } t j d | f } t j | d d | f } n  | d d k rRt	 j
 d t ƒ t j t j | j ƒ }	 n | | d }	 | d d k r›t	 j
 d t ƒ t j t j | j ƒ }
 n | | d }
 |	 |
 | f S(	   sç
  Compute Receiver operating characteristic (ROC)

    Note: this implementation is restricted to the binary classification task.

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

    Parameters
    ----------

    y_true : array, shape = [n_samples]
        True binary labels. If labels are not either {-1, 1} or {0, 1}, then
        pos_label should be explicitly given.

    y_score : array, shape = [n_samples]
        Target scores, can either be probability estimates of the positive
        class, confidence values, or non-thresholded measure of decisions
        (as returned by "decision_function" on some classifiers).

    pos_label : int or str, default=None
        Label considered as positive and others are considered negative.

    sample_weight : array-like of shape = [n_samples], optional
        Sample weights.

    drop_intermediate : boolean, optional (default=True)
        Whether to drop some suboptimal thresholds which would not appear
        on a plotted ROC curve. This is useful in order to create lighter
        ROC curves.

        .. versionadded:: 0.17
           parameter *drop_intermediate*.

    Returns
    -------
    fpr : array, shape = [>2]
        Increasing false positive rates such that element i is the false
        positive rate of predictions with score >= thresholds[i].

    tpr : array, shape = [>2]
        Increasing true positive rates such that element i is the true
        positive rate of predictions with score >= thresholds[i].

    thresholds : array, shape = [n_thresholds]
        Decreasing thresholds on the decision function used to compute
        fpr and tpr. `thresholds[0]` represents no instances being predicted
        and is arbitrarily set to `max(y_score) + 1`.

    See also
    --------
    roc_auc_score : Compute the area under the ROC curve

    Notes
    -----
    Since the thresholds are sorted from low to high values, they
    are reversed upon returning them to ensure they correspond to both ``fpr``
    and ``tpr``, which are sorted in reversed order during their calculation.

    References
    ----------
    .. [1] `Wikipedia entry for the Receiver operating characteristic
            <https://en.wikipedia.org/wiki/Receiver_operating_characteristic>`_

    .. [2] Fawcett T. An introduction to ROC analysis[J]. Pattern Recognition
           Letters, 2006, 27(8):861-874.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn import metrics
    >>> y = np.array([1, 1, 2, 2])
    >>> scores = np.array([0.1, 0.4, 0.35, 0.8])
    >>> fpr, tpr, thresholds = metrics.roc_curve(y, scores, pos_label=2)
    >>> fpr
    array([0. , 0. , 0.5, 0.5, 1. ])
    >>> tpr
    array([0. , 0.5, 0.5, 1. , 1. ])
    >>> thresholds
    array([1.8 , 0.8 , 0.4 , 0.35, 0.1 ])

    R)   R*   i   i    i   iÿÿÿÿsI   No negative samples in y_true, false positive value should be meaninglesssH   No positive samples in y_true, true positive value should be meaningless(   R]   R7   R   RS   RT   R   t
   logical_orR   RU   R   R   R   t   repeatt   nanR   (   R.   R/   R)   R*   t   drop_intermediateR\   R[   Ra   t   optimal_idxsRB   RC   (    (    s6   lib/python2.7/site-packages/sklearn/metrics/ranking.pyR>     s2    R!

/		c         C   sÔ  t  |  | | ƒ t |  d t ƒ}  t | d t ƒ} |  j | j k rU t d ƒ ‚ n  t |  ƒ } | d k r¡ | d k o… |  j d k r¡ t d j | ƒ ƒ ‚ n  t |  ƒ }  | } |  j \ } } d } xØ t	 t
 |  j |  j d ƒ ƒ D]· \ } \ } }	 |  j | |	 !}
 |
 j d	 k s)|
 j | k r9| d
 7} qé n  | | } t | d ƒ |
 } t | |
 d ƒ } | | j ƒ  } | d k	 r–| | | } n  | | 7} qé W| d k r½| | } n | t j | ƒ } | S(   sŠ  Compute ranking-based average precision

    Label ranking average precision (LRAP) is the average over each ground
    truth label assigned to each sample, of the ratio of true vs. total
    labels with lower score.

    This metric is used in multilabel ranking problem, where the goal
    is to give better rank to the labels associated to each sample.

    The obtained score is always strictly greater than 0 and
    the best value is 1.

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

    Parameters
    ----------
    y_true : array or sparse matrix, shape = [n_samples, n_labels]
        True binary labels in binary indicator format.

    y_score : array, shape = [n_samples, n_labels]
        Target scores, can either be probability estimates of the positive
        class, confidence values, or non-thresholded measure of decisions
        (as returned by "decision_function" on some classifiers).

    sample_weight : array-like of shape = [n_samples], optional
        Sample weights.

    Returns
    -------
    score : float

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.metrics import label_ranking_average_precision_score
    >>> y_true = np.array([[1, 0, 0], [0, 0, 1]])
    >>> y_score = np.array([[0.75, 0.5, 1], [1, 0.2, 0.1]])
    >>> label_ranking_average_precision_score(y_true, y_score)         # doctest: +ELLIPSIS
    0.416...

    t	   ensure_2ds'   y_true and y_score have different shapes   multilabel-indicatorR4   i   s   {0} format is not supportedg        i   i    g      ð?t   maxN(   R   R   t   FalseR   R   R   t   ndimR   R   t	   enumeratet   zipt   indptrt   indicesRU   R   t   meanR5   R   R,   (   R.   R/   R*   R9   t	   n_samplest   n_labelst   outt   it   startRD   t   relevantt   scores_it   rankt   Lt   aux(    (    s6   lib/python2.7/site-packages/sklearn/metrics/ranking.pyt%   label_ranking_average_precision_score˜  s:    +2

c         C   sû   t  |  d t ƒ}  t  | d t ƒ} t |  | | ƒ t |  ƒ } | d k rd t d j | ƒ ƒ ‚ n  |  j | j k r… t d ƒ ‚ n  t j j	 | d t j
 |  ƒ ƒ} | j d d ƒ j d ƒ } | | k j d d ƒ } | j d	 ƒ } t j | d
 | ƒS(   s0  Coverage error measure

    Compute how far we need to go through the ranked scores to cover all
    true labels. The best value is equal to the average number
    of labels in ``y_true`` per sample.

    Ties in ``y_scores`` are broken by giving maximal rank that would have
    been assigned to all tied values.

    Note: Our implementation's score is 1 greater than the one given in
    Tsoumakas et al., 2010. This extends it to handle the degenerate case
    in which an instance has 0 true labels.

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

    Parameters
    ----------
    y_true : array, shape = [n_samples, n_labels]
        True binary labels in binary indicator format.

    y_score : array, shape = [n_samples, n_labels]
        Target scores, can either be probability estimates of the positive
        class, confidence values, or non-thresholded measure of decisions
        (as returned by "decision_function" on some classifiers).

    sample_weight : array-like of shape = [n_samples], optional
        Sample weights.

    Returns
    -------
    coverage_error : float

    References
    ----------
    .. [1] Tsoumakas, G., Katakis, I., & Vlahavas, I. (2010).
           Mining multi-label data. In Data mining and knowledge discovery
           handbook (pp. 667-685). Springer US.

    Ri   s   multilabel-indicators   {0} format is not supporteds'   y_true and y_score have different shapet   maskt   axisi   iÿÿÿÿi    t   weights(   iÿÿÿÿi   (   R   Rk   R   R   R   R   R   R   t   mat   masked_arrayt   logical_nott   mint   reshapeR,   t   filledR8   (   R.   R/   R*   R9   t   y_score_maskt   y_min_relevantt   coverage(    (    s6   lib/python2.7/site-packages/sklearn/metrics/ranking.pyt   coverage_errorï  s    (!c         C   sì  t  |  d t d d ƒ}  t  | d t ƒ} t |  | | ƒ t |  ƒ } | d k rj t d j | ƒ ƒ ‚ n  |  j | j k r‹ t d ƒ ‚ n  |  j \ } } t |  ƒ }  t j	 | ƒ } x¼ t
 t |  j |  j d ƒ ƒ D]› \ } \ } }	 t j | | d t ƒ\ }
 } t j | |  j | |	 !d	 t |
 ƒ ƒ} t j | d	 t |
 ƒ ƒ} | | } t j | j ƒ  | ƒ | | <qÕ Wt |  d
 d ƒ} t j d d d d ƒ  | | | | } Wd QXd | t j | d k | | k ƒ <t j | d | ƒS(   s	  Compute Ranking loss measure

    Compute the average number of label pairs that are incorrectly ordered
    given y_score weighted by the size of the label set and the number of
    labels not in the label set.

    This is similar to the error set size, but weighted by the number of
    relevant and irrelevant labels. The best performance is achieved with
    a ranking loss of zero.

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

    .. versionadded:: 0.17
       A function *label_ranking_loss*

    Parameters
    ----------
    y_true : array or sparse matrix, shape = [n_samples, n_labels]
        True binary labels in binary indicator format.

    y_score : array, shape = [n_samples, n_labels]
        Target scores, can either be probability estimates of the positive
        class, confidence values, or non-thresholded measure of decisions
        (as returned by "decision_function" on some classifiers).

    sample_weight : array-like of shape = [n_samples], optional
        Sample weights.

    Returns
    -------
    loss : float

    References
    ----------
    .. [1] Tsoumakas, G., Katakis, I., & Vlahavas, I. (2010).
           Mining multi-label data. In Data mining and knowledge discovery
           handbook (pp. 667-685). Springer US.

    Ri   t   accept_sparset   csrs   multilabel-indicators   {0} format is not supporteds'   y_true and y_score have different shapei   t   return_inverset	   minlengthR~   t   dividet   ignoret   invalidNg        i    R   (   s   multilabel-indicator(   R   Rk   R   R   R   R   R   R   R   t   zerosRm   Rn   Ro   R6   R   t   bincountRp   R7   t   dott   cumsumR
   t   errstateRd   R8   (   R.   R/   R*   R9   Rr   Rs   t   lossRu   Rv   RD   t   unique_scorest   unique_inverset   true_at_reversed_rankt   all_at_reversed_rankt   false_at_reversed_rankt   n_positives(    (    s6   lib/python2.7/site-packages/sklearn/metrics/ranking.pyt   label_ranking_loss*  s6    (2
"((   t   __doc__t
   __future__R    R   t	   functoolsR   t   numpyR   t   scipy.sparseR   t   scipy.statsR   t   utilsR   R   R   R   t   utils.multiclassR   t   utils.extmathR	   t   utils.sparsefuncsR
   t
   exceptionsR   t   preprocessingR   t   baseR   R'   R5   R<   RM   R]   R+   R   R>   R|   R‰   R   (    (    (    s6   lib/python2.7/site-packages/sklearn/metrics/ranking.pyt   <module>   s8   YqrZU€W;