ó
‡ˆ\c           @   sü  d  Z  d d l m Z d d l Z d d l Z d d l m Z 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 e d ƒ d „  ƒ Z d „  Z e d „ Z d „  Z d „  Z e d ƒ d d „ ƒ Z d „  Z  e d „ Z! d d d „ Z" d d d d e# d d „ Z$ e d ƒ d d „ ƒ Z d d „ Z% e d  ƒ d d e# d! „ ƒ Z& d d" „ Z' e# d# „ Z( d d$ „ Z) e# d% „ Z* d& „  Z+ d d' „ Z, d( „  Z- d) „  Z. d d* d+ d, „ Z/ d S(-   s   
Extended math utilities.
iÿÿÿÿ(   t   divisionN(   t   linalgt   sparsei   (   t   check_random_statet
   deprecated(   t
   np_version(   t	   logsumexp(   t   _log_logistic_sigmoidi   (   t   xrange(   t   csr_row_norms(   t   check_arraysu   sklearn.utils.extmath.norm was deprecated in version 0.19 and will be removed in 0.21. Use scipy.linalg.norm instead.c         C   s   t  j |  ƒ S(   sÆ   Compute the Euclidean or Frobenius norm of x.

    Returns the Euclidean norm when x is a vector, the Frobenius norm when x
    is a matrix (2-d array). More precise than sqrt(squared_norm(x)).
    (   R   t   norm(   t   x(    (    s4   lib/python2.7/site-packages/sklearn/utils/extmath.pyR      s    c         C   sP   t  j |  d d ƒ}  t  j |  j t  j ƒ r@ t j d t ƒ n  t  j |  |  ƒ S(   s  Squared Euclidean or Frobenius norm of x.

    Faster than norm(x) ** 2.

    Parameters
    ----------
    x : array_like

    Returns
    -------
    float
        The Euclidean norm when x is a vector, the Frobenius norm when x
        is a matrix (2-d array).
    t   ordert   KsY   Array type is integer, np.dot may overflow. Data should be float type to avoid this issue(	   t   npt   ravelt
   issubdtypet   dtypet   integert   warningst   warnt   UserWarningt   dot(   R   (    (    s4   lib/python2.7/site-packages/sklearn/utils/extmath.pyt   squared_norm(   s
    	
c         C   st   t  j |  ƒ rB t |  t  j ƒ s3 t  j |  ƒ }  n  t |  ƒ } n t j d |  |  ƒ } | sp t j | | ƒ n  | S(   sÒ  Row-wise (squared) Euclidean norm of X.

    Equivalent to np.sqrt((X * X).sum(axis=1)), but also supports sparse
    matrices and does not create an X.shape-sized temporary.

    Performs no input validation.

    Parameters
    ----------
    X : array_like
        The input array
    squared : bool, optional (default = False)
        If True, return squared norms.

    Returns
    -------
    array_like
        The row-wise (squared) Euclidean norm of X.
    s   ij,ij->i(   R   t   issparset
   isinstancet
   csr_matrixR	   R   t   einsumt   sqrt(   t   Xt   squaredt   norms(    (    s4   lib/python2.7/site-packages/sklearn/utils/extmath.pyt	   row_norms?   s    c         C   s0   t  j j |  ƒ \ } } | d k s, t  j S| S(   sæ   Compute log(det(A)) for A symmetric

    Equivalent to : np.log(nl.det(A)) but more robust.
    It returns -Inf if det(A) is non positive or is not defined.

    Parameters
    ----------
    A : array_like
        The matrix
    i    (   R   R   t   slogdett   inf(   t   At   signt   ld(    (    s4   lib/python2.7/site-packages/sklearn/utils/extmath.pyt   fast_logdet_   s    c         C   sK   |  j  j r+ t |  j d t d d ƒt f St |  d t d d ƒt f Sd S(   s   Helper Functiont   copyR   t   FN(   t   flagst   c_contiguousR
   t   Tt   Falset   True(   R   (    (    s4   lib/python2.7/site-packages/sklearn/utils/extmath.pyt   _impose_f_orderp   s    s}   sklearn.utils.extmath.fast_dot was deprecated in version 0.19 and will be removed in 0.21. Use the equivalent np.dot instead.c         C   s   t  j |  | | ƒ S(   N(   R   R   (   t   at   bt   out(    (    s4   lib/python2.7/site-packages/sklearn/utils/extmath.pyt   fast_dotz   s    c         K   sl   t  |  d ƒ r7 t |  j ƒ |  j d |  j d } n1 |  d k rI d n t |  d k j ƒ  ƒ |  j } | S(   sÀ   Compute density of a sparse vector

    Parameters
    ----------
    w : array_like
        The sparse vector

    Returns
    -------
    float
        The density of w, between 0 and 1
    t   toarrayi    i   N(   t   hasattrt   floatt   nnzt   shapet   Nonet   sumt   size(   t   wt   kwargst   d(    (    s4   lib/python2.7/site-packages/sklearn/utils/extmath.pyt   density€   s    (1c         C   sd   t  j |  ƒ s t  j | ƒ rP |  | } | rL t | d ƒ rL | j ƒ  } n  | St j |  | ƒ Sd S(   s2  Dot product that handle the sparse matrix case correctly

    Uses BLAS GEMM as replacement for numpy.dot where possible
    to avoid unnecessary copies.

    Parameters
    ----------
    a : array or sparse matrix
    b : array or sparse matrix
    dense_output : boolean, default False
        When False, either ``a`` or ``b`` being sparse will yield sparse
        output. When True, output will always be an array.

    Returns
    -------
    dot_product : array or sparse matrix
        sparse if ``a`` or ``b`` is sparse and ``dense_output=False``.
    R4   N(   R   R   R5   R4   R   R   (   R0   R1   t   dense_outputt   ret(    (    s4   lib/python2.7/site-packages/sklearn/utils/extmath.pyt   safe_sparse_dot”   s    
t   autoc         C   s¥  t  | ƒ } | j d |  j d | f ƒ } |  j j d k rX | j |  j d t ƒ} n  | d k r‚ | d k ry d } q‚ d } n  xø t | ƒ D]ê } | d k rÅ t |  | ƒ } t |  j	 | ƒ } q | d k rt
 j t |  | ƒ d	 t ƒ\ } } t
 j t |  j	 | ƒ d	 t ƒ\ } } q | d
 k r t
 j t |  | ƒ d d ƒ\ } } t
 j t |  j	 | ƒ d d ƒ\ } } q q Wt
 j t |  | ƒ d d ƒ\ } } | S(   sÞ  Computes an orthonormal matrix whose range approximates the range of A.

    Parameters
    ----------
    A : 2D array
        The input data matrix

    size : integer
        Size of the return array

    n_iter : integer
        Number of power iterations used to stabilize the result

    power_iteration_normalizer : 'auto' (default), 'QR', 'LU', 'none'
        Whether the power iterations are normalized with step-by-step
        QR factorization (the slowest but most accurate), 'none'
        (the fastest but numerically unstable when `n_iter` is large, e.g.
        typically 5 or larger), or 'LU' factorization (numerically stable
        but can lose slightly in accuracy). The 'auto' mode applies no
        normalization if `n_iter` <= 2 and switches to LU otherwise.

        .. versionadded:: 0.18

    random_state : int, RandomState instance or None, optional (default=None)
        The seed of the pseudo random number generator to use when shuffling
        the data.  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
    -------
    Q : 2D array
        A (size x size) projection matrix, the range of which
        approximates well the range of the input matrix A.

    Notes
    -----

    Follows Algorithm 4.3 of
    Finding structure with randomness: Stochastic algorithms for constructing
    approximate matrix decompositions
    Halko, et al., 2009 (arXiv:909) https://arxiv.org/pdf/0909.4061.pdf

    An implementation of a randomized algorithm for principal component
    analysis
    A. Szlam et al. 2014
    R;   i   t   fR(   RC   i   t   nonet   LUt	   permute_lt   QRt   modet   economic(   R   t   normalR8   R   t   kindt   astypeR-   t   rangeRB   R,   R   t   luR.   t   qr(   R$   R;   t   n_itert   power_iteration_normalizert   random_statet   Qt   it   _(    (    s4   lib/python2.7/site-packages/sklearn/utils/extmath.pyt   randomized_range_finder°   s(    3		$*$.$i
   i    c         C   sò  t  |  t j t j f ƒ rC t j d j t |  ƒ j ƒ t j	 ƒ n  t
 | ƒ } | | } |  j \ }	 }
 | d k rœ | d t |  j ƒ k  r“ d n d } n  | d k r· |	 |
 k  } n  | rÉ |  j }  n  t |  | | | | ƒ } t | j |  ƒ } t j | d t ƒ\ } } } ~ t j | | ƒ } | rh| sJt | | ƒ \ } } qht | | d t ƒ\ } } n  | r±| d | … d d … f j | |  | d d … d | … f j f S| d d … d | … f | |  | d | … d d … f f Sd S(	   s¯  Computes a truncated randomized SVD

    Parameters
    ----------
    M : ndarray or sparse matrix
        Matrix to decompose

    n_components : int
        Number of singular values and vectors to extract.

    n_oversamples : int (default is 10)
        Additional number of random vectors to sample the range of M so as
        to ensure proper conditioning. The total number of random vectors
        used to find the range of M is n_components + n_oversamples. Smaller
        number can improve speed but can negatively impact the quality of
        approximation of singular vectors and singular values.

    n_iter : int or 'auto' (default is 'auto')
        Number of power iterations. It can be used to deal with very noisy
        problems. When 'auto', it is set to 4, unless `n_components` is small
        (< .1 * min(X.shape)) `n_iter` in which case is set to 7.
        This improves precision with few components.

        .. versionchanged:: 0.18

    power_iteration_normalizer : 'auto' (default), 'QR', 'LU', 'none'
        Whether the power iterations are normalized with step-by-step
        QR factorization (the slowest but most accurate), 'none'
        (the fastest but numerically unstable when `n_iter` is large, e.g.
        typically 5 or larger), or 'LU' factorization (numerically stable
        but can lose slightly in accuracy). The 'auto' mode applies no
        normalization if `n_iter` <= 2 and switches to LU otherwise.

        .. versionadded:: 0.18

    transpose : True, False or 'auto' (default)
        Whether the algorithm should be applied to M.T instead of M. The
        result should approximately be the same. The 'auto' mode will
        trigger the transposition if M.shape[1] > M.shape[0] since this
        implementation of randomized SVD tend to be a little faster in that
        case.

        .. versionchanged:: 0.18

    flip_sign : boolean, (True by default)
        The output of a singular value decomposition is only unique up to a
        permutation of the signs of the singular vectors. If `flip_sign` is
        set to `True`, the sign ambiguity is resolved by making the largest
        loadings for each component in the left singular vectors positive.

    random_state : int, RandomState instance or None, optional (default=None)
        The seed of the pseudo random number generator to use when shuffling
        the data.  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`.

    Notes
    -----
    This algorithm finds a (usually very good) approximate truncated
    singular value decomposition using randomization to speed up the
    computations. It is particularly fast on large matrices on which
    you wish to extract only a small number of components. In order to
    obtain further speed up, `n_iter` can be set <=2 (at the cost of
    loss of precision).

    References
    ----------
    * Finding structure with randomness: Stochastic algorithms for constructing
      approximate matrix decompositions
      Halko, et al., 2009 https://arxiv.org/abs/0909.4061

    * A randomized algorithm for the decomposition of matrices
      Per-Gunnar Martinsson, Vladimir Rokhlin and Mark Tygert

    * An implementation of a randomized algorithm for principal component
      analysis
      A. Szlam et al. 2014
    sC   Calculating SVD of a {} is expensive. csr_matrix is more efficient.RC   gš™™™™™¹?i   i   t   full_matricest   u_based_decisionN(   R   R   t
   lil_matrixt
   dok_matrixR   R   t   formatt   typet   __name__t   SparseEfficiencyWarningR   R8   t   minR,   RW   RB   R   t   svdR-   R   R   t   svd_flip(   t   Mt   n_componentst   n_oversamplesRQ   RR   t	   transposet	   flip_signRS   t   n_randomt	   n_samplest
   n_featuresRT   t   Bt   Uhatt   st   Vt   U(    (    s4   lib/python2.7/site-packages/sklearn/utils/extmath.pyt   randomized_svd  s4    R
(Cs}   sklearn.utils.extmath.logsumexp was deprecated in version 0.19 and will be removed in 0.21. Use scipy.misc.logsumexp instead.c         C   s   t  |  | ƒ S(   s|  Computes the sum of arr assuming arr is in the log domain.
    Returns log(sum(exp(arr))) while minimizing the possibility of
    over/underflow.
    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.utils.extmath import logsumexp
    >>> a = np.arange(10)
    >>> np.log(np.sum(np.exp(a)))
    9.458...
    >>> logsumexp(a)  # doctest: +SKIP
    9.458...
    (   t   scipy_logsumexp(   t   arrt   axis(    (    s4   lib/python2.7/site-packages/sklearn/utils/extmath.pyR   ‡  s    c         C   sk  | d k r3 t j |  ƒ }  t j | ƒ } d } n t j |  ƒ }  t j | ƒ } |  j | j k r„ t j |  j | d | j ƒ} n  t j t j |  ƒ ƒ } t |  j ƒ } d | | <t j	 | ƒ } t j	 | ƒ } x‹ | D]ƒ } t j	 |  j ƒ } |  | k }	 | |	 | |	 <t j
 t j | | ƒ | ƒ }
 t j |
 | k | | ƒ } t j |
 | ƒ } | } qÚ W| | f S(   s  Returns an array of the weighted modal (most common) value in a

    If there is more than one such value, only the first is returned.
    The bin-count for the modal bins is also returned.

    This is an extension of the algorithm in scipy.stats.mode.

    Parameters
    ----------
    a : array_like
        n-dimensional array of which to find mode(s).
    w : array_like
        n-dimensional array of weights for each value
    axis : int, optional
        Axis along which to operate. Default is 0, i.e. the first axis.

    Returns
    -------
    vals : ndarray
        Array of modal values.
    score : ndarray
        Array of weighted counts for each mode.

    Examples
    --------
    >>> from sklearn.utils.extmath import weighted_mode
    >>> x = [4, 1, 4, 2, 4, 2]
    >>> weights = [1, 1, 1, 1, 1, 1]
    >>> weighted_mode(x, weights)
    (array([4.]), array([3.]))

    The value 4 appears three times: with uniform weights, the result is
    simply the mode of the distribution.

    >>> weights = [1, 3, 0.5, 1.5, 1, 2] # deweight the 4's
    >>> weighted_mode(x, weights)
    (array([2.]), array([3.5]))

    The value 2 has the highest score: it appears twice with weights of
    1.5 and 2: the sum of these is 3.

    See Also
    --------
    scipy.stats.mode
    i    R   i   N(   R9   R   R   t   asarrayR8   t   fullR   t   uniquet   listt   zerost   expand_dimsR:   t   wheret   maximum(   R0   R<   Rs   t   scorest	   testshapet   oldmostfreqt	   oldcountst   scoret   templatet   indt   countst   mostfrequent(    (    s4   lib/python2.7/site-packages/sklearn/utils/extmath.pyt   weighted_modeš  s,    .	!

sw   sklearn.utils.extmath.pinvh was deprecated in version 0.19 and will be removed in 0.21. Use scipy.linalg.pinvh instead.c         C   s   t  j |  | | | ƒ S(   N(   R   t   pinvh(   R0   t   condt   rcondt   lower(    (    s4   lib/python2.7/site-packages/sklearn/utils/extmath.pyR†   ã  s    c         C   sÜ   g  |  D] } t  j | ƒ ^ q }  d „  |  Dƒ } |  d j } t  j | ƒ } | j t |  ƒ d ƒ j } | d k r t  j | d | ƒ} n  xH t	 |  ƒ D]: \ } } |  | | d d … | f | d d … | f <qš W| S(   sÒ  Generate a cartesian product of input arrays.

    Parameters
    ----------
    arrays : list of array-like
        1-D arrays to form the cartesian product of.
    out : ndarray
        Array to place the cartesian product in.

    Returns
    -------
    out : ndarray
        2-D array of shape (M, len(arrays)) containing cartesian products
        formed of input arrays.

    Examples
    --------
    >>> cartesian(([1, 2, 3], [4, 5], [6, 7]))
    array([[1, 4, 6],
           [1, 4, 7],
           [1, 5, 6],
           [1, 5, 7],
           [2, 4, 6],
           [2, 4, 7],
           [2, 5, 6],
           [2, 5, 7],
           [3, 4, 6],
           [3, 4, 7],
           [3, 5, 6],
           [3, 5, 7]])

    c         s   s   |  ] } t  | ƒ Vq d  S(   N(   t   len(   t   .0R   (    (    s4   lib/python2.7/site-packages/sklearn/utils/extmath.pys	   <genexpr>  s    i    iÿÿÿÿR   N(
   R   Rt   R   t   indicest   reshapeRŠ   R,   R9   t
   empty_liket	   enumerate(   t   arraysR2   R   R8   R   t   ixt   nRr   (    (    s4   lib/python2.7/site-packages/sklearn/utils/extmath.pyt	   cartesiané  s    !"2c         C   sé   | rt t  j t  j |  ƒ d d ƒ} t  j |  | t |  j d ƒ f ƒ } |  | 9}  | | d d … t  j f 9} nk t  j t  j | ƒ d d ƒ} t  j | t | j d ƒ | f ƒ } |  | 9}  | | d d … t  j f 9} |  | f S(   sÕ  Sign correction to ensure deterministic output from SVD.

    Adjusts the columns of u and the rows of v such that the loadings in the
    columns in u that are largest in absolute value are always positive.

    Parameters
    ----------
    u : ndarray
        u and v are the output of `linalg.svd` or
        `sklearn.utils.extmath.randomized_svd`, with matching inner dimensions
        so one can compute `np.dot(u * s, v)`.

    v : ndarray
        u and v are the output of `linalg.svd` or
        `sklearn.utils.extmath.randomized_svd`, with matching inner dimensions
        so one can compute `np.dot(u * s, v)`.

    u_based_decision : boolean, (default=True)
        If True, use the columns of u as the basis for sign flipping.
        Otherwise, use the rows of v. The choice of which variable to base the
        decision on is generally algorithm dependent.


    Returns
    -------
    u_adjusted, v_adjusted : arrays with the same dimensions as the input.

    Rs   i    i   N(   R   t   argmaxt   absR%   R   R8   t   newaxis(   t   ut   vRY   t   max_abs_colst   signst   max_abs_rows(    (    s4   lib/python2.7/site-packages/sklearn/utils/extmath.pyRb     s    &
 &
c         C   sŠ   |  j  d k } t j |  ƒ }  t |  d t j ƒ}  |  j \ } } | d k r` t j |  ƒ } n  t | | |  | ƒ | r† t j	 | ƒ S| S(   s9  Compute the log of the logistic function, ``log(1 / (1 + e ** -x))``.

    This implementation is numerically stable because it splits positive and
    negative values::

        -log(1 + exp(-x_i))     if x_i > 0
        x_i - log(1 + exp(x_i)) if x_i <= 0

    For the ordinary logistic function, use ``scipy.special.expit``.

    Parameters
    ----------
    X : array-like, shape (M, N) or (M, )
        Argument to the logistic function

    out : array-like, shape: (M, N) or (M, ), optional:
        Preallocated output array.

    Returns
    -------
    out : array, shape (M, N) or (M, )
        Log of the logistic function evaluated at every point in x

    Notes
    -----
    See the blog post describing this implementation:
    http://fa.bianp.net/blog/2013/numerical-optimizers-for-logistic-regression/
    i   R   N(
   t   ndimR   t
   atleast_2dR
   t   float64R8   R9   RŽ   R   t   squeeze(   R   R2   t   is_1dRi   Rj   (    (    s4   lib/python2.7/site-packages/sklearn/utils/extmath.pyt   log_logisticF  s    c         C   s|   | r t  j |  ƒ }  n  t  j |  d d ƒj d ƒ } |  | 8}  t  j |  |  ƒ t  j |  d d ƒj d ƒ } |  | }  |  S(   s5  
    Calculate the softmax function.

    The softmax function is calculated by
    np.exp(X) / np.sum(np.exp(X), axis=1)

    This will cause overflow when large values are exponentiated.
    Hence the largest value in each row is subtracted from each data
    point to prevent this.

    Parameters
    ----------
    X : array-like of floats, shape (M, N)
        Argument to the logistic function

    copy : bool, optional
        Copy X or not.

    Returns
    -------
    out : array, shape (M, N)
        Softmax function evaluated at every point in x
    Rs   i   iÿÿÿÿ(   iÿÿÿÿi   (   iÿÿÿÿi   (   R   R(   t   maxR   t   expR:   (   R   R(   t   max_probt   sum_prob(    (    s4   lib/python2.7/site-packages/sklearn/utils/extmath.pyt   softmaxs  s    

c         C   sk   t  j |  ƒ r] t |  j ƒ d k r( d S|  j j ƒ  } |  j ƒ  |  j k rP | St | d ƒ S|  j ƒ  Sd S(   s  Returns the minimum value of a dense or a CSR/CSC matrix.

    Adapated from https://stackoverflow.com/q/13426580

    Parameters
    ----------
    X : array_like
        The input array or sparse matrix

    Returns
    -------
    Float
        The min value of X
    i    N(   R   R   RŠ   t   dataR`   t   getnnzR;   (   R   t   m(    (    s4   lib/python2.7/site-packages/sklearn/utils/extmath.pyt   safe_min•  s    &c         C   sK   t  |  ƒ } | | k  rG t j |  ƒ r6 t d ƒ ‚ n  |  | | }  n  |  S(   s6  Ensure `X.min()` >= `min_value`.

    Parameters
    ----------
    X : array_like
        The matrix to make non-negative
    min_value : float
        The threshold value

    Returns
    -------
    array_like
        The thresholded array

    Raises
    ------
    ValueError
        When X is sparse
    s{   Cannot make the data matrix nonnegative because it is sparse. Adding a value to every entry would make it no longer sparse.(   Rª   R   R   t
   ValueError(   R   t	   min_valuet   min_(    (    s4   lib/python2.7/site-packages/sklearn/utils/extmath.pyt   make_nonnegative­  s    c         C   sa  | | } t  j |  j t  j ƒ ra |  j j d k  ra t  j |  d d d t  j ƒj |  j ƒ } n t  j |  d d ƒ} t  j t  j	 |  ƒ d d ƒ} | | } | | | } | d	 k rÂ d	 }	 n’ t  j |  d d ƒ| }
 | | } t  j d d d d ƒ 1 | | } | |
 | | | | | d } Wd	 QX| d k } |
 | | | <| | }	 | |	 | f S(
   sÈ  Calculate mean update and a Youngs and Cramer variance update.

    last_mean and last_variance are statistics computed at the last step by the
    function. Both must be initialized to 0.0. In case no scaling is required
    last_variance can be None. The mean is always required and returned because
    necessary for the calculation of the variance. last_n_samples_seen is the
    number of samples encountered until now.

    From the paper "Algorithms for computing the sample variance: analysis and
    recommendations", by Chan, Golub, and LeVeque.

    Parameters
    ----------
    X : array-like, shape (n_samples, n_features)
        Data to use for variance update

    last_mean : array-like, shape: (n_features,)

    last_variance : array-like, shape: (n_features,)

    last_sample_count : array-like, shape (n_features,)

    Returns
    -------
    updated_mean : array, shape (n_features,)

    updated_variance : array, shape (n_features,)
        If None, only mean is computed

    updated_sample_count : array, shape (n_features,)

    Notes
    -----
    NaNs are ignored during the algorithm.

    References
    ----------
    T. Chan, G. Golub, R. LeVeque. Algorithms for computing the sample
        variance: recommendations, The American Statistician, Vol. 37, No. 3,
        pp. 242-247

    Also, see the sparse implementation of this in
    `utils.sparsefuncs.incr_mean_variance_axis` and
    `utils.sparsefuncs_fast.incr_mean_variance_axis0`
    i   Rs   i    R   t   dividet   ignoret   invalidi   N(   R   R   R   t   floatingt   itemsizet   nansumRž   RM   R:   t   isnanR9   t   nanvart   errstate(   R   t	   last_meant   last_variancet   last_sample_countt   last_sumt   new_sumt   new_sample_countt   updated_sample_countt   updated_meant   updated_variancet   new_unnormalized_variancet   last_unnormalized_variancet   last_over_new_countt   updated_unnormalized_varianceRx   (    (    s4   lib/python2.7/site-packages/sklearn/utils/extmath.pyt   _incremental_mean_and_varÌ  s(    1
*-
	


c         C   se   t  j t  j |  ƒ d d ƒ} t  j |  t |  j d ƒ | f ƒ } |  | d d … t  j f 9}  |  S(   s  Modify the sign of vectors for reproducibility

    Flips the sign of elements of all the vectors (rows of u) such that
    the absolute maximum element of each vector is positive.

    Parameters
    ----------
    u : ndarray
        Array with vectors as its rows.

    Returns
    -------
    u_flipped : ndarray with same shape as u
        Array with the sign flipped vectors as its rows.
    Rs   i   i    N(   R   R”   R•   R%   RN   R8   R–   (   R—   R›   Rš   (    (    s4   lib/python2.7/site-packages/sklearn/utils/extmath.pyt   _deterministic_vector_sign_flip  s    &gñhãˆµøä>g:Œ0âŽyE>c      
   C   s·   t  d
 k  r( t j |  d | d t j ƒSt j |  d | d t j ƒ} t j |  d | d t j ƒ} t j t j | j d d | ƒ| d | d | d t ƒƒ s³ t	 j
 d	 t ƒ n  | S(   sÉ  Use high precision for cumsum and check that final value matches sum

    Parameters
    ----------
    arr : array-like
        To be cumulatively summed as flat
    axis : int, optional
        Axis along which the cumulative sum is computed.
        The default (None) is to compute the cumsum over the flattened array.
    rtol : float
        Relative tolerance, see ``np.allclose``
    atol : float
        Absolute tolerance, see ``np.allclose``
    i   i	   Rs   R   iÿÿÿÿt   rtolt   atolt	   equal_nansL   cumsum was found to be unstable: its last element does not correspond to sum(   i   i	   (   R   R   t   cumsumRž   R:   t   allt   iscloset   takeR.   R   R   t   RuntimeWarning(   Rr   Rs   RÇ   RÈ   R2   t   expected(    (    s4   lib/python2.7/site-packages/sklearn/utils/extmath.pyt   stable_cumsum4  s    *	
(0   t   __doc__t
   __future__R    R   t   numpyR   t   scipyR   R   t    R   R   t   fixesR   R   Rq   t   _logistic_sigmoidR   t   externals.six.movesR   t   sparsefuncs_fastR	   t
   validationR
   R   R   R-   R!   R'   R/   R9   R3   R?   RB   RW   R.   Rp   R…   R†   R“   Rb   R¡   R¦   Rª   R®   RÅ   RÆ   RÐ   (    (    (    s4   lib/python2.7/site-packages/sklearn/utils/extmath.pyt   <module>   sN   	 		
		S€	I	1,-"		R	