B
    (by                 @   s  d Z ddlZddlmZmZ ddlZddlmZm	Z	 ddl
mZ ddlmZmZmZ ddlmZmZ dd	lmZ dd
lmZmZ ddlmZ dddgZdddZdd Zd ddZG dd deeeeeZG dd deZ G dd deZ!G dd deeZ"dS )!zG
The :mod:`sklearn.pls` module implements Partial Least Squares (PLS).
    N)ABCMetaabstractmethod)pinv2svd)svds   )BaseEstimatorRegressorMixinTransformerMixin)check_arraycheck_consistent_length)svd_flip)check_is_fittedFLOAT_DTYPES)sixPLSCanonicalPLSRegressionPLSSVDA  ư>Fc             C   s  |dddgf }d}d}d }	}
t | jj}xb|dkr^|	dkrPt| dd}	t |	|}nt | j|t |j| }t |j||k r||7 }|t t |j||  }t | |}|dkr|
dkrt|dd}
t |
|}nt |j|t |j| }|r$|t t |j||  }t ||t |j||  }|| }t |j||k sn|jd dkrpP ||krt	
d P |}|d7 }q4W |||fS )a0  Inner loop of the iterative NIPALS algorithm.

    Provides an alternative to the svd(X'Y); returns the first left and right
    singular vectors of X'Y.  See PLS for the meaning of the parameters.  It is
    similar to the Power method for determining the eigenvectors and
    eigenvalues of a X'Y.
    Nr      BF)check_finitez$Maximum number of iterations reached)npfinfodtypeepsr   dotTsqrtshapewarningswarn)XYmodemax_itertolnorm_y_weightsZy_scoreZx_weights_oldZiteZX_pinvZY_pinvr   	x_weightsZx_score	y_weightsZx_weights_diff r,   O/home/dcms/DCMS/lib/python3.7/site-packages/sklearn/cross_decomposition/pls_.py_nipals_twoblocks_inner_loop   s@    	$

r.   c             C   sN   t | j|}t|dd\}}}|d d dgf }|jd d dgf }||fS )NF)full_matricesr   )r   r   r   r   )r$   r%   CUsZVhuvr,   r,   r-   _svd_cross_productT   s
    r5   Tc             C   s   | j dd}| |8 } |j dd}||8 }|rr| jddd}d||dk< | | } |jddd}d||dk< || }n t| jd }t|jd }| |||||fS )z| Center X, Y and scale if the scale parameter==True

    Returns
    -------
        X, Y, x_mean, y_mean, x_std, y_std
    r   )axisr   )r6   Zddofg      ?g        )ZmeanZstdr   onesr!   )r$   r%   scaleZx_meanZy_meanZx_stdZy_stdr,   r,   r-   _center_scale_xy\   s    
r9   c            
   @   sD   e Zd ZdZedd
