B
    ud!]                 @   s   d Z ddlZddlmZm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d
lmZ dddgZddddZdd Zdd ZdddZd ddZG dd deeedZG dd deZG dd deZdS )!aR  Random Projection transformers.

Random Projections are a simple and computationally efficient way to
reduce the dimensionality of the data by trading a controlled amount
of accuracy (as additional variance) for faster processing times and
smaller model sizes.

The dimensions and distribution of Random Projections matrices are
controlled so as to preserve the pairwise distances between any two
samples of the dataset.

The main theoretical result behind the efficiency of random projection is the
`Johnson-Lindenstrauss lemma (quoting Wikipedia)
<https://en.wikipedia.org/wiki/Johnson%E2%80%93Lindenstrauss_lemma>`_:

  In mathematics, the Johnson-Lindenstrauss lemma is a result
  concerning low-distortion embeddings of points from high-dimensional
  into low-dimensional Euclidean space. The lemma states that a small set
  of points in a high-dimensional space can be embedded into a space of
  much lower dimension in such a way that distances between the points are
  nearly preserved. The map used for the embedding is at least Lipschitz,
  and can even be taken to be an orthogonal projection.

    N)ABCMetaabstractmethod   )BaseEstimatorTransformerMixin)check_random_state)safe_sparse_dot)sample_without_replacement)check_is_fitted)DataDimensionalityWarningSparseRandomProjectionGaussianRandomProjectionjohnson_lindenstrauss_min_dimg?)epsc            C   s   t |}t | } t |dks0t |dkr<td| t | dkrVtd|  |d d |d d  }dt |  | t jS )	a	  Find a 'safe' number of components to randomly project to.

    The distortion introduced by a random projection `p` only changes the
    distance between two points by a factor (1 +- eps) in an euclidean space
    with good probability. The projection `p` is an eps-embedding as defined
    by:

      (1 - eps) ||u - v||^2 < ||p(u) - p(v)||^2 < (1 + eps) ||u - v||^2

    Where u and v are any rows taken from a dataset of shape (n_samples,
    n_features), eps is in ]0, 1[ and p is a projection by a random Gaussian
    N(0, 1) matrix of shape (n_components, n_features) (or a sparse
    Achlioptas matrix).

    The minimum number of components to guarantee the eps-embedding is
    given by:

      n_components >= 4 log(n_samples) / (eps^2 / 2 - eps^3 / 3)

    Note that the number of dimensions is independent of the original
    number of features but instead depends on the size of the dataset:
    the larger the dataset, the higher is the minimal dimensionality of
    an eps-embedding.

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

    Parameters
    ----------
    n_samples : int or array-like of int
        Number of samples that should be a integer greater than 0. If an array
        is given, it will compute a safe number of components array-wise.

    eps : float or ndarray of shape (n_components,), dtype=float,             default=0.1
        Maximum distortion rate in the range (0,1 ) as defined by the
        Johnson-Lindenstrauss lemma. If an array is given, it will compute a
        safe number of components array-wise.

    Returns
    -------
    n_components : int or ndarray of int
        The minimal number of components to guarantee with good probability
        an eps-embedding with n_samples.

    Examples
    --------
    >>> from sklearn.random_projection import johnson_lindenstrauss_min_dim
    >>> johnson_lindenstrauss_min_dim(1e6, eps=0.5)
    663

    >>> johnson_lindenstrauss_min_dim(1e6, eps=[0.5, 0.1, 0.01])
    array([    663,   11841, 1112658])

    >>> johnson_lindenstrauss_min_dim([1e4, 1e5, 1e6], eps=0.1)
    array([ 7894,  9868, 11841])

    References
    ----------

    .. [1] https://en.wikipedia.org/wiki/Johnson%E2%80%93Lindenstrauss_lemma

    .. [2] Sanjoy Dasgupta and Anupam Gupta, 1999,
           "An elementary proof of the Johnson-Lindenstrauss Lemma."
           http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.45.3654

    g        r   z1The JL bound is defined for eps in ]0, 1[, got %rr   z?The JL bound is defined for n_samples greater than zero, got %r         )npZasarrayany
