3
[ht                 @   s6  d Z ddlZddl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 Zd8ddZdd Zdd ZeddddZedddddZedddddddddZeddd d!Zd9d"d#Zd:d$d%Zd;d&d'Zd<d(d)Zd=d*d+Zd,d- Zd.d/ Zd0d1 Zd2d3 Z d>d6d7Z!dS )?z
Extended math utilities.
    N)linalgsparse   )check_random_state)_log_logistic_sigmoid)csr_row_norms)check_array)_deprecate_positional_argsc             C   s6   t j| dd} t j| jt jr*tjdt t j| | S )a  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).
    K)orderzYArray type is integer, np.dot may overflow. Data should be float type to avoid this issue)	npravel
issubdtypedtypeintegerwarningswarnUserWarningdot)x r   =/tmp/pip-build-zwgx3nbq/scikit-learn/sklearn/utils/extmath.pysquared_norm   s
    r   Fc             C   sL   t j| r*t| t js t j| } t| }ntjd| | }|sHtj|| |S )a  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, default=False
        If True, return squared norms.

    Returns
    -------
    array-like
        The row-wise (squared) Euclidean norm of X.
    zij,ij->i)r   issparse
isinstanceZ
csr_matrixr   r   Zeinsumsqrt)XZsquaredZnormsr   r   r   	row_norms1   s    


r   c             C   s$   t jj| \}}|dks t j S |S )zCompute 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.
    r   )r   r   Zslogdetinf)Asignldr   r   r   fast_logdetQ   s    r"   c             K   sP   t | dr*t| j| jd | jd   }n"| dkr6dnt| dkj | j }|S )zCompute density of a sparse vector.

    Parameters
    ----------
    w : array-like
        The sparse vector.

    Returns
    -------
    float
        The density of w, between 0 and 1.
    toarrayr   r   N)hasattrfloatZnnzshapesumsize)wkwargsdr   r   r   densityb   s    
 "r,   )dense_outputc            C   s   | j dks|j dkrtj| rhtj|d}|j|jd df}| | }|j| jd f|jdd  }qtj|r| jd	| jd
 }|| }|j| jdd |jd f }qtj| |}n| | }tj| rtj|r|rt|dr|j	 S |S )a  Dot product that handle the sparse matrix case correctly.

    Parameters
    ----------
    a : {ndarray, sparse matrix}
    b : {ndarray, sparse matrix}
    dense_output : bool, default=False
        When False, ``a`` and ``b`` both being sparse will yield sparse output.
        When True, output will always be a dense array.

    Returns
    -------
    dot_product : {ndarray, sparse matrix}
        Sparse if ``a`` and ``b`` are sparse and ``dense_output=False``.
       r   r   Nr#   r/   r0   r0   r0   )