dZdd ZdddZdddZdddZ	dS )_PLSa  Partial Least Squares (PLS)

    This class implements the generic PLS algorithm, constructors' parameters
    allow to obtain a specific implementation such as:

    - PLS2 regression, i.e., PLS 2 blocks, mode A, with asymmetric deflation
      and unnormalized y weights such as defined by [Tenenhaus 1998] p. 132.
      With univariate response it implements PLS1.

    - PLS canonical, i.e., PLS 2 blocks, mode A, with symmetric deflation and
      normalized y weights such as defined by [Tenenhaus 1998] (p. 132) and
      [Wegelin et al. 2000]. This parametrization implements the original Wold
      algorithm.

    We use the terminology defined by [Wegelin et al. 2000].
    This implementation uses the PLS Wold 2 blocks algorithm based on two
    nested loops:
        (i) The outer loop iterate over components.
        (ii) The inner loop estimates the weights vectors. This can be done
        with two algo. (a) the inner loop of the original NIPALS algo. or (b) a
        SVD on residuals cross-covariance matrices.

    n_components : int, number of components to keep. (default 2).

    scale : boolean, scale data? (default True)

    deflation_mode : str, "canonical" or "regression". See notes.

    mode : "A" classical PLS and "B" CCA. See notes.

    norm_y_weights : boolean, normalize Y weights to one? (default False)

    algorithm : string, "nipals" or "svd"
        The algorithm used to estimate the weights. It will be called
        n_components times, i.e. once for each iteration of the outer loop.

    max_iter : an integer, the maximum number of iterations (default 500)
        of the NIPALS inner loop (used only if algorithm="nipals")

    tol : non-negative real, default 1e-06
        The tolerance used in the iterative algorithm.

    copy : boolean, default True
        Whether the deflation should be done on a copy. Let the default
        value to True unless you don't care about side effects.

    Attributes
    ----------
    x_weights_ : array, [p, n_components]
        X block weights vectors.

    y_weights_ : array, [q, n_components]
        Y block weights vectors.

    x_loadings_ : array, [p, n_components]
        X block loadings vectors.

    y_loadings_ : array, [q, n_components]
        Y block loadings vectors.

    x_scores_ : array, [n_samples, n_components]
        X scores.

    y_scores_ : array, [n_samples, n_components]
        Y scores.

    x_rotations_ : array, [p, n_components]
        X block to latents rotations.

    y_rotations_ : array, [q, n_components]
        Y block to latents rotations.

    coef_ : array, [p, q]
        The coefficients of the linear model: ``Y = X coef_ + Err``

    n_iter_ : array-like
        Number of iterations of the NIPALS inner loop for each
        component. Not useful if the algorithm given is "svd".

    References
    ----------

    Jacob A. Wegelin. A survey of Partial Least Squares (PLS) methods, with
    emphasis on the two-block case. Technical Report 371, Department of
    Statistics, University of Washington, Seattle, 2000.

    In French but still a reference:
    Tenenhaus, M. (1998). La regression PLS: theorie et pratique. Paris:
    Editions Technic.

    See also
    --------
    PLSCanonical
    PLSRegression
    CCA
    PLS_SVD
    r   T
regressionr   nipalsF  ư>c
       
      C   s:   || _ || _|| _|| _|| _|| _|| _|| _|	| _d S )N)	n_componentsdeflation_moder&   r)   r8   	algorithmr'   r(   copy)
selfr?   r8   r@   r&   rA   r)   r'   r(   rB   r,   r,   r-   __init__   s    z_PLS.__init__c          	   C   sR  t || t|tj| jd}t|tj| jdd}|jdkrF|dd}|jd }|jd }|jd }| jdk sx| j|krt	d| j | j
dkrt	d	| j
 | j
d
kr| jdkrt	d| jdkrt	dt||| j\}}| _| _| _| _|}|}t|| jf| _t|| jf| _t|| jf| _t|| jf| _t|| jf| _t|| jf| _g | _xDt| jD ]4}tt|j|ttj j!k rt"#d|  P | j
dkrt$||| j| j%| j&| j'd\}	}
}| j(| n| j
d
krt)||d\}	}
t*|	|
j\}	}
|
j}
t||	}| j'r8d}nt|
j|
}t||
| }t|j|ttj j!k rt"#d|  P t|j|t|j| }|t||j8 }| jdkrt|j|t|j| }|t||j8 }| jdkr&t|j|t|j| }|t||j8 }|+ | jdd|f< |+ | jdd|f< |	+ | jdd|f< |
+ | jdd|f< |+ | jdd|f< |+ | jdd|f< qvW t| jt,t| jj| jdd| _-|jd dkrt| jt,t| jj| jdd| _.nt/d| _.ds,| jdkrNt| j-| jj| _0| j0| j | _0| S )a  Fit model to data.

        Parameters
        ----------
        X : array-like, shape = [n_samples, n_features]
            Training vectors, where n_samples is the number of samples and
            n_features is the number of predictors.

        Y : array-like, shape = [n_samples, n_targets]
            Target vectors, where n_samples is the number of samples and
            n_targets is the number of response variables.
        )r   rB   F)r   rB   	ensure_2dr   r   z Invalid number of components: %d)r   r<   z7Got algorithm %s when only 'svd' and 'nipals' are knownr   r   zHIncompatible configuration: mode B is not implemented with svd algorithm)	canonicalr;   zThe deflation mode is unknownz#Y residual constant at iteration %sr<   )r$   r%   r&   r'   r(   r)   )r$   r%   z!X scores are null at iteration %srG   r;   N)r   T)1r   r   r   float64rB   ndimreshaper!   r?   
