o
    tBh>p                     @   s   d Z ddlZddlZddlZddlmZ ddlm	Z	m
Z
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mZ dd	lmZmZ dd
lmZ ddlmZ G dd deeZG dd deZG dd deZ G dd deZ!dS )z>
Generalized Linear Models with Exponential Dispersion Family
    N   )TweedieDistribution)HalfGammaLossHalfPoissonLossHalfSquaredErrorHalfTweedieLossHalfTweedieLossIdentity)BaseEstimatorRegressorMixin)_check_optimize_result)check_scalarcheck_array
deprecated)check_is_fitted_check_sample_weight)_openmp_effective_n_threads   )LinearModelLossc                   @   sr   e Zd ZdZdddddddd	d
dZdddZdd Zdd ZdddZdd Z	dd Z
ededd ZdS )_GeneralizedLinearRegressora  Regression via a penalized Generalized Linear Model (GLM).

    GLMs based on a reproductive Exponential Dispersion Model (EDM) aim at fitting and
    predicting the mean of the target y as y_pred=h(X*w) with coefficients w.
    Therefore, the fit minimizes the following objective function with L2 priors as
    regularizer::

        1/(2*sum(s_i)) * sum(s_i * deviance(y_i, h(x_i*w)) + 1/2 * alpha * ||w||_2^2

    with inverse link function h, s=sample_weight and per observation (unit) deviance
    deviance(y_i, h(x_i*w)). Note that for an EDM, 1/2 * deviance is the negative
    log-likelihood up to a constant (in w) term.
    The parameter ``alpha`` corresponds to the lambda parameter in glmnet.

    Instead of implementing the EDM family and a link function separately, we directly
    use the loss functions `from sklearn._loss` which have the link functions included
    in them for performance reasons. We pick the loss functions that implement
    (1/2 times) EDM deviances.

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

    .. versionadded:: 0.23

    Parameters
    ----------
    alpha : float, default=1
        Constant that multiplies the penalty term and thus determines the
        regularization strength. ``alpha = 0`` is equivalent to unpenalized
        GLMs. In this case, the design matrix `X` must have full column rank
        (no collinearities).
        Values must be in the range `[0.0, inf)`.

    fit_intercept : bool, default=True
        Specifies if a constant (a.k.a. bias or intercept) should be
        added to the linear predictor (X @ coef + intercept).

    solver : 'lbfgs', default='lbfgs'
        Algorithm to use in the optimization problem:

        'lbfgs'
            Calls scipy's L-BFGS-B optimizer.

    max_iter : int, default=100
        The maximal number of iterations for the solver.
        Values must be in the range `[1, inf)`.

    tol : float, default=1e-4
        Stopping criterion. For the lbfgs solver,
        the iteration will stop when ``max{|g_j|, j = 1, ..., d} <= tol``
        where ``g_j`` is the j-th component of the gradient (derivative) of
        the objective function.
        Values must be in the range `(0.0, inf)`.

    warm_start : bool, default=False
        If set to ``True``, reuse the solution of the previous call to ``fit``
        as initialization for ``coef_`` and ``intercept_``.

    verbose : int, default=0
        For the lbfgs solver set verbose to any positive number for verbosity.
        Values must be in the range `[0, inf)`.

    Attributes
    ----------
    coef_ : array of shape (n_features,)
        Estimated coefficients for the linear predictor (`X @ coef_ +
        intercept_`) in the GLM.

    intercept_ : float
        Intercept (a.k.a. bias) added to linear predictor.

    n_iter_ : int
        Actual number of iterations used in the solver.

    _base_loss : BaseLoss, default=HalfSquaredError()
        This is set during fit via `self._get_loss()`.
        A `_base_loss` contains a specific loss function as well as the link
        function. The loss to be minimized specifies the distributional assumption of
        the GLM, i.e. the distribution from the EDM. Here are some examples:

        =======================  ========  ==========================
        _base_loss               Link      Target Domain
        =======================  ========  ==========================
        HalfSquaredError         identity  y any real number
        HalfPoissonLoss          log       0 <= y
        HalfGammaLoss            log       0 < y
        HalfTweedieLoss          log       dependend on tweedie power
        HalfTweedieLossIdentity  identity  dependend on tweedie power
        =======================  ========  ==========================

        The link function of the GLM, i.e. mapping from linear predictor
        `X @ coeff + intercept` to prediction `y_pred`. For instance, with a log link,
        we have `y_pred = exp(X @ coeff + intercept)`.
          ?Tlbfgsd   -C6?Fr   alphafit_interceptsolvermax_itertol
warm_startverbosec                C   s.   || _ || _|| _|| _|| _|| _|| _d S Nr   )selfr   r   r   r   r   r   r     r#   t/var/www/html/riverr-enterprise-integrations-main/venv/lib/python3.10/site-packages/sklearn/linear_model/_glm/glm.py__init__}   s   
z$_GeneralizedLinearRegressor.__init__Nc                 C   s  t | jdtjddd t| jtstd| j| j	dvr*t| j
j d| j	 | j	}t | jdtjd	d
 t | jdtjddd t | jdtjdd
 t| jtsZtd| j| j||ddgtjtjgddd\}}|dkrutj}ntt|j|jtj}t||ddd}t|||d}|j\}}|  | _t| j| jd}|j|std| jj