ndimr   r   r   Zrollaxisreshaper&   r   r$   r#   )abr-   Zb_Zb_2dretZa_2dr   r   r   safe_sparse_dotv   s     
"
"r6   auto)power_iteration_normalizerrandom_statec            C   s  t |}|j| jd |fd}| jjdkr:|j| jdd}|dkrT|dkrPd}nd	}xt|D ]}|dkrt| |}t| j|}q^|d	krt	j
t| |d
d\}}t	j
t| j|d
d\}}q^|dkr^t	jt| |dd\}}t	jt| j|dd\}}q^W t	jt| |dd\}}|S )a  Computes an orthonormal matrix whose range approximates the range of A.

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

    size : int
        Size of the return array.

    n_iter : int
        Number of power iterations used to stabilize the result.

    power_iteration_normalizer : {'auto', 'QR', 'LU', 'none'}, default='auto'
        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, default=None
        The seed of the pseudo random number generator to use when shuffling
        the data, i.e. getting the random vectors to initialize the algorithm.
        Pass an int for reproducible results across multiple function calls.
        See :term:`Glossary <random_state>`.

    Returns
    -------
    Q : ndarray
        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   )r(   fF)copyr7   r.   noneZLUT)Z	permute_lZQRZeconomic)mode)r   Znormalr&   r   kindastyperanger6   Tr   ZluZqr)r   r(   n_iterr8   r9   Qi_r   r   r   randomized_range_finder   s(    3
rF   
   T)n_oversamplesrB   r8   	transpose	flip_signr9   c            C   s^  t | tjtjfr,tjdjt| jtj	 t
|}|| }| j\}	}
|dkrh|dt| j k rddnd}|dkrx|	|
k }|r| j} t| ||||d}t|j| }tj|dd\}}}~tj||}|r|st||\}}nt||dd	\}}|r(|d
|d
d
f j|d
| |d
d
d
|f jfS |d
d
d
|f |d
| |d
|d
d
f fS d
S )aV  Computes a truncated randomized SVD.

    Parameters
    ----------
    M : {ndarray, sparse matrix}
        Matrix to decompose.

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

    n_oversamples : int, default=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='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', 'QR', 'LU', 'none'}, default='auto'
        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 : bool or 'auto', default='auto'
        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 : bool, default=True
        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, default=0
        The seed of the pseudo random number generator to use when shuffling
        the data, i.e. getting the random vectors to initialize the algorithm.
        Pass an int for reproducible results across multiple function calls.
        See :term:`Glossary <random_state>`.

    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
    zCCalculating SVD of a {} is expensive. csr_matrix is more efficient.r7   g?      )r(   rB   r8   r9   F)Zfull_matrices)u_based_decisionN)r   r   Z
lil_matrixZ
dok_matrixr   r   formattype__name__ZSparseEfficiencyWarningr   r&   minrA   rF   r6   r   Zsvdr   r   svd_flip)MZn_componentsrH   rB   r8   rI   rJ   r9   Zn_random	n_samples
n_featuresrC   BZUhatsZVtUr   r   r   randomized_svd   s8    R

6rY   )axisc            C   s   |dkr"t j| } t j|}d}nt j| } t j|}| j|jkrVt j| j||jd}t jt j| }t| j}d||< t j|}t j|}xb|D ]Z}t j| j}| |k}	||	 ||	< t j	t j
|||}
t j|
|k||}t j|
|}|}qW ||fS )a  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, default=0
        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.5.

    See Also
    --------
    scipy.stats.mode
    Nr   )r   r   )r   r   asarrayr&   fullr   uniquelistzerosZexpand_dimsr'   wheremaximum)r3   r)   rZ   ZscoresZ	testshapeZoldmostfreqZ	oldcountsZscoretemplateindcountsZmostfrequentr   r   r   weighted_modey  s,    /







re   c             C   s   dd | D } dd | D }| d j }tj|}|jt| d	j}|dkrXtj||d}x8t| D ],\}}| | |dd|f  |dd|f< qbW |S )
ak  Generate a cartesian product of input arrays.

    Parameters
    ----------
    arrays : list of array-like
        1-D arrays to form the cartesian product of.
    out : ndarray, default=None
        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]])

    Notes
    -----
    This function may not be used on more than 32 arrays
    because the underlying numpy functions do not support it.
    c             S   s   g | ]}t j|qS r   )r   r[   ).0r   r   r   r   
<listcomp>  s    zcartesian.<locals>.<listcomp>c             s   s   | ]}t |V  qd S )N)len)rf   r   r   r   r   	<genexpr>  s    zcartesian.<locals>.<genexpr>r   r   N)r   r0   )r   r   indicesr2   rh   rA   
empty_like	enumerate)Zarraysoutr&   r   ixnarrr   r   r   	cartesian  s    %

