U
    9%eTy                     @   s  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Zddl	m
Z ddlmZmZm
Z
 ddlmZ ddlmZ dd	lmZmZmZmZmZ dd
lmZ ddlmZmZ ddlmZ ddl m!Z!m"Z"m#Z#m$Z$ ddl%m&Z&m'Z' ddl(m)Z)m*Z* ddl+m,Z,m-Z- ddl.m/Z/m0Z0m1Z1 dZ2dd Z3d+ddZ4d,ddZ5d-ddZ6G dd deedZ7G d d! d!eZ8G d"d# d#Z9G d$d% d%eee7Z:d.d'd(Z;d/d)d*Z<dS )0z
Generalized Linear Models.
    N)ABCMetaabstractmethod)Integral)linalgoptimizesparse)lsqr)expit   )BaseEstimatorClassifierMixinMultiOutputMixinRegressorMixin_fit_context)_is_constant_feature)check_arraycheck_random_state)get_namespace)ArrayDataset32ArrayDataset64CSRDataset32CSRDataset64)_incremental_mean_and_varsafe_sparse_dot)Paralleldelayed)inplace_column_scalemean_variance_axis)FLOAT_DTYPES_check_sample_weightcheck_is_fittedg{Gz?c                 C   st   | dkrt d| dkrd}n| }d| d}d}d|kr>d	}| dkr`| r`td
| | t n| sptdt |S )aB  Normalize is to be deprecated from linear models and a use of
    a pipeline with a StandardScaler is to be recommended instead.
    Here the appropriate message is selected to be displayed to the user
    depending on the default normalize value (as it varies between the linear
    models and normalize value selected by the user).

    Parameters
    ----------
    normalize : bool,
        normalize value passed by the user

    estimator_name : str
        name of the linear estimator which calls this function.
        The name will be used for writing the deprecation warnings

    Returns
    -------
    normalize : bool,
        normalize value which should further be used by the estimator at this
        stage of the depreciation process

    Notes
    -----
    This function should be completely removed in 1.4.
    )TF
deprecatedzALeave 'normalize' to its default value or set it to True or Falser!   FzIf you wish to scale the data, use Pipeline with a StandardScaler in a preprocessing stage. To reproduce the previous behavior:

from sklearn.pipeline import make_pipeline

model = make_pipeline(StandardScaler(with_mean=False), z())

If you wish to pass a sample_weight parameter, you need to pass it as a fit parameter to each step of the pipeline as follows:

kwargs = {s[0] + '__sample_weight': sample_weight for s in model.steps}
model.fit(X, y, **kwargs)

 Z	LassoLarsz=Set parameter alpha to: original_alpha * np.sqrt(n_samples). zF'normalize' was deprecated in version 1.2 and will be removed in 1.4.
a3  'normalize' was deprecated in version 1.2 and will be removed in 1.4. Please leave the normalize parameter to its default value to silence this warning. The default behavior of this estimator is to not do any normalization. If normalization is needed please use sklearn.preprocessing.StandardScaler instead.)
ValueErrorwarningswarnFutureWarning)	normalizeZestimator_name
_normalizeZpipeline_msgZ	alpha_msg r)   Y/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/sklearn/linear_model/_base.py_deprecate_normalize;   s6    
r+   c           
      C   s   t |}|dttjj}| jtjkr4t}t	}nt
}t}t| rf|| j| j| j|||d}t}	nt| } || |||d}d}	||	fS )aD  Create ``Dataset`` abstraction for sparse and dense inputs.

    This also returns the ``intercept_decay`` which is different
    for sparse datasets.

    Parameters
    ----------
    X : array-like, shape (n_samples, n_features)
        Training data

    y : array-like, shape (n_samples, )
        Target values.

    sample_weight : numpy array of shape (n_samples,)
        The weight of each sample

    random_state : int, RandomState instance or None (default)
        Determines random number generation for dataset random sampling. It is not
        used for dataset shuffling.
        Pass an int for reproducible output across multiple function calls.
        See :term:`Glossary <random_state>`.

    Returns
    -------
    dataset
        The ``Dataset`` abstraction
    intercept_decay
        The intercept decay
       )seed      ?)r   randintnpZiinfoZint32maxdtypefloat32r   r   r   r   spissparsedataZindptrindicesSPARSE_INTERCEPT_DECAYZascontiguousarray)
