ó
‡ˆ\c           @   s  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 d d	 l m Z d d
 l m Z d d l m Z d d l m Z d „  Z d „  Z d d „ Z d d „ Z d e d e d d „ Z d d e d d „ Z d d e d d „ Z d S(   iÿÿÿÿ(   t   divisionN(   t   issparse(   t   digammai   (   t   moves(   t   mutual_info_score(   t   NearestNeighbors(   t   scale(   t   check_random_state(   t	   check_X_y(   t   check_classification_targetsc         C   s…  |  j  } |  j d ƒ }  | j d ƒ } t j |  | f ƒ } t d d d | ƒ } | j | ƒ | j ƒ  d } t j | d d … d f d ƒ } | j d d	 ƒ | j |  ƒ | j	 d
 | d t
 ƒ } t j g  | D] } | j  ^ qÒ ƒ }	 | j | ƒ | j	 d
 | d t
 ƒ } t j g  | D] } | j  ^ qƒ }
 t | ƒ t | ƒ t j t |	 d ƒ ƒ t j t |
 d ƒ ƒ } t d | ƒ S(   sm  Compute mutual information between two continuous variables.

    Parameters
    ----------
    x, y : ndarray, shape (n_samples,)
        Samples of two continuous random variables, must have an identical
        shape.

    n_neighbors : int
        Number of nearest neighbors to search for each point, see [1]_.

    Returns
    -------
    mi : float
        Estimated mutual information. If it turned out to be negative it is
        replace by 0.

    Notes
    -----
    True mutual information can't be negative. If its estimate by a numerical
    method is negative, it means (providing the method is adequate) that the
    mutual information is close to 0 and replacing it by 0 is a reasonable
    strategy.

    References
    ----------
    .. [1] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual
           information". Phys. Rev. E 69, 2004.
    iÿÿÿÿi   t   metrict	   chebyshevt   n_neighborsi    Nt	   algorithmt   kd_treet   radiust   return_distance(   iÿÿÿÿi   (   iÿÿÿÿi   (   t   sizet   reshapet   npt   hstackR   t   fitt
   kneighborst	   nextaftert
   set_paramst   radius_neighborst   Falset   arrayR   t   meant   max(   t   xt   yR   t	   n_samplest   xyt   nnR   t   indt   it   nxt   nyt   mi(    (    sE   lib/python2.7/site-packages/sklearn/feature_selection/mutual_info_.pyt   _compute_mi_cc   s"    	"%%Dc         C   s  |  j  d } |  j d
 ƒ }  t j | ƒ } t j | ƒ } t j | ƒ } t ƒ  } x¿ t j | ƒ D]® } | | k }	 t j |	 ƒ }
 |
 d k rt | |
 d ƒ } | j d | ƒ | j	 |  |	 ƒ | j
 ƒ  d } t j | d d … d f d ƒ | |	 <| | |	 <n  |
 | |	 <qb W| d k }	 t j |	 ƒ } | |	 } | |	 } |  |	 }  | |	 } | j d d ƒ | j	 |  ƒ | j d | d	 t ƒ } t j g  | D] } | j ^ q™ƒ } t | ƒ t j t | ƒ ƒ t j t | ƒ ƒ t j t | d ƒ ƒ } t d | ƒ S(   s•  Compute mutual information between continuous and discrete variables.

    Parameters
    ----------
    c : ndarray, shape (n_samples,)
        Samples of a continuous random variable.

    d : ndarray, shape (n_samples,)
        Samples of a discrete random variable.

    n_neighbors : int
        Number of nearest neighbors to search for each point, see [1]_.

    Returns
    -------
    mi : float
        Estimated mutual information. If it turned out to be negative it is
        replace by 0.

    Notes
    -----
    True mutual information can't be negative. If its estimate by a numerical
    method is negative, it means (providing the method is adequate) that the
    mutual information is close to 0 and replacing it by 0 is a reasonable
    strategy.

    References
    ----------
    .. [1] B. C. Ross "Mutual Information between Discrete and Continuous
       Data Sets". PLoS ONE 9(2), 2014.
    i    iÿÿÿÿi   R   NR   R   R   R   (   iÿÿÿÿi   (   t   shapeR   R   t   emptyR   t   uniquet   sumt   minR   R   R   R   R   R   R   R   R   R   R   (   t   ct   dR   R    R   t   label_countst   k_allR"   t   labelt   maskt   countt   kt   rR#   R$   t   m_allR'   (    (    sE   lib/python2.7/site-packages/sklearn/feature_selection/mutual_info_.pyt   _compute_mi_cdO   s<     	&



%/i   c         C   sg   | r | r t  |  | ƒ S| r6 | r6 t | |  | ƒ S| rS | rS t |  | | ƒ St |  | | ƒ Sd S(   s²   Compute mutual information between two variables.

    This is a simple wrapper which selects a proper function to call based on
    whether `x` and `y` are discrete or not.
    N(   R   R8   R(   (   R   R   t
   x_discretet
   y_discreteR   (    (    sE   lib/python2.7/site-packages/sklearn/feature_selection/mutual_info_.pyt   _compute_mi–   s    c         c   sÄ   | d k r" t |  j d ƒ } n  t |  ƒ rš x | D]^ } t j |  j d ƒ } |  j | |  j | d } } |  j | | !| |  j | | !<| Vq5 Wn& x# | D] } |  d d … | f Vq¡ Wd S(   sˆ  Iterate over columns of a matrix.

    Parameters
    ----------
    X : ndarray or csc_matrix, shape (n_samples, n_features)
        Matrix over which to iterate.

    columns : iterable or None, default None
        Indices of columns to iterate over. If None, iterate over all columns.

    Yields
    ------
    x : ndarray, shape (n_samples,)
        Columns of `X` in dense format.
    i   i    N(	   t   Nonet   rangeR)   R   R   t   zerost   indptrt   datat   indices(   t   Xt   columnsR$   R   t	   start_ptrt   end_ptr(    (    sE   lib/python2.7/site-packages/sklearn/feature_selection/mutual_info_.pyt   _iterate_columns¦   s    t   autoc         C   s‘  t  |  | d d d | ƒ\ }  } |  j \ } } | d k rL t |  ƒ } n  t | t ƒ r€ t j | d t ƒ}	 |	 j | ƒ nF t j | ƒ } | j	 d k rÀ t j
 | d t ƒ}	 t |	 | <n | }	 |	 }
 t j |
 ƒ r÷ t |  ƒ r÷ t d ƒ ‚ n  t | ƒ } t j |
 ƒ rí| r'|  j ƒ  }  n  | sht |  d d … |
 f d	 t d
 t ƒ|  d d … |
 f <n  |  j t ƒ }  t j d t j t j |  d d … |
 f ƒ d d ƒƒ } |  d d … |
 f c d | | j | t j |
 ƒ ƒ 7<n  | sAt | d	 t ƒ} | d t j d t j t j | ƒ ƒ ƒ | j | ƒ 7} n  g  t j t |  ƒ |	 ƒ D]$ \ } } t | | | | | ƒ ^ qZ} t j | ƒ S(   s   Estimate mutual information between the features and the target.

    Parameters
    ----------
    X : array_like or sparse matrix, shape (n_samples, n_features)
        Feature matrix.

    y : array_like, shape (n_samples,)
        Target vector.

    discrete_features : {'auto', bool, array_like}, default 'auto'
        If bool, then determines whether to consider all features discrete
        or continuous. If array, then it should be either a boolean mask
        with shape (n_features,) or array with indices of discrete features.
        If 'auto', it is assigned to False for dense `X` and to True for
        sparse `X`.

    discrete_target : bool, default False
        Whether to consider `y` as a discrete variable.

    n_neighbors : int, default 3
        Number of neighbors to use for MI estimation for continuous variables,
        see [1]_ and [2]_. Higher values reduce variance of the estimation, but
        could introduce a bias.

    copy : bool, default True
        Whether to make a copy of the given data. If set to False, the initial
        data will be overwritten.

    random_state : int, RandomState instance or None, optional, default None
        The seed of the pseudo random number generator for adding small noise
        to continuous variables in order to remove repeated values.  If int,
        random_state is the seed used by the random number generator; If
        RandomState instance, random_state is the random number generator; If
        None, the random number generator is the RandomState instance used by
        `np.random`.

    Returns
    -------
    mi : ndarray, shape (n_features,)
        Estimated mutual information between each feature and the target.
        A negative value will be replaced by 0.

    References
    ----------
    .. [1] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual
           information". Phys. Rev. E 69, 2004.
    .. [2] B. C. Ross "Mutual Information between Discrete and Continuous
           Data Sets". PLoS ONE 9(2), 2014.
    t   accept_sparset   csct	   y_numericRG   t   dtypet   bools1   Sparse matrix `X` can't have continuous features.Nt	   with_meant   copyi   t   axisi    g»½×Ùß|Û=(   R   R)   R   t
   isinstanceRL   R   R*   t   fillt   asarrayRK   R>   t   Truet   anyt
   ValueErrorR   RN   R   R   t   astypet   floatt   maximumR   t   abst   randnR,   R   t   zipRF   R;   R   (   RB   R   t   discrete_featurest   discrete_targetR   RN   t   random_stateR    t
   n_featurest   discrete_maskt   continuous_maskt   rngt   meansR   t   discrete_featureR'   (    (    sE   lib/python2.7/site-packages/sklearn/feature_selection/mutual_info_.pyt   _estimate_miÄ   s@    4"":#<@c         C   s   t  |  | | t | | | ƒ S(   s   Estimate mutual information for a continuous target variable.

    Mutual information (MI) [1]_ between two random variables is a non-negative
    value, which measures the dependency between the variables. It is equal
    to zero if and only if two random variables are independent, and higher
    values mean higher dependency.

    The function relies on nonparametric methods based on entropy estimation
    from k-nearest neighbors distances as described in [2]_ and [3]_. Both
    methods are based on the idea originally proposed in [4]_.

    It can be used for univariate features selection, read more in the
    :ref:`User Guide <univariate_feature_selection>`.

    Parameters
    ----------
    X : array_like or sparse matrix, shape (n_samples, n_features)
        Feature matrix.

    y : array_like, shape (n_samples,)
        Target vector.

    discrete_features : {'auto', bool, array_like}, default 'auto'
        If bool, then determines whether to consider all features discrete
        or continuous. If array, then it should be either a boolean mask
        with shape (n_features,) or array with indices of discrete features.
        If 'auto', it is assigned to False for dense `X` and to True for
        sparse `X`.

    n_neighbors : int, default 3
        Number of neighbors to use for MI estimation for continuous variables,
        see [2]_ and [3]_. Higher values reduce variance of the estimation, but
        could introduce a bias.

    copy : bool, default True
        Whether to make a copy of the given data. If set to False, the initial
        data will be overwritten.

    random_state : int, RandomState instance or None, optional, default None
        The seed of the pseudo random number generator for adding small noise
        to continuous variables in order to remove repeated values.
        If int, random_state is the seed used by the random number generator;
        If RandomState instance, random_state is the random number generator;
        If None, the random number generator is the RandomState instance used
        by `np.random`.

    Returns
    -------
    mi : ndarray, shape (n_features,)
        Estimated mutual information between each feature and the target.

    Notes
    -----
    1. The term "discrete features" is used instead of naming them
       "categorical", because it describes the essence more accurately.
       For example, pixel intensities of an image are discrete features
       (but hardly categorical) and you will get better results if mark them
       as such. Also note, that treating a continuous variable as discrete and
       vice versa will usually give incorrect results, so be attentive about that.
    2. True mutual information can't be negative. If its estimate turns out
       to be negative, it is replaced by zero.

    References
    ----------
    .. [1] `Mutual Information <https://en.wikipedia.org/wiki/Mutual_information>`_
           on Wikipedia.
    .. [2] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual
           information". Phys. Rev. E 69, 2004.
    .. [3] B. C. Ross "Mutual Information between Discrete and Continuous
           Data Sets". PLoS ONE 9(2), 2014.
    .. [4] L. F. Kozachenko, N. N. Leonenko, "Sample Estimate of the Entropy
           of a Random Vector", Probl. Peredachi Inf., 23:2 (1987), 9-16
    (   Re   R   (   RB   R   R\   R   RN   R^   (    (    sE   lib/python2.7/site-packages/sklearn/feature_selection/mutual_info_.pyt   mutual_info_regression&  s    Kc         C   s&   t  | ƒ t |  | | t | | | ƒ S(   s  Estimate mutual information for a discrete target variable.

    Mutual information (MI) [1]_ between two random variables is a non-negative
    value, which measures the dependency between the variables. It is equal
    to zero if and only if two random variables are independent, and higher
    values mean higher dependency.

    The function relies on nonparametric methods based on entropy estimation
    from k-nearest neighbors distances as described in [2]_ and [3]_. Both
    methods are based on the idea originally proposed in [4]_.

    It can be used for univariate features selection, read more in the
    :ref:`User Guide <univariate_feature_selection>`.

    Parameters
    ----------
    X : array_like or sparse matrix, shape (n_samples, n_features)
        Feature matrix.

    y : array_like, shape (n_samples,)
        Target vector.

    discrete_features : {'auto', bool, array_like}, default 'auto'
        If bool, then determines whether to consider all features discrete
        or continuous. If array, then it should be either a boolean mask
        with shape (n_features,) or array with indices of discrete features.
        If 'auto', it is assigned to False for dense `X` and to True for
        sparse `X`.

    n_neighbors : int, default 3
        Number of neighbors to use for MI estimation for continuous variables,
        see [2]_ and [3]_. Higher values reduce variance of the estimation, but
        could introduce a bias.

    copy : bool, default True
        Whether to make a copy of the given data. If set to False, the initial
        data will be overwritten.

    random_state : int, RandomState instance or None, optional, default None
        The seed of the pseudo random number generator for adding small noise
        to continuous variables in order to remove repeated values.  If int,
        random_state is the seed used by the random number generator; If
        RandomState instance, random_state is the random number generator; If
        None, the random number generator is the RandomState instance used by
        `np.random`.

    Returns
    -------
    mi : ndarray, shape (n_features,)
        Estimated mutual information between each feature and the target.

    Notes
    -----
    1. The term "discrete features" is used instead of naming them
       "categorical", because it describes the essence more accurately.
       For example, pixel intensities of an image are discrete features
       (but hardly categorical) and you will get better results if mark them
       as such. Also note, that treating a continuous variable as discrete and
       vice versa will usually give incorrect results, so be attentive about that.
    2. True mutual information can't be negative. If its estimate turns out
       to be negative, it is replaced by zero.

    References
    ----------
    .. [1] `Mutual Information <https://en.wikipedia.org/wiki/Mutual_information>`_
           on Wikipedia.
    .. [2] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual
           information". Phys. Rev. E 69, 2004.
    .. [3] B. C. Ross "Mutual Information between Discrete and Continuous
           Data Sets". PLoS ONE 9(2), 2014.
    .. [4] L. F. Kozachenko, N. N. Leonenko, "Sample Estimate of the Entropy
           of a Random Vector:, Probl. Peredachi Inf., 23:2 (1987), 9-16
    (   R	   Re   RS   (   RB   R   R\   R   RN   R^   (    (    sE   lib/python2.7/site-packages/sklearn/feature_selection/mutual_info_.pyt   mutual_info_classifu  s    K
(    t
   __future__R    t   numpyR   t   scipy.sparseR   t   scipy.specialR   t   externals.sixR   t   metrics.cluster.supervisedR   t	   neighborsR   t   preprocessingR   t   utilsR   t   utils.validationR   t   utils.multiclassR	   R(   R8   R;   R<   RF   R   RS   Re   Rf   Rg   (    (    (    sE   lib/python2.7/site-packages/sklearn/feature_selection/mutual_info_.pyt   <module>   s(   	=	GaN