ValueErrorrA   r&   r@   r9   r8   x_mean_y_mean_x_std_y_std_zeros	x_scores_	y_scores_
x_weights_
y_weights_Zx_loadings_Zy_loadings_n_iter_rangeallr   r   r   doubler   r"   r#   r.   r'   r(   r)   appendr5   r   Zravelr   x_rotations_y_rotations_r7   coef_)rC   r$   r%   npqZXkZYkkr*   r+   rU   x_scoresZy_ssy_scoresZ
x_loadingsZ
y_loadingsr,   r,   r-   fit   s    








"$	z_PLS.fitNc             C   s   t | d t||td}|| j8 }|| j }t|| j}|dk	rt|d|td}|jdkrh|	dd}|| j
8 }|| j }t|| j}||fS |S )a  Apply the dimension reduction learned on the train data.

        Parameters
        ----------
        X : array-like, shape = [n_samples, n_features]
            Training vectors, where n_samples is the number of samples and
            n_features is the number of predictors.

        Y : array-like, shape = [n_samples, n_targets]
            Target vectors, where n_samples is the number of samples and
            n_targets is the number of response variables.

        copy : boolean, default True
            Whether to copy X and Y, or perform in-place normalization.

        Returns
        -------
        x_scores if Y is not given, (x_scores, y_scores) otherwise.
        rL   )rB   r   NF)rE   rB   r   r   rF   )r   r   r   rL   rN   r   r   rZ   rI   rJ   rM   rO   r[   )rC   r$   r%   rB   ra   rb   r,   r,   r-   	transformt  s    





z_PLS.transformc             C   sD   t | d t||td}|| j8 }|| j }t|| j}|| j S )a   Apply the dimension reduction learned on the train data.

        Parameters
        ----------
        X : array-like, shape = [n_samples, n_features]
            Training vectors, where n_samples is the number of samples and
            n_features is the number of predictors.

        copy : boolean, default True
            Whether to copy X and Y, or perform in-place normalization.

        Notes
        -----
        This call requires the estimation of a p x q matrix, which may
        be an issue in high dimensional space.
        rL   )rB   r   )	r   r   r   rL   rN   r   r   r\   rM   )rC   r$   rB   ZYpredr,   r,   r-   predict  s    


z_PLS.predictc             C   s   |  ||||S )aB  Learn and apply the dimension reduction on the train data.

        Parameters
        ----------
        X : array-like, shape = [n_samples, n_features]
            Training vectors, where n_samples is the number of samples and
            n_features is the number of predictors.

        y : array-like, shape = [n_samples, n_targets]
            Target vectors, where n_samples is the number of samples and
            n_targets is the number of response variables.

        Returns
        -------
        x_scores if Y is not given, (x_scores, y_scores) otherwise.
        )rc   rd   )rC   r$   yr,   r,   r-   fit_transform  s    z_PLS.fit_transform)	r   Tr;   r   r<   Fr=   r>   T)NT)T)N)