Xysample_weightZrandom_staterngr-   ZCSRDataZ	ArrayDataZdatasetZintercept_decayr)   r)   r*   make_dataset   s    

r=   FTc                 C   s  t |tjrd}|dk	r"t|}|rNt| |ddgtd} t|| j|dd}n4|j| j|d}|rt	
| rv|  } n| jdd	} |rt	
| rt| d
|d\}}	nF|rt| ddd|d\}}	}
ntj| d
|d}|j| jdd}| |8 } |rv|	j| jdd}	t|	|| jd
 }|dkr.|	| jd
 9 }	n|	| 9 }	tj|	|	d}d||< t	
| rlt| d|  n| | } ntj| jd | jd}tj|d
|d}||8 }n\tj| jd | jd}tj| jd | jd}|jdkr| jd
}ntj|jd | jd}| ||||fS )a9  Center and scale data.

    Centers data to have mean zero along axis 0. If fit_intercept=False or if
    the X is a sparse matrix, no centering is done, but normalization can still
    be applied. The function returns the statistics necessary to reconstruct
    the input data, which are X_offset, y_offset, X_scale, such that the output

        X = (X - X_offset) / X_scale

    X_scale is the L2 norm of X - X_offset. If sample_weight is not None,
    then the weighted mean of X and y is zero, and not the mean itself. If
    fit_intercept=True, the mean, eventually weighted, is returned, independently
    of whether X was centered (option used for optimization with sparse data in
    coordinate_descend).

    This is here because nearly all linear models will want their data to be
    centered. This function also systematically makes y consistent with X.dtype

    Returns
    -------
    X_out : {ndarray, sparse matrix} of shape (n_samples, n_features)
        If copy=True a copy of the input X is triggered, otherwise operations are
        inplace.
        If input X is dense, then X_out is centered.
        If normalize is True, then X_out is rescaled (dense and sparse case)
    y_out : {ndarray, sparse matrix} of shape (n_samples,) or (n_samples, n_targets)
        Centered version of y. Likely performed inplace on input y.
    X_offset : ndarray of shape (n_features,)
        The mean per column of input X.
    y_offset : float or ndarray of shape (n_features,)
    X_scale : ndarray of shape (n_features,)
        The standard deviation per column of input X.
    Ncsrcsc)copyaccept_sparser2   F)r2   r@   Z	ensure_2d)r@   K)orderr   )axisweights        )Z	last_meanZlast_varianceZlast_sample_countr;   outr.   r,   r2   )
isinstancenumbersNumberr0   Zasarrayr   r   r2   astyper4   r5   r@   r   r   Zaverager   shapesumsqrtr   oneszerosndimtype)r9   r:   fit_interceptr'   r@   Zcopy_yr;   check_inputX_offsetZX_var_Zconstant_maskX_scaley_offsetr)   r)   r*   _preprocess_data   s\    +






r[   c                 C   s   | j d }t|}t| s(t|r>tj|df||fd}t| rTt|| } n2|rp| |ddtjf 9 } n| |ddtjf  } t|rt||}nZ|r|j	dkr||9 }q||ddtjf 9 }n*|j	dkr|| }n||ddtjf  }| ||fS )a  Rescale data sample-wise by square root of sample_weight.

    For many linear models, this enables easy support for sample_weight because

        (y - X w)' S (y - X w)

    with S = diag(sample_weight) becomes

        ||y_rescaled - X_rescaled w||_2^2

    when setting

        y_rescaled = sqrt(S) y
        X_rescaled = sqrt(S) X

    Returns
    -------
    X_rescaled : {array-like, sparse matrix}

    y_rescaled : {array-like, sparse matrix}
    r   )rN   Nr,   )