ValueErrorlogZastypeZint64)	n_samplesr   denominator r   f/work/yifan.wang/ringdown/master-ringdown-env/lib/python3.7/site-packages/sklearn/random_projection.pyr   4   s    C

c             C   s8   | dkrdt | } n| dks(| dkr4td|  | S )z.Factorize density check according to Li et al.autor   r   z)Expected density in range ]0, 1], got: %r)r   sqrtr   )density
n_featuresr   r   r   _check_density   s
    r   c             C   s,   | dkrt d|  |dkr(t d| dS )z9Factorize argument checking for random matrix generation.r   z.n_components must be strictly positive, got %dz,n_features must be strictly positive, got %dN)r   )n_componentsr   r   r   r   _check_input_size   s
    
r!   c             C   s4   t | | t|}|jddt|  | |fd}|S )ab  Generate a dense Gaussian random matrix.

    The components of the random matrix are drawn from

        N(0, 1.0 / n_components).

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

    Parameters
    ----------
    n_components : int,
        Dimensionality of the target projection space.

    n_features : int,
        Dimensionality of the original source space.

    random_state : int, RandomState instance or None, default=None
        Controls the pseudo random number generator used to generate the matrix
        at fit time.
        Pass an int for reproducible output across multiple function calls.
        See :term:`Glossary <random_state>`.

    Returns
    -------
    components : ndarray of shape (n_components, n_features)
        The generated Gaussian random matrix.

    See Also
    --------
    GaussianRandomProjection
    g        g      ?)locscalesize)r!   r   normalr   r   )r    r   random_staterng
componentsr   r   r   _gaussian_random_matrix   s
     
r)   r   c             C   s  t | | t||}t|}|dkrP|dd| |fd d }dt|  | S g }d}|g}xFt| D ]:}	|||}
t||
|d}|| ||
7 }|| qhW t	|}|jddt
|dd d }tj|||f| |fd}td| t|  | S dS )	a  Generalized Achlioptas random sparse matrix for random projection.

    Setting density to 1 / 3 will yield the original matrix by Dimitris
    Achlioptas while setting a lower value will yield the generalization
    by Ping Li et al.

    If we note :math:`s = 1 / density`, the components of the random matrix are
    drawn from:

      - -sqrt(s) / sqrt(n_components)   with probability 1 / 2s
      -  0                              with probability 1 - 1 / s
      - +sqrt(s) / sqrt(n_components)   with probability 1 / 2s

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

    Parameters
    ----------
    n_components : int,
        Dimensionality of the target projection space.

    n_features : int,
        Dimensionality of the original source space.

    density : float or 'auto', default='auto'
        Ratio of non-zero component in the random projection matrix in the
        range `(0, 1]`

        If density = 'auto', the value is set to the minimum density
        as recommended by Ping Li et al.: 1 / sqrt(n_features).

        Use density = 1 / 3.0 if you want to reproduce the results from
        Achlioptas, 2001.

    random_state : int, RandomState instance or None, default=None
        Controls the pseudo random number generator used to generate the matrix
        at fit time.
        Pass an int for reproducible output across multiple function calls.
        See :term:`Glossary <random_state>`.

    Returns
    -------
    components : {ndarray, sparse matrix} of shape (n_components, n_features)
        The generated Gaussian random matrix. Sparse matrix will be of CSR
        format.

    See Also
    --------
    SparseRandomProjection

    References
    ----------

    .. [1] Ping Li, T. Hastie and K. W. Church, 2006,
           "Very Sparse Random Projections".
           https://web.stanford.edu/~hastie/Papers/Ping/KDD06_rp.pdf

    .. [2] D. Achlioptas, 2001, "Database-friendly random projections",
           http://www.cs.ucsc.edu/~optas/papers/jl.pdf

    r   g      ?r   r   )r&   )r$   )shapeN)r!   r   r   Zbinomialr   r   ranger	   appendZconcatenater$   spZ
