U
    ½mœdðG  ã                   @   sÒ   d Z ddlm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
Zdd	lmZmZ d
dlmZ dd„ Zdd„ ZeeedœZdd„ Zdd„ Zdd„ Zdd„ Zd"dd„Zd#dd„Zd$dd„Zd d!„ ZdS )%zX
Multi-class / multi-label utility function
==========================================

é    )ÚSequence)ÚchainN)Úissparse)Ú
dok_matrix)Ú
lil_matrixé   )Úcheck_arrayÚ_assert_all_finiteé   )Úget_namespacec                 C   s6   t | ƒ\}}t| dƒs|r*| | | ¡¡S t| ƒS d S )NÚ	__array__)r   ÚhasattrÚunique_valuesÚasarrayÚset)ÚyÚxpÚis_array_api© r   úQ/home/sam/Atlas/atlas_env/lib/python3.8/site-packages/sklearn/utils/multiclass.pyÚ_unique_multiclass   s    r   c                 C   s    t  t| ddddgd�jd ¡S )Nr   ÚcsrÚcscÚcoo)Ú
input_nameÚaccept_sparser   )ÚnpZaranger   Úshape©r   r   r   r   Ú_unique_indicator   s    ÿr   )ÚbinaryÚ
multiclassúmultilabel-indicatorc                     s  t | Ž \}}| stdƒ‚tdd„ | D ƒƒ}|ddhkr<dh}t|ƒdkrTtd| ƒ‚| ¡ }|dkr†ttd	d„ | D ƒƒƒdkr†td
ƒ‚t |d¡‰ ˆ s¦tdt| ƒ ƒ‚|rÌ| ‡ fdd„| D ƒ¡}| 	|¡S tt
 ‡ fdd„| D ƒ¡ƒ}ttdd„ |D ƒƒƒdk�rtdƒ‚| t|ƒ¡S )a�  Extract an ordered array of unique labels.

    We don't allow:
        - mix of multilabel and multiclass (single label) targets
        - mix of label indicator matrix and anything else,
          because there are no explicit labels)
        - mix of label indicator matrices of different sizes
        - mix of string and integer labels

    At the moment, we also don't allow "multiclass-multioutput" input type.

    Parameters
    ----------
    *ys : array-likes
        Label values.

    Returns
    -------
    out : ndarray of shape (n_unique_labels,)
        An ordered array of unique labels.

    Examples
    --------
    >>> from sklearn.utils.multiclass import unique_labels
    >>> unique_labels([3, 5, 5, 5, 7, 7])
    array([3, 5, 7])
    >>> unique_labels([1, 2, 3, 4], [2, 2, 3, 4])
    array([1, 2, 3, 4])
    >>> unique_labels([1, 2, 10], [5, 11])
    array([ 1,  2,  5, 10, 11])
    zNo argument has been passed.c                 s   s   | ]}t |ƒV  qd S ©N)Útype_of_target)Ú.0Úxr   r   r   Ú	<genexpr>Q   s     z unique_labels.<locals>.<genexpr>r    r!   r   z'Mix type of y not allowed, got types %sr"   c                 s   s&   | ]}t |d ddgd�jd V  qdS )r   r   r   )r   r   N)r   r   ©r%   r   r   r   r   r'   ^   s    zCMulti-label binary indicator input with different numbers of labelsNzUnknown label type: %sc                    s   g | ]}ˆ |ƒ‘qS r   r   r(   ©Z_unique_labelsr   r   Ú
<listcomp>o   s     z!unique_labels.<locals>.<listcomp>c                 3   s    | ]}d d„ ˆ |ƒD ƒV  qdS )c                 s   s   | ]
}|V  qd S r#   r   )r%   Úir   r   r   r'   r   s     z*unique_labels.<locals>.<genexpr>.<genexpr>Nr   r(   r)   r   r   r'   r   s     c                 s   s   | ]}t |tƒV  qd S r#   )Ú
isinstanceÚstr)r%   Úlabelr   r   r   r'   t   s     z,Mix of label input types (string and number))r   Ú
ValueErrorr   ÚlenÚpopÚ_FN_UNIQUE_LABELSÚgetÚreprÚconcatr   r   Úfrom_iterabler   Úsorted)Zysr   r   Zys_typesZ
label_typeZ	unique_ysZ	ys_labelsr   r)   r   Úunique_labels,   s@     ÿÿÿûþ	ÿ
r8   c                 C   s    | j jdkot |  t¡| k¡S )NÚf)ÚdtypeÚkindr   ÚallÚastypeÚintr   r   r   r   Ú_is_integral_floatz   s    r?   c                 C   sŽ  t | ƒ\}}t| dƒs$t| tƒs$|rÀtddddddd�}t ¡ �z t dtj	¡ zt
| fddi|—Ž} W nL tj	tfk
r´ } z(t|ƒ d	¡r�‚ t
| fdti|—Ž} W 5 d}~X Y nX W 5 Q R X t| d
ƒrâ| jdkrâ| jd dksædS t| ƒ�r\t| ttfƒ�r|  ¡ } | | j¡}t| jƒdk�pZ|jdk�sF|jdk�oZd|k�oZ| jjdk�pZt|ƒS | | ¡}t|ƒdk �oˆ| jjdk�pˆt|ƒS dS )a~  Check if ``y`` is in a multilabel format.

    Parameters
    ----------
    y : ndarray of shape (n_samples,)
        Target values.

    Returns
    -------
    out : bool
        Return ``True``, if ``y`` is in a multilabel format, else ```False``.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.utils.multiclass import is_multilabel
    >>> is_multilabel([0, 1, 0, 1])
    False
    >>> is_multilabel([[1], [0, 2], []])
    False
    >>> is_multilabel(np.array([[1, 0], [0, 0]]))
    True
    >>> is_multilabel(np.array([[1], [0], [0]]))
    False
    >>> is_multilabel(np.array([[1, 0, 0]]))
    True
    r   TFr   ©r   Zallow_ndZforce_all_finiteZ	ensure_2dZensure_min_samplesZensure_min_featuresÚerrorr:   NúComplex data not supportedr   r
   r   Zbiué   )r   r   r,   r   ÚdictÚwarningsÚcatch_warningsÚsimplefilterr   ÚVisibleDeprecationWarningr   r/   r-   Ú
startswithÚobjectÚndimr   r   r   r   Ztocsrr   Údatar0   Úsizer:   r;   r?   )r   r   r   Úcheck_y_kwargsÚeÚlabelsr   r   r   Úis_multilabel~   s@    ú
0"
"ý
ÿrQ   c                 C   s$   t | dd�}|dkr td| ƒ‚dS )aA  Ensure that target y is of a non-regression type.

    Only the following target types (as defined in type_of_target) are allowed:
        'binary', 'multiclass', 'multiclass-multioutput',
        'multilabel-indicator', 'multilabel-sequences'

    Parameters
    ----------
    y : array-like
        Target values.
    r   ©r   )r    r!   zmulticlass-multioutputr"   zmultilabel-sequenceszUnknown label type: %rN)r$   r/   )r   Zy_typer   r   r   Úcheck_classification_targetsÆ   s    rS   Ú c                 C   s”  t | ƒ\}}t| tƒs(t| ƒs(t| dƒr4t| tƒ p6|}|sHtd|  ƒ‚| jjdk}|r`tdƒ‚t	| ƒrldS t