rN   r0   rP   r4   r5   r   Z
dia_matrixr   ZnewaxisrS   )r9   r:   r;   inplace	n_samplessample_weight_sqrtZ	sw_matrixr)   r)   r*   _rescale_data/  s,    

 





r_   c                   @   s<   e Zd ZdZedd Zdd Zdd Zdd	 Zd
d Z	dS )LinearModelzBase class for Linear Modelsc                 C   s   dS )z
Fit model.Nr)   )selfr9   r:   r)   r)   r*   fitj  s    zLinearModel.fitc                 C   s6   t |  | j|dddgdd}t|| jjdd| j S )Nr>   r?   cooFrA   resetTZdense_output)r    _validate_datar   coef_T
intercept_ra   r9   r)   r)   r*   _decision_functionn  s    zLinearModel._decision_functionc                 C   s
   |  |S )a!  
        Predict using the linear model.

        Parameters
        ----------
        X : array-like or sparse matrix, shape (n_samples, n_features)
            Samples.

        Returns
        -------
        C : array, shape (n_samples,)
            Returns predicted values.
        )rl   rk   r)   r)   r*   predictt  s    zLinearModel.predictc                 C   s>   | j r4tj| j||jd| _|t|| jj | _nd| _dS )zSet the intercept_rI   rF   N)rU   r0   dividerh   r2   dotri   rj   )ra   rW   rZ   rY   r)   r)   r*   _set_intercept  s    zLinearModel._set_interceptc                 C   s   ddiS )NZ
requires_yTr)   )ra   r)   r)   r*   
_more_tags  s    zLinearModel._more_tagsN)
__name__
__module____qualname____doc__r   rb   rl   rm   rp   rq   r)   r)   r)   r*   r`   g  s   

r`   )	metaclassc                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	LinearClassifierMixinzRMixin for linear classifiers.

    Handles prediction for sparse and dense X.
    c                 C   sZ   t |  t|\}}| j|ddd}t|| jjdd| j }|jd dkrV||dS |S )a  
        Predict confidence scores for samples.

        The confidence score for a sample is proportional to the signed
        distance of that sample to the hyperplane.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            The data matrix for which we want to get the confidence scores.

        Returns
        -------
        scores : ndarray of shape (n_samples,) or (n_samples, n_classes)
            Confidence scores per `(n_samples, n_classes)` combination. In the
            binary case, confidence score for `self.classes_[1]` where >0 means
            this class would be predicted.
        r>   Frd   Trf   r,   ))	r    r   rg   r   rh   ri   rj   rN   reshape)ra   r9   xprX   scoresr)   r)   r*   decision_function  s
    z'LinearClassifierMixin.decision_functionc                 C   sR   t |\}}| |}t|jdkr6||dkt}n|j|dd}|| j|S )a~  
        Predict class labels for samples in X.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            The data matrix for which we want to get the predictions.

        Returns
        -------
        y_pred : ndarray of shape (n_samples,)
            Vector containing the class labels for each sample.
        r,   r   rD   )	r   r|   lenrN   rM   intZargmaxZtakeZclasses_)ra   r9   rz   rX   r{   r7   r)   r)   r*   rm     s    