__name__
__module____qualname____doc__r   rD   rc   rd   re   rg   r,   r,   r,   r-   r:   v   s   b   
&
r:   c                   s"   e Zd ZdZd fdd	Z  ZS )	r   a  PLS regression

    PLSRegression implements the PLS 2 blocks regression known as PLS2 or PLS1
    in case of one dimensional response.
    This class inherits from _PLS with mode="A", deflation_mode="regression",
    norm_y_weights=False and algorithm="nipals".

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

    Parameters
    ----------
    n_components : int, (default 2)
        Number of components to keep.

    scale : boolean, (default True)
        whether to scale the data

    max_iter : an integer, (default 500)
        the maximum number of iterations of the NIPALS inner loop (used
        only if algorithm="nipals")

    tol : non-negative real
        Tolerance used in the iterative algorithm default 1e-06.

    copy : boolean, default True
        Whether the deflation should be done on a copy. Let the default
        value to True unless you don't care about side effect

    Attributes
    ----------
    x_weights_ : array, [p, n_components]
        X block weights vectors.

    y_weights_ : array, [q, n_components]
        Y block weights vectors.

    x_loadings_ : array, [p, n_components]
        X block loadings vectors.

    y_loadings_ : array, [q, n_components]
        Y block loadings vectors.

    x_scores_ : array, [n_samples, n_components]
        X scores.

    y_scores_ : array, [n_samples, n_components]
        Y scores.

    x_rotations_ : array, [p, n_components]
        X block to latents rotations.

    y_rotations_ : array, [q, n_components]
        Y block to latents rotations.

    coef_ : array, [p, q]
        The coefficients of the linear model: ``Y = X coef_ + Err``

    n_iter_ : array-like
        Number of iterations of the NIPALS inner loop for each
        component.

    Notes
    -----
    Matrices::

        T: x_scores_
        U: y_scores_
        W: x_weights_
        C: y_weights_
        P: x_loadings_
        Q: y_loadings__

    Are computed such that::

        X = T P.T + Err and Y = U Q.T + Err
        T[:, k] = Xk W[:, k] for k in range(n_components)
        U[:, k] = Yk C[:, k] for k in range(n_components)
        x_rotations_ = W (P.T W)^(-1)
        y_rotations_ = C (Q.T C)^(-1)

    where Xk and Yk are residual matrices at iteration k.

    `Slides explaining
    PLS <http://www.eigenvector.com/Docs/Wise_pls_properties.pdf>`_


    For each component k, find weights u, v that optimizes:
    ``max corr(Xk u, Yk v) * std(Xk u) std(Yk u)``, such that ``|u| = 1``

    Note that it maximizes both the correlations between the scores and the
    intra-block variances.

    The residual matrix of X (Xk+1) block is obtained by the deflation on
    the current X score: x_score.

    The residual matrix of Y (Yk+1) block is obtained by deflation on the
    current X score. This performs the PLS regression known as PLS2. This
    mode is prediction oriented.

    This implementation provides the same results that 3 PLS packages
    provided in the R language (R-project):

        - "mixOmics" with function pls(X, Y, mode = "regression")
        - "plspm " with function plsreg2(X, Y)
        - "pls" with function oscorespls.fit(X, Y)

    Examples
    --------
    >>> from sklearn.cross_decomposition import PLSRegression
    >>> X = [[0., 0., 1.], [1.,0.,0.], [2.,2.,2.], [2.,5.,4.]]
    >>> Y = [[0.1, -0.2], [0.9, 1.1], [6.2, 5.9], [11.9, 12.3]]
    >>> pls2 = PLSRegression(n_components=2)
    >>> pls2.fit(X, Y)
    ... # doctest: +NORMALIZE_WHITESPACE
    PLSRegression(copy=True, max_iter=500, n_components=2, scale=True,
            tol=1e-06)
    >>> Y_pred = pls2.predict(X)

    References
    ----------

    Jacob A. Wegelin. A survey of Partial Least Squares (PLS) methods, with
    emphasis on the two-block case. Technical Report 371, Department of
    Statistics, University of Washington, Seattle, 2000.

    In french but still a reference:
    Tenenhaus, M. (1998). La regression PLS: theorie et pratique. Paris:
    Editions Technic.
    r   T  ư>c          
      s$   t t| j||ddd|||d d S )Nr;   r   F)r?   r8   r@   r&   r)   r'   r(   rB   )superr   rD   )rC   r?   r8   r'   r(   rB   )	__class__r,   r-   rD   J  s
    