(rq   c             C   s   |rTt jt j| dd}t j| |t| jd f }| |9 } ||ddt jf 9 }nNt jt j|dd}t j|t|jd |f }| |9 } ||ddt jf 9 }| |fS )a:  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
        :func:`~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
        :func:`~sklearn.utils.extmath.randomized_svd`, with matching inner
        dimensions so one can compute `np.dot(u * s, v)`.
        The input v should really be called vt to be consistent with scipy's
        ouput.

    u_based_decision : bool, 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.

    r   )rZ   r   N)r   argmaxabsr    r@   r&   newaxis)uvrM   Zmax_abs_colssignsmax_abs_rowsr   r   r   rR     s    rR   c             C   s^   | j dk}tj| } t| tjd} | j\}}|dkr>tj| }t||| | |rZtj|S |S )aB  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 of shape (M, N) or (M,)
        Argument to the logistic function.

    out : array-like of shape (M, N) or (M,), default=None
        Preallocated output array.

    Returns
    -------
    out : ndarray of 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/
    r   )r   N)	r1   r   Z
atleast_2dr   float64r&   rk   r   Zsqueeze)r   rm   Zis_1drT   rU   r   r   r   log_logistic&  s    




rz   c             C   sV   |rt j| } t j| ddjd}| |8 } t j| |  t j| ddjd}| | } | S )a@  
    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 float of shape (M, N)
        Argument to the logistic function.

    copy : bool, default=True
        Copy X or not.

    Returns
    -------
    out : ndarray of shape (M, N)
        Softmax function evaluated at every point in x.
    r   )rZ   r0   )r0   r   r0   )r0   r   )r   r;   maxr2   expr'   )r   r;   Zmax_probZsum_probr   r   r   softmaxS  s    
r}   c             C   s2   | j  }||k r.tj| r"td| ||  } | S )aE  Ensure `X.min()` >= `min_value`.

    Parameters
    ----------
    X : array-like
        The matrix to make non-negative.
    min_value : float, default=0
        The threshold value.

    Returns
    -------
    array-like
        The thresholded array.

    Raises
    ------
    ValueError
        When X is sparse.
    z{Cannot make the data matrix nonnegative because it is sparse. Adding a value to every entry would make it no longer sparse.)rQ   r   r   
ValueError)r   Z	min_valueZmin_r   r   r   make_nonnegativeu  s    
r   c             O   sL   t j|jt jr8|jjdk r8| |f||dt ji}n| |f||}|S )a  
    This function provides numpy accumulator functions with a float64 dtype
    when used on a floating point input. This prevents accumulator overflow on
    smaller floating point dtypes.

    Parameters
    ----------
    op : function
        A numpy accumulator function such as np.mean or np.sum.
    x : ndarray
        A numpy array to apply the accumulator function.
    *args : positional arguments
        Positional arguments passed to the accumulator function after the
        input x.
    **kwargs : keyword arguments
        Keyword arguments passed to the accumulator function.

    Returns
    -------
    result
        The output of the accumulator function passed to this function.
       r   )r   r   r   Zfloatingitemsizery   )opr   argsr*   resultr   r   r   _safe_accumulator_op  s    r   c             C   s$  |dkrt | |||S tj| }tj|d}tj|| j jtj}ttj	|dd}tj
|d| }	tj|	|ddjtj}
|
|| 9 }
|| }|| ||
  | }|dkrd}nhtj
|d| |
 d }	ttj|	|dd}||| 9 }|||
| d   }|||| d   }|| | }|||fS )	a  Calculate weighted mean and weighted variance incremental update.

    .. versionadded:: 0.24

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

    sample_weight : array-like of shape (n_samples,) or None
        Sample weights. If None, then samples are equally weighted.

    last_mean : array-like of shape (n_features,)
        Mean before the incremental update.

    last_variance : array-like of shape (n_features,) or None
        Variance before the incremental update.
        If None, variance update is not computed (in case scaling is not
        required).

    last_weight_sum : array-like of shape (n_features,)
        Sum of weights before the incremental update.

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

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

    updated_weight_sum : array of shape (n_features,)

    Notes
    -----
    NaNs in `X` are ignored.

    `last_mean` and `last_variance` are statistics computed at the last step
    by the function. Both must be initialized to 0.0.
    The mean is always required (`last_mean`) and returned (`updated_mean`),
    whereas the variance can be None (`last_variance` and `updated_variance`).

    For further details on the algorithm to perform the computation in a
    numerically stable way, see [Finch2009]_, Sections 4 and 5.

    References
    ----------
    .. [Finch2009] `Tony Finch,
       "Incremental calculation of weighted mean and variance",
       University of Cambridge Computing Service, February 2009.
       <https://fanf2.user.srcf.net/hermes/doc/antiforgery/stats.pdf>`_

    Nr   r   )rZ   )weightsrZ   r.   r0   )r   r0   )_incremental_mean_and_varr   isnanr2   r   r   r?   ry   r   r'   r`   Zaverage)r   Zsample_weight	last_meanlast_varianceZlast_weight_sumZnan_maskZsample_weight_TZnew_weight_sumZtotal_weight_sumZX_0Znew_meanZupdated_weight_sumupdated_meanupdated_varianceZnew_varianceZnew_termZ	last_termr   r   r   "_incremental_weighted_mean_and_var  s:    ;