csr_matrix)r    r   r   r&   r'   r(   indicesoffsetZindptr_Zn_nonzero_iZ	indices_idatar   r   r   _sparse_random_matrix   s*    =



r2   c               @   sF   e Zd ZdZedddddddZed	d
 ZdddZdd ZdS )BaseRandomProjectionz~Base class for random projections.

    Warning: This class should not be used directly.
    Use derived classes instead.
    r   g?FN)r   dense_outputr&   c            C   s   || _ || _|| _|| _d S )N)r    r   r4   r&   )selfr    r   r4   r&   r   r   r   __init__,  s    zBaseRandomProjection.__init__c             C   s   dS )a  Generate the random projection matrix.

        Parameters
        ----------
        n_components : int,
            Dimensionality of the target projection space.

        n_features : int,
            Dimensionality of the original source space.

        Returns
        -------
        components : {ndarray, sparse matrix} of shape                 (n_components, n_features)
            The generated random matrix. Sparse matrix will be of CSR format.

        Nr   )r5   r    r   r   r   r   _make_random_matrix5  s    z(BaseRandomProjection._make_random_matrixc             C   s   | j |ddgd}|j\}}| jdkr|t|| jd| _| jdkrXtd| j|| jf q| j|krtd| j|| j|f nB| jdkrtd	| j n | j|krtd
|| jf t	 | j| _| 
| j|| _| jj| j|fkstd| S )a  Generate a sparse random projection matrix.

        Parameters
        ----------
        X : {ndarray, sparse matrix} of shape (n_samples, n_features)
            Training set: only the shape is used to find optimal random
            matrix dimensions based on the theory referenced in the
            afore mentioned papers.

        y : Ignored
            Not used, present here for API consistency by convention.

        Returns
        -------
        self : object
            BaseRandomProjection class instance.
        csrcsc)accept_sparser   )r   r   r   zIeps=%f and n_samples=%d lead to a target dimension of %d which is invalidzseps=%f and n_samples=%d lead to a target dimension of %d which is larger than the original space with n_features=%dz+n_components must be greater than 0, got %szThe number of components is higher than the number of features: n_features < n_components (%s < %s).The dimensionality of the problem will not be reduced.zLAn error has occurred the self.components_ matrix has  not the proper shape.)_validate_datar*   r    r   r   Zn_components_r   warningswarnr   r7   components_AssertionError)r5   Xyr   r   r   r   r   fitI  s4    






zBaseRandomProjection.fitc             C   sh   t |  | j|ddgdd}|jd | jjd krPtd|jd | jjd f t|| jj| jd}|S )a  Project the data by using matrix product with the random matrix.

        Parameters
        ----------
        X : {ndarray, sparse matrix} of shape (n_samples, n_features)
            The input data to project into a smaller dimensional space.

        Returns
        -------
        X_new : {ndarray, sparse matrix} of shape (n_samples, n_components)
            Projected array.
        r8   r9   F)r:   resetr   z^Impossible to perform projection:X at fit stage had a different number of features. (%s != %s))r4   )r
   r;   r*   r>   r   r   Tr4   )r5   r@   ZX_newr   r   r   	transform  s    zBaseRandomProjection.transform)r   )N)	__name__