jd||   }| jrt!| dr| jrt"| j#t$| j%gf}	n| j#}	|	j&|dd}	n"| jrtj'|d	 |d}	|jj((tj)||d|	d< ntj'||d}	|dkr8|j*}
| j}t+ }t,j-j.|
|	d d| j| jdkd	 | jd!t/t0j1 d"|||||fd#}t2d|| _3|j4}	| jrJ|	d | _%|	d$d | _#| S d| _%|	| _#| S )%a  Fit a Generalized Linear Model.

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

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

        sample_weight : array-like of shape (n_samples,), default=None
            Sample weights.

        Returns
        -------
        self : object
            Fitted model.
        r           left)nametarget_typemin_valinclude_boundariesz0The argument fit_intercept must be bool; got {0})r   z$ supports only solvers 'lbfgs'; got r      )r(   r)   r*   r   neitherr    r   z-The argument warm_start must be bool; got {0}csccsrTF)accept_sparsedtype	y_numericmulti_outputr   Cr1   order	ensure_2dr1   )	base_lossr   :Some value(s) of y are out of the valid range of the loss .coef_)copyweightszL-BFGS-Bg     @@)maxiteriprintgtolftol)methodjacoptionsargsN)5r   r   numbersReal
isinstancer   bool
ValueErrorformatr   	__class____name__r   Integralr   r    r   _validate_datanpfloat64float32minmaxr1   r   r   shape	_get_loss
_base_lossr   r9   in_y_true_rangesumhasattrconcatenater<   array
intercept_astypezeroslinkaverageloss_gradientr   scipyoptimizeminimizefinfofloatepsr   n_iter_x)r"   Xysample_weightr   
loss_dtype	n_samples
n_featureslinear_losscoeffuncl2_reg_strength	n_threadsopt_resr#   r#   r$   fit   s   










