
    0Ph"N                        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mZ ddlmZ dd	lmZ dd
lmZmZmZ ddlmZ ddlmZmZ ddlmZmZ d Zd Zd$dZd%dZ ddddddddZ! eddgdg edh          ddg eeddd          gdgdgedgdd           dddddd!d"            Z" eddgdg edh          ddg eeddd          gdgdgedgdd           dddddd!d#            Z#dS )&    )IntegralN)issparse)digamma   )mutual_info_score)KDTreeNearestNeighbors)scale)check_random_state)Interval
StrOptionsvalidate_params)check_classification_targets)Paralleldelayed)check_array	check_X_yc                 D   | j         }|                     d          } |                    d          }t          j        | |f          }t	          d|          }|                    |           |                                d         }t          j        |dddf         d          }t          | d          }|	                    | |dd	
          }t          j
        |          dz
  }t          |d          }|	                    ||dd	
          }	t          j
        |	          dz
  }	t          |          t          |          z   t          j        t          |dz                       z
  t          j        t          |	dz                       z
  }
t          d|
          S )a{  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 in nat units. If it turned out to be
        negative it is replaced 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.
       	chebyshev)metricn_neighborsr   Nr   )r   TF
count_onlyreturn_distanceg      ?r   )sizereshapenphstackr	   fit
kneighbors	nextafterr   query_radiusarrayr   meanmax)xyr   	n_samplesxynnradiuskdnxnymis              f/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sklearn/feature_selection/_mutual_info.py_compute_mi_ccr4      sz   < I			'A			'A	Aq6		B 
+	F	F	FBFF2JJJ]]__QF\&B-++F 
+	&	&	&B	FtU	K	KB	"	B	+	&	&	&B	FtU	K	KB	"	B 		
+

	
''"q&//
"
"	# ''"q&//
"
"	#  q"::    c                 R   | j         d         }|                     d          } t          j        |          }t          j        |          }t          j        |          }t	                      }t          j        |          D ]}||k    }	t          j        |	          }
|
dk    rt          ||
dz
            }|                    |           |	                    | |	                    |
                                d         }t          j        |dddf         d          ||	<   |||	<   |
||	<   |dk    }	t          j        |	          }||	         }||	         }| |	         } ||	         }t          |           }|                    | |dd	          }t          j        |          }t          |          t          j        t          |                    z   t          j        t          |                    z
  t          j        t          |                    z
  }t#          d|          S )
a  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 in nat units. If it turned out to be
        negative it is replaced 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.
    r   r   r   )r   Nr   TFr   )shaper   r    emptyr	   uniquesummin
set_paramsr"   r#   r$   r   r%   r&   r   r'   r(   )cdr   r+   r.   label_countsk_allr-   labelmaskcountkrr/   m_allr2   s                   r3   _compute_mi_cdrG   S   s   @ 
I			'AXi  F8I&&LHYE			B1 
# 
#Ezt199K++AMMaM(((FF1T7OOO"A<!!!R%!44F4LE$K"T !DtI%L$KE	$AD\F	BOOAv$ONNEHUOOE 		
''%..
!
!	"
'',''
(
(	) ''%..
!
!	"  q"::r5      c                     |r|rt          | |          S |r|st          || |          S |s|rt          | ||          S t          | ||          S )zCompute 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.
    )r   rG   r4   )r)   r*   
x_discrete
y_discreter   s        r3   _compute_mirL      sw      1j 1 A&&&	 1J 1aK000 1J 1aK000aK000r5   c              #   R  K   |t          | j        d                   }t          |           rf|D ]a}t          j        | j        d                   }| j        |         | j        |dz            }}| j        ||         || j        ||         <   |V  bdS |D ]}| dd|f         V  dS )a  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.
    Nr   r   )ranger7   r   r    zerosindptrdataindices)Xcolumnsir)   	start_ptrend_ptrs         r3   _iterate_columnsrX      s        
##{{  	 	A$$A!"!ahq1uowI./fYw5F.GAai	')*+GGGG		 	  	 	AAAAqD'MMMM	 	r5   autoFTdiscrete_featuresdiscrete_targetr   copyrandom_staten_jobsc          
         t          | d           \  } | j        \  }}	t          |t          t          f          rkt          |t                    r%|dk    rt          |           }nt          d          t          j        |	t                    }
|
	                    |           n?t          |d          }|j        dk    r!t          j        |	t                    }