zPLSRegression.__init__)r   Trl   rm   T)rh   ri   rj   rk   rD   __classcell__r,   r,   )ro   r-   r     s     c                   s"   e Zd ZdZd	 fdd	Z  ZS )
r   a   PLSCanonical implements the 2 blocks canonical PLS of the original Wold
    algorithm [Tenenhaus 1998] p.204, referred as PLS-C2A in [Wegelin 2000].

    This class inherits from PLS with mode="A" and deflation_mode="canonical",
    norm_y_weights=True and algorithm="nipals", but svd should provide similar
    results up to numerical errors.

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

    Parameters
    ----------
    n_components : int, (default 2).
        Number of components to keep

    scale : boolean, (default True)
        Option to scale data

    algorithm : string, "nipals" or "svd"
        The algorithm used to estimate the weights. It will be called
        n_components times, i.e. once for each iteration of the outer loop.

    max_iter : an integer, (default 500)
        the maximum number of iterations of the NIPALS inner loop (used
        only if algorithm="nipals")

    tol : non-negative real, default 1e-06
        the tolerance used in the iterative algorithm

    copy : boolean, default True
        Whether the deflation should be done on a copy. Let the default
        value to True unless you don't care about side effect

    Attributes
    ----------
    x_weights_ : array, shape = [p, n_components]
        X block weights vectors.

    y_weights_ : array, shape = [q, n_components]
        Y block weights vectors.

    x_loadings_ : array, shape = [p, n_components]
        X block loadings vectors.

    y_loadings_ : array, shape = [q, n_components]
        Y block loadings vectors.

    x_scores_ : array, shape = [n_samples, n_components]
        X scores.

    y_scores_ : array, shape = [n_samples, n_components]
        Y scores.

    x_rotations_ : array, shape = [p, n_components]
        X block to latents rotations.

    y_rotations_ : array, shape = [q, n_components]
        Y block to latents rotations.

    n_iter_ : array-like
        Number of iterations of the NIPALS inner loop for each
        component. Not useful if the algorithm provided is "svd".

    Notes
    -----
    Matrices::

        T: x_scores_
        U: y_scores_
        W: x_weights_
        C: y_weights_
        P: x_loadings_
        Q: y_loadings__

    Are computed such that::

        X = T P.T + Err and Y = U Q.T + Err
        T[:, k] = Xk W[:, k] for k in range(n_components)
        U[:, k] = Yk C[:, k] for k in range(n_components)
        x_rotations_ = W (P.T W)^(-1)
        y_rotations_ = C (Q.T C)^(-1)

    where Xk and Yk are residual matrices at iteration k.

    `Slides explaining PLS
    <http://www.eigenvector.com/Docs/Wise_pls_properties.pdf>`_

    For each component k, find weights u, v that optimize::

        max corr(Xk u, Yk v) * std(Xk u) std(Yk u), such that ``|u| = |v| = 1``

    Note that it maximizes both the correlations between the scores and the
    intra-block variances.

    The residual matrix of X (Xk+1) block is obtained by the deflation on the
    current X score: x_score.

    The residual matrix of Y (Yk+1) block is obtained by deflation on the
    current Y score. This performs a canonical symmetric version of the PLS
    regression. But slightly different than the CCA. This is mostly used
    for modeling.

    This implementation provides the same results that the "plspm" package
    provided in the R language (R-project), using the function plsca(X, Y).
    Results are equal or collinear with the function
    ``pls(..., mode = "canonical")`` of the "mixOmics" package. The difference
    relies in the fact that mixOmics implementation does not exactly implement
    the Wold algorithm since it does not normalize y_weights to one.

    Examples
    --------
    >>> from sklearn.cross_decomposition import PLSCanonical
    >>> X = [[0., 0., 1.], [1.,0.,0.], [2.,2.,2.], [2.,5.,4.]]
    >>> Y = [[0.1, -0.2], [0.9, 1.1], [6.2, 5.9], [11.9, 12.3]]
    >>> plsca = PLSCanonical(n_components=2)
    >>> plsca.fit(X, Y)
    ... # doctest: +NORMALIZE_WHITESPACE
    PLSCanonical(algorithm='nipals', copy=True, max_iter=500, n_components=2,
                 scale=True, tol=1e-06)
    >>> X_c, Y_c = plsca.transform(X, Y)

    References
    ----------

    Jacob A. Wegelin. A survey of Partial Least Squares (PLS) methods, with
    emphasis on the two-block case. Technical Report 371, Department of
    Statistics, University of Washington, Seattle, 2000.

    Tenenhaus, M. (1998). La regression PLS: theorie et pratique. Paris:
    Editions Technic.

    See also
    --------
    CCA
    PLSSVD
    r   Tr<     ư>c                s&   t t| j||ddd||||d	 d S )NrG   r   T)	r?   r8   r@   r&   r)   rA   r'   r(   rB   )rn   r   rD   )rC   r?   r8   rA   r'   r(   rB   )ro   r,   r-   rD     s
    