__module____qualname____doc__r   r6   r7   rB   rE   r   r   r   r   r3   %  s   
Dr3   )	metaclassc                   s2   e Zd ZdZd
ddd fddZdd	 Z  ZS )r   a	  Reduce dimensionality through Gaussian random projection.

    The components of the random matrix are drawn from N(0, 1 / n_components).

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

    .. versionadded:: 0.13

    Parameters
    ----------
    n_components : int or 'auto', default='auto'
        Dimensionality of the target projection space.

        n_components can be automatically adjusted according to the
        number of samples in the dataset and the bound given by the
        Johnson-Lindenstrauss lemma. In that case the quality of the
        embedding is controlled by the ``eps`` parameter.

        It should be noted that Johnson-Lindenstrauss lemma can yield
        very conservative estimated of the required number of components
        as it makes no assumption on the structure of the dataset.

    eps : float, default=0.1
        Parameter to control the quality of the embedding according to
        the Johnson-Lindenstrauss lemma when `n_components` is set to
        'auto'. The value should be strictly positive.

        Smaller values lead to better embedding and higher number of
        dimensions (n_components) in the target projection space.

    random_state : int, RandomState instance or None, default=None
        Controls the pseudo random number generator used to generate the
        projection matrix at fit time.
        Pass an int for reproducible output across multiple function calls.
        See :term:`Glossary <random_state>`.

    Attributes
    ----------
    n_components_ : int
        Concrete number of components computed when n_components="auto".

    components_ : ndarray of shape (n_components, n_features)
        Random matrix used for the projection.

    n_features_in_ : int
        Number of features seen during :term:`fit`.

        .. versionadded:: 0.24

    feature_names_in_ : ndarray of shape (`n_features_in_`,)
        Names of features seen during :term:`fit`. Defined only when `X`
        has feature names that are all strings.

        .. versionadded:: 1.0

    See Also
    --------
    SparseRandomProjection : Reduce dimensionality through sparse
        random projection.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.random_projection import GaussianRandomProjection
    >>> rng = np.random.RandomState(42)
    >>> X = rng.rand(25, 3000)
    >>> transformer = GaussianRandomProjection(random_state=rng)
    >>> X_new = transformer.fit_transform(X)
    >>> X_new.shape
    (25, 2759)
    r   g?N)r   r&   c               s   t  j||d|d d S )NT)r    r   r4   r&   )superr6   )r5   r    r   r&   )	__class__r   r   r6     s
    z!GaussianRandomProjection.__init__c             C   s   t | j}t|||dS )a   Generate the random projection matrix.

        Parameters
        ----------
        n_components : int,
            Dimensionality of the target projection space.

        n_features : int,
            Dimensionality of the original source space.

        Returns
        -------
        components : {ndarray, sparse matrix} of shape                 (n_components, n_features)
            The generated random matrix. Sparse matrix will be of CSR format.

        )r&   )r   r&   r)   )r5   r    r   r&   r   r   r   r7     s    