d	|
|<   n|}
|
 }t          j        |          rt          |           rt          d
          t          |          }t          j        |          r|                     t          j        |          } t#          | dd|f         dd          | dd|f<   t          j        dt          j        t          j        | dd|f                   d                    }| dd|fxx         d|z  |                    |t          j        |          f          z  z  cc<   sgt#          d          dt          j        dt          j        t          j                                      z  |                    |          z  z   t/          |          fdt1          t3          |           |
          D                       }t          j        |          S )a  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 of 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, default=None
        Determines random number generation for adding small noise to
        continuous variables in order to remove repeated values.
        Pass an int for reproducible results across multiple function calls.
        See :term:`Glossary <random_state>`.

    n_jobs : int, default=None
        The number of jobs to use for computing the mutual information.
        The parallelization is done on the columns of `X`.
        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

        .. versionadded:: 1.5


    Returns
    -------
    mi : ndarray, shape (n_features,)
        Estimated mutual information between each feature and the target in
        nat units. 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.
    csc)accept_sparse	y_numericrY   z+Invalid string value for discrete_features.)dtypeF)	ensure_2dboolTz1Sparse matrix `X` can't have continuous features.)r]   N)	with_meanr]   r   r   )axisg|=)r   )rg   )r_   c              3   `   K   | ](\  }} t          t                    ||          V  )d S N)r   rL   ).0r)   discrete_featurer\   r   r*   s      r3   	<genexpr>z_estimate_mi.<locals>.<genexpr>=  sW       ! !A 	Q#3_kRR! ! ! ! ! !r5   )r   r7   
isinstancestrrf   r   
ValueErrorr    r8   fillr   rd   rO   anyr   astypefloat64r
   maximumr'   absstandard_normalr:   r   ziprX   r&   )rS   r*   r[   r\   r   r]   r^   r_   r+   
n_featuresdiscrete_maskcontinuous_maskrngmeansr2   s    ` ``          r3   _estimate_mir~      s
   J Qo:MNNNDAqGIz#c4[11 .'-- 	P F**$,QKK!! !NOOO4888,----'(9UKKK"f,,HZt<<<M/3M+,,-M$nO	vo N8A;; NLMMM
\
*
*C	vo 
HHRZdH++ %aaa !U!
 !
 !
!!!_

 
1bgbfQqqq//A-B&C&C!LLLMM	!!!_
!!	26/3J3J'K!LLM	
  
!u%%%	jBGBF1II..//0!!y!112	
 
!	 	 	  ! ! ! ! ! !#&'7':':M#J#J! ! ! 
 
B
 8B<<r5   z
array-likezsparse matrixbooleanr   left)closedr^   rS   r*   r[   r   r]   r^   r_   )prefer_skip_nested_validation)r[   r   r]   r^   r_   c          
      0    t          | ||d||||          S )a~  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 of 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, default=None
        Determines random number generation for adding small noise to
        continuous variables in order to remove repeated values.
        Pass an int for reproducible results across multiple function calls.
        See :term:`Glossary <random_state>`.

    n_jobs : int, default=None
        The number of jobs to use for computing the mutual information.
        The parallelization is done on the columns of `X`.

        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

        .. versionadded:: 1.5

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

    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

    Examples
    --------
    >>> from sklearn.datasets import make_regression
    >>> from sklearn.feature_selection import mutual_info_regression
    >>> X, y = make_regression(
    ...     n_samples=50, n_features=3, n_informative=1, noise=1e-4, random_state=42
    ... )
    >>> mutual_info_regression(X, y)
    array([0.1..., 2.6...  , 0.0...])
    FrZ   )r~   r   s          r3   mutual_info_regressionr   E  s4    h 		+!	 	 	 	r5   c          
      N    t          |           t          | ||d||||          S )a  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, sparse matrix} of shape (n_samples, n_features)
        Feature matrix.

    y : array-like of shape (n_samples,)
        Target vector.

    discrete_features : 'auto', bool or 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, default=None
        Determines random number generation for adding small noise to
        continuous variables in order to remove repeated values.
        Pass an int for reproducible results across multiple function calls.
        See :term:`Glossary <random_state>`.

    n_jobs : int, default=None
        The number of jobs to use for computing the mutual information.
        The parallelization is done on the columns of `X`.
        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

        .. versionadded:: 1.5

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

    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

    Examples
    --------
    >>> from sklearn.datasets import make_classification
    >>> from sklearn.feature_selection import mutual_info_classif
    >>> X, y = make_classification(
    ...     n_samples=100, n_features=10, n_informative=2, n_clusters_per_class=1,
    ...     shuffle=False, random_state=42
    ... )
    >>> mutual_info_classif(X, y)
    array([0.58..., 0.10..., 0.19..., 0.09... , 0.        ,
           0.     , 0.     , 0.     , 0.      , 0.        ])
    TrZ   )r   r~   r   s          r3   mutual_info_classifr     sB    j !###		+!	 	 	 	r5   )rH   rj   )$numbersr   numpyr    scipy.sparser   scipy.specialr   metrics.clusterr   	neighborsr   r	   preprocessingr
   utilsr   utils._param_validationr   r   r   utils.multiclassr   utils.parallelr   r   utils.validationr   r   r4   rG   rL   rX   r~   r   r    r5   r3   <module>r      s             ! ! ! ! ! ! ! ! ! ! ! ! / / / / / / 0 0 0 0 0 0 0 0 ! ! ! ! ! ! & & & & & & K K K K K K K K K K ; ; ; ; ; ; . . . . . . . . 5 5 5 5 5 5 5 5< < <~F F FR1 1 1 1    D 	x x x x xv O,^(j&22I|L 1d6BBBC'(T"  #'    	q q q q qh O,^(j&22I|L 1d6BBBC'(T"  #'    	s s s s s s sr5   