z_GeneralizedLinearRegressor.fitc                 C   s:   t |  | j|g dtjtjgdddd}|| j | j S )a  Compute the linear_predictor = `X @ coef_ + intercept_`.

        Note that we often use the term raw_prediction instead of linear predictor.

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

        Returns
        -------
        y_pred : array of shape (n_samples,)
            Returns predicted values of linear predictor.
        )r/   r.   cooTF)r0   r1   r7   allow_ndreset)r   rR   rS   rT   rU   r<   r`   )r"   rn   r#   r#   r$   _linear_predictor3  s   
z-_GeneralizedLinearRegressor._linear_predictorc                 C   s   |  |}| jj|}|S )a*  Predict using GLM with feature matrix X.

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

        Returns
        -------
        y_pred : array of shape (n_samples,)
            Returns predicted values.
        )r~   rZ   rc   inverse)r"   rn   raw_predictiony_predr#   r#   r$   predictM  s   
z#_GeneralizedLinearRegressor.predictc           
      C   s   |  |}t||jddd}|durt|||jd}| j}||s+td|j dt	|j
|d}|durD||jd	 t| 9 }||||d
d}|jtj||d}||t||jd	 |d
d}	d
|| |	|   S )aJ  Compute D^2, the percentage of deviance explained.

        D^2 is a generalization of the coefficient of determination R^2.
        R^2 uses squared error and D^2 uses the deviance of this GLM, see the
        :ref:`User Guide <regression_metrics>`.

        D^2 is defined as
        :math:`D^2 = 1-\frac{D(y_{true},y_{pred})}{D_{null}}`,
        :math:`D_{null}` is the null deviance, i.e. the deviance of a model
        with intercept alone, which corresponds to :math:`y_{pred} = \bar{y}`.
        The mean :math:`\bar{y}` is averaged by sample_weight.
        Best possible score is 1.0 and it can be negative (because the model
        can be arbitrarily worse).

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

        y : array-like of shape (n_samples,)
            True values of target.

        sample_weight : array-like of shape (n_samples,), default=None
            Sample weights.

        Returns
        -------
        score : float
            D^2 of self.predict(X) w.r.t. y.
        r4   Fr5   Nr8   r:   r;   )y_truer   r,   )r   r   rp   rx   r>   )r~   r   r1   r   rZ   r[   rM   rP   rS   meanconstant_to_optimal_zerorX   r\   rc   rd   tile)
r"   rn   ro   rp   r   r9   constantdeviancey_meandeviance_nullr#   r#   r$   score_  s8   
%
z!_GeneralizedLinearRegressor.scorec                 C   s   |   }d|d iS )Nrequires_positive_yg      )rY   r[   )r"   r9   r#   r#   r$   
_more_tags  s   z&_GeneralizedLinearRegressor._more_tagsc                 C      t  S )a	  This is only necessary because of the link and power arguments of the
        TweedieRegressor.

        Note that we do not need to pass sample_weight to the loss class as this is
        only needed to set loss.constant_hessian on which GLMs do not rely.
        )r   r"   r#   r#   r$   rY     s   z%_GeneralizedLinearRegressor._get_losszLAttribute `family` was deprecated in version 1.1 and will be removed in 1.3.c                 C   s:   t | trdS t | trdS t | trt| jdS td)z:Ensure backward compatibility for the time of deprecation.poissongammapowerzThis should never happen. You presumably accessed the deprecated `family` attribute from a subclass of the private scikit-learn class _GeneralizedLinearRegressor.)rK   PoissonRegressorGammaRegressorTweedieRegressorr   r   rM   r   r#   r#   r$   family  s   


z"_GeneralizedLinearRegressor.familyr!   )rP   
__module____qualname____doc__r%   rz   r~   r   r   r   rY   r   propertyr   r#   r#   r#   r$   r      s,    a
 $
K
r   c                       8   e Zd ZdZddddddd fd	d

Zdd Z  ZS )r   a
  Generalized Linear Model with a Poisson distribution.

    This regressor uses the 'log' link function.

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

    .. versionadded:: 0.23

    Parameters
    ----------
    alpha : float, default=1
        Constant that multiplies the penalty term and thus determines the
        regularization strength. ``alpha = 0`` is equivalent to unpenalized
        GLMs. In this case, the design matrix `X` must have full column rank
        (no collinearities).
        Values must be in the range `[0.0, inf)`.

    fit_intercept : bool, default=True
        Specifies if a constant (a.k.a. bias or intercept) should be
        added to the linear predictor (X @ coef + intercept).

    max_iter : int, default=100
        The maximal number of iterations for the solver.
        Values must be in the range `[1, inf)`.

    tol : float, default=1e-4
        Stopping criterion. For the lbfgs solver,
        the iteration will stop when ``max{|g_j|, j = 1, ..., d} <= tol``
        where ``g_j`` is the j-th component of the gradient (derivative) of
        the objective function.
        Values must be in the range `(0.0, inf)`.

    warm_start : bool, default=False
        If set to ``True``, reuse the solution of the previous call to ``fit``
        as initialization for ``coef_`` and ``intercept_`` .

    verbose : int, default=0
        For the lbfgs solver set verbose to any positive number for verbosity.
        Values must be in the range `[0, inf)`.

    Attributes
    ----------
    coef_ : array of shape (n_features,)
        Estimated coefficients for the linear predictor (`X @ coef_ +
        intercept_`) in the GLM.

    intercept_ : float
        Intercept (a.k.a. bias) added to linear predictor.

    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

    n_iter_ : int
        Actual number of iterations used in the solver.

    See Also
    --------
    TweedieRegressor : Generalized Linear Model with a Tweedie distribution.

    Examples
    --------
    >>> from sklearn import linear_model
    >>> clf = linear_model.PoissonRegressor()
    >>> X = [[1, 2], [2, 3], [3, 4], [4, 3]]
    >>> y = [12, 17, 22, 21]
    >>> clf.fit(X, y)
    PoissonRegressor()
    >>> clf.score(X, y)
    0.990...
    >>> clf.coef_
    array([0.121..., 0.158...])
    >>> clf.intercept_
    2.088...
    >>> clf.predict([[1, 1], [3, 4]])
    array([10.676..., 21.875...])
    r   Tr   r   Fr   r   r   r   r   r   r    c                      t  j||||||d d S Nr   superr%   r"   r   r   r   r   r   r    rO   r#   r$   r%   %     

zPoissonRegressor.__init__c                 C   r   r!   )r   r   r#   r#   r$   rY   8     zPoissonRegressor._get_lossrP   r   r   r   r%   rY   __classcell__r#   r#   r   r$   r     s    Xr   c                       r   )r   a
  Generalized Linear Model with a Gamma distribution.

    This regressor uses the 'log' link function.

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

    .. versionadded:: 0.23

    Parameters
    ----------
    alpha : float, default=1
        Constant that multiplies the penalty term and thus determines the
        regularization strength. ``alpha = 0`` is equivalent to unpenalized
        GLMs. In this case, the design matrix `X` must have full column rank
        (no collinearities).
        Values must be in the range `[0.0, inf)`.

    fit_intercept : bool, default=True
        Specifies if a constant (a.k.a. bias or intercept) should be
        added to the linear predictor (X @ coef + intercept).

    max_iter : int, default=100
        The maximal number of iterations for the solver.
        Values must be in the range `[1, inf)`.

    tol : float, default=1e-4
        Stopping criterion. For the lbfgs solver,
        the iteration will stop when ``max{|g_j|, j = 1, ..., d} <= tol``
        where ``g_j`` is the j-th component of the gradient (derivative) of
        the objective function.
        Values must be in the range `(0.0, inf)`.

    warm_start : bool, default=False
        If set to ``True``, reuse the solution of the previous call to ``fit``
        as initialization for ``coef_`` and ``intercept_`` .

    verbose : int, default=0
        For the lbfgs solver set verbose to any positive number for verbosity.
        Values must be in the range `[0, inf)`.

    Attributes
    ----------
    coef_ : array of shape (n_features,)
        Estimated coefficients for the linear predictor (`X * coef_ +
        intercept_`) in the GLM.

    intercept_ : float
        Intercept (a.k.a. bias) added to linear predictor.

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

        .. versionadded:: 0.24

    n_iter_ : int
        Actual number of iterations used in the solver.

    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
    --------
    PoissonRegressor : Generalized Linear Model with a Poisson distribution.
    TweedieRegressor : Generalized Linear Model with a Tweedie distribution.

    Examples
    --------
    >>> from sklearn import linear_model
    >>> clf = linear_model.GammaRegressor()
    >>> X = [[1, 2], [2, 3], [3, 4], [4, 3]]
    >>> y = [19, 26, 33, 30]
    >>> clf.fit(X, y)
    GammaRegressor()
    >>> clf.score(X, y)
    0.773...
    >>> clf.coef_
    array([0.072..., 0.066...])
    >>> clf.intercept_
    2.896...
    >>> clf.predict([[1, 0], [2, 8]])
    array([19.483..., 35.795...])
    r   Tr   r   Fr   r   c                   r   r   r   r   r   r#   r$   r%     r   zGammaRegressor.__init__c                 C   r   r!   )r   r   r#   r#   r$   rY     r   zGammaRegressor._get_lossr   r#   r#   r   r$   r   <  s    Yr   c                	       s<   e Zd ZdZdddddddd	d
 fdd
Zdd Z  ZS )r   a<  Generalized Linear Model with a Tweedie distribution.

    This estimator can be used to model different GLMs depending on the
    ``power`` parameter, which determines the underlying distribution.

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

    .. versionadded:: 0.23

    Parameters
    ----------
    power : float, default=0
            The power determines the underlying target distribution according
            to the following table:

            +-------+------------------------+
            | Power | Distribution           |
            +=======+========================+
            | 0     | Normal                 |
            +-------+------------------------+
            | 1     | Poisson                |
            +-------+------------------------+
            | (1,2) | Compound Poisson Gamma |
            +-------+------------------------+
            | 2     | Gamma                  |
            +-------+------------------------+
            | 3     | Inverse Gaussian       |
            +-------+------------------------+

            For ``0 < power < 1``, no distribution exists.

    alpha : float, default=1
        Constant that multiplies the penalty term and thus determines the
        regularization strength. ``alpha = 0`` is equivalent to unpenalized
        GLMs. In this case, the design matrix `X` must have full column rank
        (no collinearities).
        Values must be in the range `[0.0, inf)`.

    fit_intercept : bool, default=True
        Specifies if a constant (a.k.a. bias or intercept) should be
        added to the linear predictor (X @ coef + intercept).

    link : {'auto', 'identity', 'log'}, default='auto'
        The link function of the GLM, i.e. mapping from linear predictor
        `X @ coeff + intercept` to prediction `y_pred`. Option 'auto' sets
        the link depending on the chosen `power` parameter as follows:

        - 'identity' for ``power <= 0``, e.g. for the Normal distribution
        - 'log' for ``power > 0``, e.g. for Poisson, Gamma and Inverse Gaussian
          distributions

    max_iter : int, default=100
        The maximal number of iterations for the solver.
        Values must be in the range `[1, inf)`.

    tol : float, default=1e-4
        Stopping criterion. For the lbfgs solver,
        the iteration will stop when ``max{|g_j|, j = 1, ..., d} <= tol``
        where ``g_j`` is the j-th component of the gradient (derivative) of
        the objective function.
        Values must be in the range `(0.0, inf)`.

    warm_start : bool, default=False
        If set to ``True``, reuse the solution of the previous call to ``fit``
        as initialization for ``coef_`` and ``intercept_`` .

    verbose : int, default=0
        For the lbfgs solver set verbose to any positive number for verbosity.
        Values must be in the range `[0, inf)`.

    Attributes
    ----------
    coef_ : array of shape (n_features,)
        Estimated coefficients for the linear predictor (`X @ coef_ +
        intercept_`) in the GLM.

    intercept_ : float
        Intercept (a.k.a. bias) added to linear predictor.

    n_iter_ : int
        Actual number of iterations used in the solver.

    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
    --------
    PoissonRegressor : Generalized Linear Model with a Poisson distribution.
    GammaRegressor : Generalized Linear Model with a Gamma distribution.

    Examples
    --------
    >>> from sklearn import linear_model
    >>> clf = linear_model.TweedieRegressor()
    >>> X = [[1, 2], [2, 3], [3, 4], [4, 3]]
    >>> y = [2, 3.5, 5, 5.5]
    >>> clf.fit(X, y)
    TweedieRegressor()
    >>> clf.score(X, y)
    0.839...
    >>> clf.coef_
    array([0.599..., 0.299...])
    >>> clf.intercept_
    1.600...
    >>> clf.predict([[1, 1], [3, 4]])
    array([2.500..., 4.599...])
    r&   r   Tautor   r   Fr   )r   r   r   rc   r   r   r   r    c          	         s(   t  j||||||d || _|| _d S r   )r   r%   rc   r   )	r"   r   r   r   rc   r   r   r   r    r   r#   r$   r%     s   
zTweedieRegressor.__init__c                 C   sj   | j dkr| jdkrt| jdS t| jdS | j dkr!t| jdS | j dkr,t| jdS td| j d)Nr   r   r   logidentityzFThe link must be an element of ['auto', 'identity', 'log']; got (link=))rc   r   r   r   rM   r   r#   r#   r$   rY   6  s   



zTweedieRegressor._get_lossr   r#   r#   r   r$   r     s    wr   )"r   rI   numpyrS   scipy.optimizerf   _loss.glm_distributionr   
_loss.lossr   r   r   r   r   baser	   r
   utils.optimizer   utilsr   r   r   utils.validationr   r   utils._openmp_helpersr   _linear_lossr   r   r   r   r   r#   r#   r#   r$   <module>   s&       4mn