zLinearClassifierMixin.predictc                 C   s\   |  |}t||d |jdkr4td| |gjS ||jdd|jd df }|S dS )zProbability estimation for OvR logistic regression.

        Positive class probabilities are computed as
        1. / (1. + np.exp(-self.decision_function(X)));
        multiclass is handled by normalizing that over all classes.
        rG   r,   r}   r   rx   N)	r|   r	   rS   r0   vstackri   rO   ry   rN   )ra   r9   Zprobr)   r)   r*   _predict_proba_lr  s    

 z'LinearClassifierMixin._predict_proba_lrN)rr   rs   rt   ru   r|   rm   r   r)   r)   r)   r*   rw     s   rw   c                   @   s    e Zd ZdZdd Zdd ZdS )SparseCoefMixinzlMixin for converting coef_ to and from CSR format.

    L1-regularizing estimators should inherit this.
    c                 C   s,   d}t | |d t| jr(| j | _| S )a  
        Convert coefficient matrix to dense array format.

        Converts the ``coef_`` member (back) to a numpy.ndarray. This is the
        default format of ``coef_`` and is required for fitting, so calling
        this method is only required on models that have previously been
        sparsified; otherwise, it is a no-op.

        Returns
        -------
        self
            Fitted estimator.
        z6Estimator, %(name)s, must be fitted before densifying.msg)r    r4   r5   rh   Ztoarrayra   r   r)   r)   r*   densify  s
    zSparseCoefMixin.densifyc                 C   s"   d}t | |d t| j| _| S )a  
        Convert coefficient matrix to sparse format.

        Converts the ``coef_`` member to a scipy.sparse matrix, which for
        L1-regularized models can be much more memory- and storage-efficient
        than the usual numpy.ndarray representation.

        The ``intercept_`` member is not converted.

        Returns
        -------
        self
            Fitted estimator.

        Notes
        -----
        For non-sparse models, i.e. when there are not many zeros in ``coef_``,
        this may actually *increase* memory usage, so use this method with
        care. A rule of thumb is that the number of zero elements, which can
        be computed with ``(coef_ == 0).sum()``, must be more than 50% for this
        to provide significant benefits.

        After calling this method, further fitting with the partial_fit
        method (if any) will not work until you call densify.
        z7Estimator, %(name)s, must be fitted before sparsifying.r   )r    r4   Z