ddddddd	�}t ¡ �† t d
tj¡ t| ƒ�s
zt| fddi|—Ž} W nN tjtfk
�r } z(t|ƒ d¡rä‚ t| fdti|—Ž} W 5 d}~X Y nX W 5 Q R X z<t| d dƒ�sNt| d tƒ�rNt| d tƒ�sNtdƒ‚W n tk
�rf   Y nX | jdk�rxdS t| jƒ�s˜| jdk�r”dS dS t| ƒ�sÄ| jtk�rÄt| jd tƒ�sÄdS | jdk�ræ| jd dk�ræd}nd}| jjdk�r6t| ƒ�r| jn| }	| |	|	 t¡k¡�r6t|	|d� d| S t| ƒ�sH| d n
|  d¡j}
|  | ¡jd dk�s„| jdk�rŒt!|
ƒdk�rŒd| S dS dS )a
  Determine the type of data indicated by the target.

    Note that this type is the most specific type that can be inferred.
    For example:

        * ``binary`` is more specific but compatible with ``multiclass``.
        * ``multiclass`` of integers is more specific but compatible with
          ``continuous``.
        * ``multilabel-indicator`` is more specific but compatible with
          ``multiclass-multioutput``.

    Parameters
    ----------
    y : {array-like, sparse matrix}
        Target values. If a sparse matrix, `y` is expected to be a
        CSR/CSC matrix.

    input_name : str, default=""
        The data name used to construct the error message.

        .. versionadded:: 1.1.0

    Returns
    -------
    target_type : str
        One of:

        * 'continuous': `y` is an array-like of floats that are not all
          integers, and is 1d or a column vector.
        * 'continuous-multioutput': `y` is a 2d array of floats that are
          not all integers, and both dimensions are of size > 1.
        * 'binary': `y` contains <= 2 discrete values and is 1d or a column
          vector.
        * 'multiclass': `y` contains more than two discrete values, is not a
          sequence of sequences, and is 1d or a column vector.
        * 'multiclass-multioutput': `y` is a 2d array that contains more
          than two discrete values, is not a sequence of sequences, and both
          dimensions are of size > 1.
        * 'multilabel-indicator': `y` is a label indicator matrix, an array
          of two dimensions with at least two columns, and at most 2 unique
          values.
        * 'unknown': `y` is array-like but none of the above, such as a 3d
          array, sequence of sequences, or an array of non-sequence objects.

    Examples
    --------
    >>> from sklearn.utils.multiclass import type_of_target
    >>> import numpy as np
    >>> type_of_target([0.1, 0.6])
    'continuous'
    >>> type_of_target([1, -1, -1, 1])
    'binary'
    >>> type_of_target(['a', 'b', 'a'])
    'binary'
    >>> type_of_target([1.0, 2.0])
    'binary'
    >>> type_of_target([1, 0, 2])
    'multiclass'
    >>> type_of_target([1.0, 0.0, 3.0])
    'multiclass'
    >>> type_of_target(['a', 'b', 'c'])
    'multiclass'
    >>> type_of_target(np.array([[1, 2], [3, 1]]))
    'multiclass-multioutput'
    >>> type_of_target([[1, 2]])
    'multilabel-indicator'
    >>> type_of_target(np.array([[1.5, 2.0], [3.0, 1.6]]))
    'continuous-multioutput'
    >>> type_of_target(np.array([[0, 1], [1, 1]]))
    'multilabel-indicator'
    r   z:Expected array-like (array or non-string sequence), got %r)ZSparseSeriesZSparseArrayz1y cannot be class 'SparseSeries' or 'SparseArray'r"   TFr   r@   rA   r:   NrB   zÝYou appear to be using a legacy multi-label data representation. Sequence of sequences are no longer supported; use a binary array or sparse matrix instead - the MultiLabelBinarizer transformer can convert to this format.)r   r
   Úunknownr   r    r
   z-multioutputrT   r9   rR   Z