r   c             C   s   || }t tj| dd}tjtj|  dd}|| }|| | }|dkrPd}	nzt tj| dd| }
|| }tjddd. || }||
 || || | d   }W dQ R X |dk}|
| ||< || }	||	|fS )a  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 of shape (n_samples, n_features)
        Data to use for variance update.

    last_mean : array-like of shape (n_features,)

    last_variance : array-like of shape (n_features,)

    last_sample_count : array-like of shape (n_features,)

    Returns
    -------
    updated_mean : ndarray of shape (n_features,)

    updated_variance : ndarray of shape (n_features,)
        If None, only mean is computed.

    updated_sample_count : ndarray of 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`
    r   )rZ   Nignore)divideinvalidr.   )r   r   Znansumr'   r   ZnanvarZerrstate)r   r   r   Zlast_sample_countZlast_sumZnew_sumZnew_sample_countZupdated_sample_countr   r   Znew_unnormalized_varianceZlast_unnormalized_varianceZlast_over_new_countZupdated_unnormalized_variancer_   r   r   r   r     s$    1r   c             C   sJ   t jt j| dd}t j| t| jd |f }| |ddt jf 9 } | S )a  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.
    r   )rZ   r   N)r   rr   rs   r    r@   r&   rt   )ru   rx   rw   r   r   r   _deterministic_vector_sign_flipf  s    r   h㈵>:0yE>c             C   sX   t j| |t jd}t j| |t jd}t jt j|jd|d|||ddsTtjdt	 |S )a  Use high precision for cumsum and check that final value matches sum.

    Parameters
    ----------
    arr : array-like
        To be cumulatively summed as flat.
    axis : int, default=None
        Axis along which the cumulative sum is computed.
        The default (None) is to compute the cumsum over the flattened array.
    rtol : float, default=1e-05
        Relative tolerance, see ``np.allclose``.
    atol : float, default=1e-08
        Absolute tolerance, see ``np.allclose``.
    )rZ   r   r   )rZ   T)rtolatolZ	equal_nanzLcumsum was found to be unstable: its last element does not correspond to sumr0   )
r   Zcumsumry   r'   alliscloseZtaker   r   RuntimeWarning)rp   rZ   r   r   rm   expectedr   r   r   stable_cumsum|  s    r   )F)N)T)N)T)r   )Nr   r   )"__doc__r   Znumpyr   Zscipyr   r    r   Z_logistic_sigmoidr   Zsparsefuncs_fastr   Z
validationr   r	   r   r   r"   r,   r6   rF   rY   re   rq   rR   rz   r}   r   r   r   r   r   r   r   r   r   r   <module>   sD   
 )R I
5
.
-
"
"cN