csr_matrixrh   r   r)   r)   r*   sparsify  s    zSparseCoefMixin.sparsifyN)rr   rs   rt   ru   r   r   r)   r)   r)   r*   r     s   r   c                   @   sZ   e Zd ZU dZdgdgdegdgdZeed< ddddddd	Ze	dd
dddZ
dS )LinearRegressiona^  
    Ordinary least squares Linear Regression.

    LinearRegression fits a linear model with coefficients w = (w1, ..., wp)
    to minimize the residual sum of squares between the observed targets in
    the dataset, and the targets predicted by the linear approximation.

    Parameters
    ----------
    fit_intercept : bool, default=True
        Whether to calculate the intercept for this model. If set
        to False, no intercept will be used in calculations
        (i.e. data is expected to be centered).

    copy_X : bool, default=True
        If True, X will be copied; else, it may be overwritten.

    n_jobs : int, default=None
        The number of jobs to use for the computation. This will only provide
        speedup in case of sufficiently large problems, that is if firstly
        `n_targets > 1` and secondly `X` is sparse or if `positive` is set
        to `True`. ``None`` means 1 unless in a
        :obj:`joblib.parallel_backend` context. ``-1`` means using all
        processors. See :term:`Glossary <n_jobs>` for more details.

    positive : bool, default=False
        When set to ``True``, forces the coefficients to be positive. This
        option is only supported for dense arrays.

        .. versionadded:: 0.24

    Attributes
    ----------
    coef_ : array of shape (n_features, ) or (n_targets, n_features)
        Estimated coefficients for the linear regression problem.
        If multiple targets are passed during the fit (y 2D), this
        is a 2D array of shape (n_targets, n_features), while if only
        one target is passed, this is a 1D array of length n_features.

    rank_ : int
        Rank of matrix `X`. Only available when `X` is dense.

    singular_ : array of shape (min(X, y),)
        Singular values of `X`. Only available when `X` is dense.

    intercept_ : float or array of shape (n_targets,)
        Independent term in the linear model. Set to 0.0 if
        `fit_intercept = False`.

    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
    --------
    Ridge : Ridge regression addresses some of the
        problems of Ordinary Least Squares by imposing a penalty on the
        size of the coefficients with l2 regularization.
    Lasso : The Lasso is a linear model that estimates
        sparse coefficients with l1 regularization.
    ElasticNet : Elastic-Net is a linear regression
        model trained with both l1 and l2 -norm regularization of the
        coefficients.

    Notes
    -----
    From the implementation point of view, this is just plain Ordinary
    Least Squares (scipy.linalg.lstsq) or Non Negative Least Squares
    (scipy.optimize.nnls) wrapped as a predictor object.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.linear_model import LinearRegression
    >>> X = np.array([[1, 1], [1, 2], [2, 2], [2, 3]])
    >>> # y = 1 * x_0 + 2 * x_1 + 3
    >>> y = np.dot(X, np.array([1, 2])) + 3
    >>> reg = LinearRegression().fit(X, y)
    >>> reg.score(X, y)
    1.0
    >>> reg.coef_
    array([1., 2.])
    >>> reg.intercept_
    3.0...
    >>> reg.predict(np.array([[3, 5]]))
    array([16.])
    booleanNrU   copy_Xn_jobspositive_parameter_constraintsTFc                C   s   || _ || _|| _|| _d S Nr   )ra   rU   r   r   r   r)   r)   r*   __init__}  s    zLinearRegression.__init__)Zprefer_skip_nested_validationc                    s  | j }| jrdndddg}| j |ddd\ |dk	}|rPt|  jdd}| jo`t  }t | j	||d	\ }}	}
|rt
 ||d
\ | jrjdk rt d | _n>t|d fddtjd D }tdd |D | _nt r||
 |r: fdd} fdd}n fdd} fdd}tjj j||djdk rtd | _n>t|dfddtjd D }tdd |D | _n$t \| _}| _| _| jj| _jdkrt| j| _| ||	|
 | S )ap  
        Fit linear model.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            Training data.

        y : array-like of shape (n_samples,) or (n_samples, n_targets)
            Target values. Will be cast to X's dtype if necessary.

        sample_weight : array-like of shape (n_samples,), default=None
            Individual weights for each sample.

            .. versionadded:: 0.17
               parameter *sample_weight* support to LinearRegression.

        Returns
        -------
        self : object
            Fitted Estimator.
        Fr>   r?   rc   T)rA   Z	y_numericZmulti_outputN)r2   Zonly_non_negative)rU   r@   r;   )r\   r
   r   )r   c                 3   s*   | ]"}t tj d d |f V  qd S r   )r   r   nnls.0j)r9   r:   r)   r*   	<genexpr>  s    z'LinearRegression.fit.<locals>.<genexpr>r,   c                 S   s   g | ]}|d  qS r   r)   r   rH   r)   r)   r*   
<listcomp>  s     z(LinearRegression.fit.<locals>.<listcomp>c                    s     | |    S r   ro   br9   X_offset_scaler^   r)   r*   matvec  s    z$LinearRegression.fit.<locals>.matvecc                    s    j | |   S r   )ri   ro   r   r   r)   r*   rmatvec  s    z%LinearRegression.fit.<locals>.rmatvecc                    s     | |   S r   r   r   r9   r   r)   r*   r     s    c                    s    j | |    S r   )ri   ro   rO   r   r   r)   r*   r     s    )rN   r   r   c                 3   s,   | ]$}t t d d |f  V  qd S r   )r   r   ravelr   )
X_centeredr:   r)   r*   r     s   c                 S   s   g | ]}|d  qS r   r)   r   r)   r)   r*   r     s     )r   r   rg   r   r2   r   r4   r5   r[   rU   r_   rS   r   r   rh   r   rangerN   r0   r   r   r   ZLinearOperatorr   ZlstsqZrank_Z	singular_ri   r   rp   )ra   r9   r:   r;   Zn_jobs_rA   Zhas_swZcopy_X_in_preprocess_datarW   rZ   rY   Zoutsr   r   rX   r)   )r9   r   r   r^   r:   r*   rb     s~        
      
  
zLinearRegression.fit)N)rr   rs   rt   ru   r   r   dict__annotations__r   r   rb   r)   r)   r)   r*   r     s   
`
r   h㈵>c              
   C   s   | j d }|d }t|d |d }| dd|f ||  ||  }	| dd|f ||  ||  }