z,GaussianRandomProjection._make_random_matrix)r   )rF   rG   rH   rI   r6   r7   __classcell__r   r   )rL   r   r     s   Gc                   s6   e Zd ZdZdddddd fddZd	d
 Z  ZS )r   ae  Reduce dimensionality through sparse random projection.

    Sparse random matrix is an alternative to dense random
    projection matrix that guarantees similar embedding quality while being
    much more memory efficient and allowing faster computation of the
    projected data.

    If we note `s = 1 / density` the components of the random matrix are
    drawn from:

      - -sqrt(s) / sqrt(n_components)   with probability 1 / 2s
      -  0                              with probability 1 - 1 / s
      - +sqrt(s) / sqrt(n_components)   with probability 1 / 2s

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

    .. versionadded:: 0.13

    Parameters
    ----------
    n_components : int or 'auto', default='auto'
        Dimensionality of the target projection space.

        n_components can be automatically adjusted according to the
        number of samples in the dataset and the bound given by the
        Johnson-Lindenstrauss lemma. In that case the quality of the
        embedding is controlled by the ``eps`` parameter.

        It should be noted that Johnson-Lindenstrauss lemma can yield
        very conservative estimated of the required number of components
        as it makes no assumption on the structure of the dataset.

    density : float or 'auto', default='auto'
        Ratio in the range (0, 1] of non-zero component in the random
        projection matrix.

        If density = 'auto', the value is set to the minimum density
        as recommended by Ping Li et al.: 1 / sqrt(n_features).

        Use density = 1 / 3.0 if you want to reproduce the results from
        Achlioptas, 2001.

    eps : float, default=0.1
        Parameter to control the quality of the embedding according to
        the Johnson-Lindenstrauss lemma when n_components is set to
        'auto'. This value should be strictly positive.

        Smaller values lead to better embedding and higher number of
        dimensions (n_components) in the target projection space.

    dense_output : bool, default=False
        If True, ensure that the output of the random projection is a
        dense numpy array even if the input and random projection matrix
        are both sparse. In practice, if the number of components is
        small the number of zero components in the projected data will
        be very small and it will be more CPU and memory efficient to
        use a dense representation.

        If False, the projected data uses a sparse representation if
        the input is sparse.

    random_state : int, RandomState instance or None, default=None
        Controls the pseudo random number generator used to generate the
        projection matrix at fit time.
        Pass an int for reproducible output across multiple function calls.
        See :term:`Glossary <random_state>`.

    Attributes
    ----------
    n_components_ : int
        Concrete number of components computed when n_components="auto".

    components_ : sparse matrix of shape (n_components, n_features)
        Random matrix used for the projection. Sparse matrix will be of CSR
        format.

    density_ : float in range 0.0 - 1.0
        Concrete density computed from when density = "auto".

    n_features_in_ : int
        Number of features seen during :term:`fit`.

        .. versionadded:: 0.24

    feature_names_in_ : ndarray of shape (`n_features_in_`,)
        Names of features seen during :term:`fit`. Defined only when `X`
        has feature names that are all strings.

        .. versionadded:: 1.0

    See Also
    --------
    GaussianRandomProjection : Reduce dimensionality through Gaussian
        random projection.

    References
    ----------

    .. [1] Ping Li, T. Hastie and K. W. Church, 2006,
           "Very Sparse Random Projections".
           https://web.stanford.edu/~hastie/Papers/Ping/KDD06_rp.pdf

    .. [2] D. Achlioptas, 2001, "Database-friendly random projections",
           https://users.soe.ucsc.edu/~optas/papers/jl.pdf

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.random_projection import SparseRandomProjection
    >>> rng = np.random.RandomState(42)
    >>> X = rng.rand(25, 3000)
    >>> transformer = SparseRandomProjection(random_state=rng)
    >>> X_new = transformer.fit_transform(X)
    >>> X_new.shape
    (25, 2759)
    >>> # very few components are non-zero
    >>> np.mean(transformer.components_ != 0)
    0.0182...
    r   g?FN)r   r   r4   r&   c               s   t  j||||d || _d S )N)r    r   r4   r&   )rK   r6   r   )r5   r    r   r   r4   r&   )rL   r   r   r6     s    	zSparseRandomProjection.__init__c             C   s*   t | j}t| j|| _t||| j|dS )a   Generate the random projection matrix

        Parameters
        ----------
        n_components : int
            Dimensionality of the target projection space.

        n_features : int
            Dimensionality of the original source space.

        Returns
        -------
        components : {ndarray, sparse matrix} of shape                 (n_components, n_features)
            The generated random matrix. Sparse matrix will be of CSR format.

        )r   r&   )r   r&   r   r   Zdensity_r2   )r5   r    r   r&   r   r   r   r7     s    
z*SparseRandomProjection._make_random_matrix)r   )rF   rG   rH   rI   r6   r7   rM   r   r   )rL   r   r     s   w)N)r   N) rI   r<   abcr   r   numpyr   Zscipy.sparsesparser-   baser   r   utilsr   Zutils.extmathr   Zutils.randomr	   Zutils.validationr
   
exceptionsr   __all__r   r   r!   r)   r2   r3   r   r   r   r   r   r   <module>   s,   S


(
b i