continuousr!   )"r   r,   r   r   r   r-   r/   Ú	__class__Ú__name__rQ   rD   rE   rF   rG   r   rH   r   rI   rJ   Ú
IndexErrorrK   Úminr   r:   Zflatr;   rL   Úanyr=   r>   r	   Zgetrowr   r0   )r   r   r   r   ZvalidZsparse_pandasrN   rO   ÚsuffixrL   Ú	first_rowr   r   r   r$   Ý   s€    H
ÿýÿú	

0ÿþýÿ(0r$   c                 C   sr   t | ddƒdkr"|dkr"tdƒ‚nL|dk	rnt | ddƒdk	r`t | jt|ƒ¡sntd|| jf ƒ‚nt|ƒ| _dS dS )a"  Private helper function for factorizing common classes param logic.

    Estimators that implement the ``partial_fit`` API need to be provided with
    the list of possible classes at the first call to partial_fit.

    Subsequent calls to partial_fit should check that ``classes`` is still
    consistent with a previous value of ``clf.classes_`` when provided.

    This function returns True if it detects that this was the first call to
    ``partial_fit`` on ``clf``. In that case the ``classes_`` attribute is also
    set on ``clf``.

    Úclasses_Nz8classes must be passed on the first call to partial_fit.zD`classes=%r` is not the same as on last call to partial_fit, was: %rTF)Úgetattrr/   r   Zarray_equalr]   r8   )ZclfÚclassesr   r   r   Ú_check_partial_fit_first_call‰  s    
ÿÿ
r`   c                 C   sâ  g }g }g }| j \}}|dk	r(t |¡}t| ƒ�rp|  ¡ } t | j¡}t|ƒD �]}| j| j| | j|d  … }	|dk	r˜||	 }
t 	|¡t 	|
¡ }nd}
| j d ||  }tj
| j| j| | j|d  … dd�\}}tj||
d�}d|k�r||dk  |7  < d|k�r@|| | j d k �r@t |dd¡}t |d|¡}| |¡ | |j d ¡ | || 	¡  ¡ qNnht|ƒD ]^}tj
| dd…|f dd�\}}| |¡ | |j d ¡ tj||d�}| || 	¡  ¡ �qx|||fS )az  Compute class priors from multioutput-multiclass target data.

    Parameters
    ----------
    y : {array-like, sparse matrix} of size (n_samples, n_outputs)
        The labels for each example.

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

    Returns
    -------
    classes : list of size n_outputs of ndarray of size (n_classes,)
        List of classes for each column.

    n_classes : list of int of size n_outputs
        Number of classes in each column.

    class_prior : list of size n_outputs of ndarray of size (n_classes,)
        Class distribution of each column.
    Nr   r   T)Zreturn_inverse)Úweights)r   r   r   r   ZtocscÚdiffZindptrÚrangeÚindicesÚsumÚuniquerL   ZbincountÚinsertÚappend)r   Zsample_weightr_   Ú	n_classesZclass_priorÚ	n_samplesZ	n_outputsZy_nnzÚkZcol_nonzeroZnz_samp_weightZzeros_samp_weight_sumZ	classes_kZy_kZclass_prior_kr   r   r   Úclass_distribution¬  sH    


 ÿ