t|	|
}|||f }|j|jg}|dkrdd |D }t|}tj||||dstd| d| d	| d
| d	dS )a^  Computes a single element of the gram matrix and compares it to
    the corresponding element of the user supplied gram matrix.

    If the values do not match a ValueError will be thrown.

    Parameters
    ----------
    X : ndarray of shape (n_samples, n_features)
        Data array.

    precompute : array-like of shape (n_features, n_features)
        User-supplied gram matrix.

    X_offset : ndarray of shape (n_features,)
        Array of feature means used to center design matrix.

    X_scale : ndarray of shape (n_features,)
        Array of feature scale factors used to normalize design matrix.

    rtol : float, default=None
        Relative tolerance; see numpy.allclose
        If None, it is set to 1e-4 for arrays of dtype numpy.float32 and 1e-7
        otherwise.

    atol : float, default=1e-5
        absolute tolerance; see :func`numpy.allclose`. Note that the default
        here is more tolerant than the default for
        :func:`numpy.testing.assert_allclose`, where `atol=0`.

    Raises
    ------
    ValueError
        Raised when the provided Gram matrix is not consistent.
    r,   r
   Nc                 S   s   g | ]}|t jkrd ndqS )g-C6?gHz>)r0   r3   )r   r2   r)   r)   r*   r   *  s     z2_check_precomputed_gram_matrix.<locals>.<listcomp>)rtolatolzGram matrix passed in via 'precompute' parameter did not pass validation when a single element was checked - please check that it was computed properly. For element (,z) we computed z! but the user-supplied value was .)rN   minr0   ro   r2   r1   iscloser#   )r9   
precomputerW   rY   r   r   
n_featuresf1f2Zv1Zv2expectedactualZdtypesZrtolsr)   r)   r*   _check_precomputed_gram_matrix  s    &
  r   c	              	   C   s  | j \}	}
t| r:d}t| |||d||d\} }}}}n<t| ||||||d\} }}}}|dk	rvt| ||d\} }}t|dr|rt|t|
r|rt|t	|
st
dt d}d}n|rt| ||| t|tr|dkr|	|
k}|dkr tj|
|
f| jd	d
}tj| j| |d t|ds0d}t|dr|dkrt| j|j}|jdkrtj|
|d	d
}tj| j||d n2|j d }tj|
|f|dd
}tj|j| |jd | ||||||fS )zFunction used at beginning of fit in linear models with L1 or L0 penalty.

    This function applies _preprocess_data and additionally computes the gram matrix
    `precompute` as needed as well as `Xy`.
    F)rU   r'   r@   rV   r;   N)r;   Z	__array__zlGram matrix was provided but X was centered to fit intercept, or X was normalized : recomputing Gram matrix.autoTC)rN   r2   rC   rG   r,   F)rN   r   r5   r[   r_   hasattrr0   ZallcloserR   rQ   r$   r%   UserWarningr   rJ   stremptyr2   ro   ri   Zresult_typerS   )r9   r:   ZXyr   r'   rU   r@   rV   r;   r]   r   rW   rZ   rY   rX   Zcommon_dtype	n_targetsr)   r)   r*   _pre_fit8  sp    




r   )N)FTTNT)F)Nr   )TN)=ru   rK   r$   abcr   r   r   numpyr0   Zscipy.sparser   r4   Zscipyr   r   Zscipy.sparse.linalgr   Zscipy.specialr	   baser   r   r   r   r   Zpreprocessing._datar   utilsr   r   Zutils._array_apir   Zutils._seq_datasetr   r   r   r   Zutils.extmathr   r   Zutils.parallelr   r   Zutils.sparsefuncsr   r   Zutils.validationr   r   r    r8   r+   r=   r[   r_   r`   rw   r   r   r   r   r)   r)   r)   r*   <module>   sN   M
9     
r
8-H: d   
H  