zPLSCanonical.__init__)r   Tr<   rq   rr   T)rh   ri   rj   rk   rD   rp   r,   r,   )ro   r-   r   S  s     c               @   s6   e Zd ZdZdddZdd Zdd	d
ZdddZdS )r   aG  Partial Least Square SVD

    Simply perform a svd on the crosscovariance matrix: X'Y
    There are no iterative deflation here.

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

    Parameters
    ----------
    n_components : int, default 2
        Number of components to keep.

    scale : boolean, default True
        Whether to scale X and Y.

    copy : boolean, default True
        Whether to copy X and Y, or perform in-place computations.

    Attributes
    ----------
    x_weights_ : array, [p, n_components]
        X block weights vectors.

    y_weights_ : array, [q, n_components]
        Y block weights vectors.

    x_scores_ : array, [n_samples, n_components]
        X scores.

    y_scores_ : array, [n_samples, n_components]
        Y scores.

    See also
    --------
    PLSCanonical
    CCA
    r   Tc             C   s   || _ || _|| _d S )N)r?   r8   rB   )rC   r?   r8   rB   r,   r,   r-   rD     s    zPLSSVD.__init__c             C   s,  t || t|tj| jd}t|tj| jdd}|jdkrF|dd}| jt|j	d |j	d krt
d| jt|j	t|j	f t||| j\}}| _| _| _| _t|j|}| jt|j	krt|dd\}}}nt|| jd\}}}t||\}}|j}t||| _t||| _|| _|| _| S )	a  Fit model to data.

        Parameters
        ----------
        X : array-like, shape = [n_samples, n_features]
            Training vectors, where n_samples is the number of samples and
            n_features is the number of predictors.

        Y : array-like, shape = [n_samples, n_targets]
            Target vectors, where n_samples is the number of samples and
            n_targets is the number of response variables.
        )r   rB   F)r   rB   rE   r   rF   zRInvalid number of components n_components=%d with X of shape %s and Y of shape %s.)r/   )r`   )r   r   r   rH   rB   rI   rJ   r?   maxr!   rK   strr9   r8   rL   rM   rN   rO   r   r   minr   r   r   rQ   rR   rS   rT   )rC   r$   r%   r0   r1   r2   Vr,   r,   r-   rc     s(    

"z
PLSSVD.fitNc             C   s~   t | d t|tjd}|| j | j }t|| j}|dk	rz|jdkrT|	dd}|| j
 | j }t|| j}||fS |S )a  
        Apply the dimension reduction learned on the train data.

        Parameters
        ----------
        X : array-like, shape = [n_samples, n_features]
            Training vectors, where n_samples is the number of samples and
            n_features is the number of predictors.

        Y : array-like, shape = [n_samples, n_targets]
            Target vectors, where n_samples is the number of samples and
            n_targets is the number of response variables.
        rL   )r   Nr   rF   )r   r   r   rH   rL   rN   r   rS   rI   rJ   rM   rO   rT   )rC   r$   r%   ZXrra   ZYrrb   r,   r,   r-   rd   A  s    

zPLSSVD.transformc             C   s   |  ||||S )aB  Learn and apply the dimension reduction on the train data.

        Parameters
        ----------
        X : array-like, shape = [n_samples, n_features]
            Training vectors, where n_samples is the number of samples and
            n_features is the number of predictors.

        y : array-like, shape = [n_samples, n_targets]
            Target vectors, where n_samples is the number of samples and
            n_targets is the number of response variables.

        Returns
        -------
        x_scores if Y is not given, (x_scores, y_scores) otherwise.
        )rc   rd   )rC   r$   rf   r,   r,   r-   rg   [  s    zPLSSVD.fit_transform)r   TT)N)N)rh   ri   rj   rk   rD   rc   rd   rg   r,   r,   r,   r-   r     s
   %
0
)r   r   r   F)T)#rk   r"   abcr   r   numpyr   Zscipy.linalgr   r   Zscipy.sparse.linalgr   baser   r	   r
   utilsr   r   Zutils.extmathr   Zutils.validationr   r   Z	externalsr   __all__r.   r5   r9   with_metaclassr:   r   r   r   r,   r,   r,   r-   <module>   s0   
 
;
  R  