rl   c           
      C   s  | j d }t ||f¡}t ||f¡}d}t|ƒD ]°}t|d |ƒD ]œ}|dd…|f  |dd…|f 8  < |dd…|f  |dd…|f 7  < || dd…|f dk|f  d7  < || dd…|f dk|f  d7  < |d7 }qDq2|dt |¡d   }	||	 S )ay  Compute a continuous, tie-breaking OvR decision function from OvO.

    It is important to include a continuous value, not only votes,
    to make computing AUC or calibration meaningful.

    Parameters
    ----------
    predictions : array-like of shape (n_samples, n_classifiers)
        Predicted classes for each binary classifier.

    confidences : array-like of shape (n_samples, n_classifiers)
        Decision functions or predicted probabilities for positive class
        for each binary classifier.

    n_classes : int
        Number of classes. n_classifiers must be
        ``n_classes * (n_classes - 1 ) / 2``.
    r   r   NrC   )r   r   Zzerosrc   Úabs)
ZpredictionsZconfidencesri   rj   ZvotesZsum_of_confidencesrk   r+   ÚjZtransformed_confidencesr   r   r   Ú_ovr_decision_functionö  s    
$$$$	ÿro   )rT   )N)N)Ú__doc__Úcollections.abcr   Ú	itertoolsr   rE   Zscipy.sparser   r   r   Únumpyr   Z
validationr   r	   Zutils._array_apir   r   r   r2   r8   r?   rQ   rS   r$   r`   rl   ro   r   r   r   r   Ú<module>   s0   ýNH
 -
#
J