ó
‡ˆ\c           @`  s½   d  d l  m Z m Z d  d l Z d  d l Z d  d l 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 e
 e f d „  ƒ  YZ d S(   i    (   t   divisiont   absolute_importNi   (   t   OneHotEncoderi   (   t   BaseEstimatort   TransformerMixin(   t   check_array(   t   check_is_fitted(   t   FLOAT_DTYPES(   t
   np_versiont   KBinsDiscretizerc           B`  sG   e  Z d  Z d d d d „ Z d	 d „ Z d „  Z d „  Z d „  Z RS(
   s  Bin continuous data into intervals.

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

    Parameters
    ----------
    n_bins : int or array-like, shape (n_features,) (default=5)
        The number of bins to produce. Raises ValueError if ``n_bins < 2``.

    encode : {'onehot', 'onehot-dense', 'ordinal'}, (default='onehot')
        Method used to encode the transformed result.

        onehot
            Encode the transformed result with one-hot encoding
            and return a sparse matrix. Ignored features are always
            stacked to the right.
        onehot-dense
            Encode the transformed result with one-hot encoding
            and return a dense array. Ignored features are always
            stacked to the right.
        ordinal
            Return the bin identifier encoded as an integer value.

    strategy : {'uniform', 'quantile', 'kmeans'}, (default='quantile')
        Strategy used to define the widths of the bins.

        uniform
            All bins in each feature have identical widths.
        quantile
            All bins in each feature have the same number of points.
        kmeans
            Values in each bin have the same nearest center of a 1D k-means
            cluster.

    Attributes
    ----------
    n_bins_ : int array, shape (n_features,)
        Number of bins per feature. Bins whose width are too small
        (i.e., <= 1e-8) are removed with a warning.

    bin_edges_ : array of arrays, shape (n_features, )
        The edges of each bin. Contain arrays of varying shapes ``(n_bins_, )``
        Ignored features will have empty arrays.

    Examples
    --------
    >>> X = [[-2, 1, -4,   -1],
    ...      [-1, 2, -3, -0.5],
    ...      [ 0, 3, -2,  0.5],
    ...      [ 1, 4, -1,    2]]
    >>> est = KBinsDiscretizer(n_bins=3, encode='ordinal', strategy='uniform')
    >>> est.fit(X)  # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
    KBinsDiscretizer(...)
    >>> Xt = est.transform(X)
    >>> Xt  # doctest: +SKIP
    array([[ 0., 0., 0., 0.],
           [ 1., 1., 1., 0.],
           [ 2., 2., 2., 1.],
           [ 2., 2., 2., 2.]])

    Sometimes it may be useful to convert the data back into the original
    feature space. The ``inverse_transform`` function converts the binned
    data into the original feature space. Each value will be equal to the mean
    of the two bin edges.

    >>> est.bin_edges_[0]
    array([-2., -1.,  0.,  1.])
    >>> est.inverse_transform(Xt)
    array([[-1.5,  1.5, -3.5, -0.5],
           [-0.5,  2.5, -2.5, -0.5],
           [ 0.5,  3.5, -1.5,  0.5],
           [ 0.5,  3.5, -1.5,  1.5]])

    Notes
    -----
    In bin edges for feature ``i``, the first and last values are used only for
    ``inverse_transform``. During transform, bin edges are extended to::

      np.concatenate([-np.inf, bin_edges_[i][1:-1], np.inf])

    You can combine ``KBinsDiscretizer`` with
    :class:`sklearn.compose.ColumnTransformer` if you only want to preprocess
    part of the features.

    ``KBinsDiscretizer`` might produce constant features (e.g., when
    ``encode = 'onehot'`` and certain bins do not contain any data).
    These features can be removed with feature selection algorithms
    (e.g., :class:`sklearn.feature_selection.VarianceThreshold`).

    See also
    --------
     sklearn.preprocessing.Binarizer : class used to bin values as ``0`` or
        ``1`` based on a parameter ``threshold``.
    i   t   onehott   quantilec         C`  s   | |  _  | |  _ | |  _ d  S(   N(   t   n_binst   encodet   strategy(   t   selfR   R   R   (    (    sD   lib/python2.7/site-packages/sklearn/preprocessing/_discretization.pyt   __init__w   s    		c         C`  sö  t  | d d ƒ} d } |  j | k rE t d j | |  j ƒ ƒ ‚ n  d } |  j | k rx t d
 j | |  j ƒ ƒ ‚ n  | j d } |  j | ƒ } t j | d t	 ƒ} x´t
 | ƒ D]¦} | d d … | f }	 |	 j ƒ  |	 j ƒ  }
 } |
 | k r8t j d | ƒ d | | <t j t j t j g ƒ | | <q¶ n  |  j d k rkt j |
 | | | d ƒ | | <na|  j d k rÔt j d d | | d ƒ } t d k  r²t | ƒ } n  t j t j |	 | ƒ ƒ | | <nø |  j d	 k rÌd d l m } t j |
 | | | d ƒ } | d | d  d d … d f d } | d | | d | d d ƒ } | j |	 d d … d f ƒ j d d … d f } | j ƒ  | d | d  d | | <t j |
 | | | f | | <n  |  j d  k r¶ t j | | d t j ƒd k } | | | | | <t | | ƒ d | | k r\t j d | ƒ t | | ƒ d | | <q\q¶ q¶ W| |  _ | |  _  d |  j k ròt! d g  |  j  D] } t j" | ƒ ^ q‘d |  j d k ƒ |  _# |  j# j t j d t |  j  ƒ f d t$ ƒƒ n  |  S(!   sè   Fits the estimator.

        Parameters
        ----------
        X : numeric array-like, shape (n_samples, n_features)
            Data to be discretized.

        y : ignored

        Returns
        -------
        self
        t   dtypet   numericR
   s   onehot-denset   ordinals;   Valid options for 'encode' are {}. Got encode={!r} instead.t   uniformR   t   kmeanss?   Valid options for 'strategy' are {}. Got strategy={!r} instead.i   Ns3   Feature %d is constant and will be replaced with 0.i    id   i	   i   (   t   KMeansiÿÿÿÿg      à?t
   n_clusterst   initt   n_initt   to_beging:Œ0âŽyE>sq   Bins whose width are too small (i.e., <= 1e-8) in feature %d are removed. Consider decreasing the number of bins.t
   categoriest   sparse(   R
   s   onehot-denseR   (   R   R   R   (   i   i	   (   R   R   (%   R   R   t
   ValueErrort   formatR   t   shapet   _validate_n_binst   npt   zerost   objectt   ranget   mint   maxt   warningst   warnt   arrayt   inft   linspaceR   t   listt   asarrayt
   percentilet   clusterR   t   Nonet   fitt   cluster_centers_t   sortt   r_t   ediff1dt   lent
   bin_edges_t   n_bins_R   t   aranget   _encodert   int(   R   t   Xt   yt   valid_encodet   valid_strategyt
   n_featuresR   t	   bin_edgest   jjt   columnt   col_mint   col_maxt	   quantilesR   t   uniform_edgesR   t   kmt   centerst   maskt   i(    (    sD   lib/python2.7/site-packages/sklearn/preprocessing/_discretization.pyR1   |   sh    			
 $"&2
!"	"		%1c         C`  si  |  j  } t | t j ƒ r  t | t j t j f ƒ s] t d j t	 j
 t | ƒ j
 ƒ ƒ ‚ n  | d k  r‡ t d j t	 j
 | ƒ ƒ ‚ n  t j | | d t j ƒSt | d t j d t d t ƒ} | j d k sã | j d | k rò t d	 ƒ ‚ n  | d k  | | k B} t j | ƒ d } | j d d k red
 j d „  | Dƒ ƒ } t d j t	 j
 | ƒ ƒ ‚ n  | S(   s9   Returns n_bins_, the number of bins per feature.
        s>   {} received an invalid n_bins type. Received {}, expected int.i   sH   {} received an invalid number of bins. Received {}, expected at least 2.R   t   copyt	   ensure_2di   i    s8   n_bins must be a scalar or array of shape (n_features,).s   , c         s`  s   |  ] } t  | ƒ Vq d  S(   N(   t   str(   t   .0RK   (    (    sD   lib/python2.7/site-packages/sklearn/preprocessing/_discretization.pys	   <genexpr>ð   s    sk   {} received an invalid number of bins at indices {}. Number of bins must be at least 2, and must be an int.(   R   t
   isinstancet   numberst   Numbert   IntegralR!   t   integerR   R   R	   t   __name__t   typet   fullR;   R   t   Truet   Falset   ndimR   t   wheret   join(   R   R@   t	   orig_binsR   t   bad_nbins_valuet   violating_indicest   indices(    (    sD   lib/python2.7/site-packages/sklearn/preprocessing/_discretization.pyR    Õ   s*    				"	c   	      C`  sH  t  |  d g ƒ t | d t d t ƒ} |  j j d } | j d | k rm t d j | | j d ƒ ƒ ‚ n  |  j } xŒ t	 | j d ƒ D]w } d } d } | | t
 j | d	 d	 … | f ƒ } t
 j | d	 d	 … | f | | | d ƒ | d	 d	 … | f <qŠ Wt
 j | d |  j d d
 | ƒ|  j d k r8| S|  j j | ƒ S(   s  Discretizes the data.

        Parameters
        ----------
        X : numeric array-like, shape (n_samples, n_features)
            Data to be discretized.

        Returns
        -------
        Xt : numeric array-like or sparse matrix
            Data in the binned space.
        R7   RL   R   i    i   s8   Incorrect number of features. Expecting {}, received {}.gñhãˆµøä>g:Œ0âŽyE>Nt   outR   (   R   R   RX   R   R8   R   R   R   R7   R$   R!   t   abst   digitizet   clipR   R:   t	   transform(	   R   R<   t   XtR@   RA   RB   t   rtolt   atolt   eps(    (    sD   lib/python2.7/site-packages/sklearn/preprocessing/_discretization.pyRe   ÷   s     		'B c         C`  s  t  |  d g ƒ d |  j k r4 |  j j | ƒ } n  t | d t d t ƒ} |  j j d } | j d | k r‘ t	 d j
 | | j d ƒ ƒ ‚ n  xj t | ƒ D]\ } |  j | } | d | d  d	 } | t j | d
 d
 … | f ƒ | d
 d
 … | f <qž W| S(   s½  Transforms discretized data back to original feature space.

        Note that this function does not regenerate the original data
        due to discretization rounding.

        Parameters
        ----------
        Xt : numeric array-like, shape (n_sample, n_features)
            Transformed data in the binned space.

        Returns
        -------
        Xinv : numeric array-like
            Data in the original feature space.
        R7   R
   RL   R   i    i   s8   Incorrect number of features. Expecting {}, received {}.iÿÿÿÿg      à?N(   R   R   R:   t   inverse_transformR   RX   R   R8   R   R   R   R$   R7   R!   t   int_(   R   Rf   t   XinvR@   RB   RA   t   bin_centers(    (    sD   lib/python2.7/site-packages/sklearn/preprocessing/_discretization.pyRj     s    	7N(	   RU   t
   __module__t   __doc__R   R0   R1   R    Re   Rj   (    (    (    sD   lib/python2.7/site-packages/sklearn/preprocessing/_discretization.pyR	      s   ^Y	"	&(   t
   __future__R    R   RQ   t   numpyR!   R'   t    R   t   baseR   R   t   utils.validationR   R   R   t   utils.fixesR   R	   (    (    (    sD   lib/python2.7/site-packages/sklearn/preprocessing/_discretization.pyt   <module>   s   