
    0Ph@[                       d Z ddl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
 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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"m#Z#m$Z$ ddl%m&Z&m'Z' ddl(m)Z)m*Z*m+Z+m,Z,m-Z- ddl.m/Z/ ddl0m1Z1m2Z2 ddl3m4Z4m5Z5 ddl6m7Z7m8Z8m9Z9m:Z: ddl;m<Z<m=Z=m>Z> ddl?m@Z@ ddlAmBZB ddlCmDZD dZEd ZFd ZG	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d-d'ZHd( ZI G d) d*e=e>e<          ZJ G d+ d,eJe=e<          ZKdS ).z
Logistic Regression
    N)IntegralReal)effective_n_jobs)optimize)get_scorer_names   )HalfBinomialLossHalfMultinomialLoss)_fit_context)
get_scorer)check_cv)LabelBinarizerLabelEncoder)_fit_liblinear)Bunchcheck_arraycheck_consistent_lengthcheck_random_statecompute_class_weight)HiddenInterval
StrOptions)	row_normssoftmax)MetadataRouterMethodMapping_raise_for_params_routing_enabledprocess_routing)check_classification_targets)_check_optimize_result
_newton_cg)Paralleldelayed)_check_method_params_check_sample_weightcheck_is_fittedvalidate_data   )BaseEstimatorLinearClassifierMixinSparseCoefMixin)NewtonCholeskySolver)LinearModelLoss)
sag_solverzPlease also refer to the documentation for alternative solver options:
    https://scikit-learn.org/stable/modules/linear_model.html#logistic-regressionc                     | dvr|dvrt          d|  d| d          | dk    r|rt          d|  d|           |dk    r| d	k    rt          d
|  d          | dk    r|t          d          | S )N)	liblinearsaga)l2NzSolver z+ supports only 'l2' or None penalties, got z	 penalty.r1   z$ supports only dual=False, got dual=
elasticnetr2   z;Only 'saga' solver supports elasticnet penalty, got solver=.z6penalty=None is not supported for the liblinear solver
ValueError)solverpenaltyduals      ^/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sklearn/linear_model/_logistic.py_check_solverr<   =   s    ***wl/J/Jf     
 
 	
 U6UUtUUVVV,6V#3#3S&SSS
 
 	
 QRRRM    c                 n    | dk    r|dv rd} n|dk    rd} nd} | dk    r|dv rt          d|z            | S )zComputes the multi class type, either "multinomial" or "ovr".

    For `n_classes` > 2 and a solver that supports it, returns "multinomial".
    For all other cases, in particular binary classification, return "ovr".
    auto)r1   ovrr   multinomialz1Solver %s does not support a multinomial backend.r6   )multi_classr8   	n_classess      r;   _check_multi_classrD   Q   se     f^##KK]]'KKKm##.(@(@LvUVVVr=   
   Td   -C6?lbfgsFr3         ?r?   c                    t          |t          j                  rt          j        dd|          }t          |||          }|rAt          | dt          j        |dv          } t          |dd          }t          | |           | j	        \  }}t          j
        |          }t          |          }t          ||t          |                    }|(|d	k    r"|j        d
k    rt          d          |d         }||
t!          || | j        d          }t%                      }t          |
t&                    s|d	k    r2|
0t)          |
||          }|||                    |                   z  }|dk    rt          j        |t/          |          z   | j                  }||k    }t          j        |j	        | j                  }|dk    rt          j        ddg          }d|| <   nt          j        ddg          }d|| <   |
dk    r0t)          |
||          }|||                    |                   z  }n|dv r>t%                      }|                    |                              | j        d          }nMt7                      }|                    |          }|j	        d         dk    rt          j        d|z
  |g          }t          j        |j        |t/          |          z   fd| j                  }|dv r||nt          j        |          } |	|dk    r<|	j        ||j        fvrt          d|	j        ||j        fz            |	|d|	j        <   n|j        }!|!d
k    rd}!|	j	        d         |!k    s|	j	        d         ||dz   fvr;t          d|	j	        d         |	j	        d         |j        ||j        |dz   fz            |!dk    r*|	 |dd|	j	        d         f<   |	|dd|	j	        d         f<   n|	|ddd|	j	        d         f<   |d	k    rs|dv r|                    d          }t?          tA          |j                   |!          }"|}#|d"k    r|"j!        }$n|d#k    r|"j"        }$|"j#        }%|"j$        }&d$|j%        i}'n|}#|d"k    r%t?          tM                      |!          }"|"j!        }$n\|d#k    r3t?          tM                      |!          }"|"j"        }$|"j#        }%|"j$        }&n#|d%k    rt?          tM                      |!          }"d$t          j'        |d&          i}'tQ                      }(t          j        t          |          t          j)                  })tU          |          D ]\  }*}+|d"k    rd'|+| z  z  },g d(t          j+        t          j        g d)          |                   }-tY          j-        |$|d*d| |#||,|f|d+|-|d,t          j.        t^                    j0        z  d-.          }.tc          ||.|td          /          }/|.j3        |.j4        }"}n|d#k    r+d'|+| z  z  },| |#||,|f}0tk          |&|$|%||0|||0          \  }}/nQ|d%k    r?d'|+| z  z  },tm          ||"|,||||1          }1|17                    | |#|2          }|1j8        }/n|dk    rtts          | |#|+||d|||||||3          \  }2}3}/|r)t          j:        |2                                |3g          }n|2                                }|/;                                }/n|d4v r||d	k    r|#                    | j        d          }#d	}"nd5}"|d6k    rd}4d'|+z  }5n!|d7k    rd'|+z  }4d}5nd'|+z  d|z
  z  }4d'|+z  |z  }5ty          | |#||"|4|5||||d||'|d8k    9          \  }}/}'nt          d:|z            |d	k    rt{          d
|j                  }!|dv rt          j>        ||!dfd          }6n|}6|!d
k    r|6d         t          j?        ddf         }6|(@                    |6A                                           n'|(@                    |A                                           |/|)|*<   t          j        |(          t          j        |          |)fS );a  Compute a Logistic Regression model for a list of regularization
    parameters.

    This is an implementation that uses the result of the previous model
    to speed up computations along the set of solutions, making it faster
    than sequentially calling LogisticRegression for the different parameters.
    Note that there will be no speedup with liblinear solver, since it does
    not handle warm-starting.

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

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

    y : array-like of shape (n_samples,) or (n_samples, n_targets)
        Input data, target values.

    pos_class : int, default=None
        The class with respect to which we perform a one-vs-all fit.
        If None, then it is assumed that the given problem is binary.

    Cs : int or array-like of shape (n_cs,), default=10
        List of values for the regularization parameter or integer specifying
        the number of regularization parameters that should be used. In this
        case, the parameters will be chosen in a logarithmic scale between
        1e-4 and 1e4.

    fit_intercept : bool, default=True
        Whether to fit an intercept for the model. In this case the shape of
        the returned array is (n_cs, n_features + 1).

    max_iter : int, default=100
        Maximum number of iterations for the solver.

    tol : float, default=1e-4
        Stopping criterion. For the newton-cg and lbfgs solvers, the iteration
        will stop when ``max{|g_i | i = 1, ..., n} <= tol``
        where ``g_i`` is the i-th component of the gradient.

    verbose : int, default=0
        For the liblinear and lbfgs solvers set verbose to any positive
        number for verbosity.

    solver : {'lbfgs', 'liblinear', 'newton-cg', 'newton-cholesky', 'sag', 'saga'},             default='lbfgs'
        Numerical solver to use.

    coef : array-like of shape (n_features,), default=None
        Initialization value for coefficients of logistic regression.
        Useless for liblinear solver.

    class_weight : dict or 'balanced', default=None
        Weights associated with classes in the form ``{class_label: weight}``.
        If not given, all classes are supposed to have weight one.

        The "balanced" mode uses the values of y to automatically adjust
        weights inversely proportional to class frequencies in the input data
        as ``n_samples / (n_classes * np.bincount(y))``.

        Note that these weights will be multiplied with sample_weight (passed
        through the fit method) if sample_weight is specified.

    dual : bool, default=False
        Dual or primal formulation. Dual formulation is only implemented for
        l2 penalty with liblinear solver. Prefer dual=False when
        n_samples > n_features.

    penalty : {'l1', 'l2', 'elasticnet'}, default='l2'
        Used to specify the norm used in the penalization. The 'newton-cg',
        'sag' and 'lbfgs' solvers support only l2 penalties. 'elasticnet' is
        only supported by the 'saga' solver.

    intercept_scaling : float, default=1.
        Useful only when the solver 'liblinear' is used
        and self.fit_intercept is set to True. In this case, x becomes
        [x, self.intercept_scaling],
        i.e. a "synthetic" feature with constant value equal to
        intercept_scaling is appended to the instance vector.
        The intercept becomes ``intercept_scaling * synthetic_feature_weight``.

        Note! the synthetic feature weight is subject to l1/l2 regularization
        as all other features.
        To lessen the effect of regularization on synthetic feature weight
        (and therefore on the intercept) intercept_scaling has to be increased.

    multi_class : {'ovr', 'multinomial', 'auto'}, default='auto'
        If the option chosen is 'ovr', then a binary problem is fit for each
        label. For 'multinomial' the loss minimised is the multinomial loss fit
        across the entire probability distribution, *even when the data is
        binary*. 'multinomial' is unavailable when solver='liblinear'.
        'auto' selects 'ovr' if the data is binary, or if solver='liblinear',
        and otherwise selects 'multinomial'.

        .. versionadded:: 0.18
           Stochastic Average Gradient descent solver for 'multinomial' case.
        .. versionchanged:: 0.22
            Default changed from 'ovr' to 'auto' in 0.22.

    random_state : int, RandomState instance, default=None
        Used when ``solver`` == 'sag', 'saga' or 'liblinear' to shuffle the
        data. See :term:`Glossary <random_state>` for details.

    check_input : bool, default=True
        If False, the input arrays X and y will not be checked.

    max_squared_sum : float, default=None
        Maximum squared sum of X over samples. Used only in SAG solver.
        If None, it will be computed, going through all the samples.
        The value should be precomputed to speed up cross validation.

    sample_weight : array-like of shape(n_samples,), default=None
        Array of weights that are assigned to individual samples.
        If not provided, then each sample is given unit weight.

    l1_ratio : float, default=None
        The Elastic-Net mixing parameter, with ``0 <= l1_ratio <= 1``. Only
        used if ``penalty='elasticnet'``. Setting ``l1_ratio=0`` is equivalent
        to using ``penalty='l2'``, while setting ``l1_ratio=1`` is equivalent
        to using ``penalty='l1'``. For ``0 < l1_ratio <1``, the penalty is a
        combination of L1 and L2.

    n_threads : int, default=1
       Number of OpenMP threads to use.

    Returns
    -------
    coefs : ndarray of shape (n_cs, n_features) or (n_cs, n_features + 1)
        List of coefficients for the Logistic Regression model. If
        fit_intercept is set to True then the second dimension will be
        n_features + 1, where the last item represents the intercept. For
        ``multiclass='multinomial'``, the shape is (n_classes, n_cs,
        n_features) or (n_classes, n_cs, n_features + 1).

    Cs : ndarray
        Grid of Cs used for cross-validation.

    n_iter : array of shape (n_cs,)
        Actual number of iteration for each Cs.

    Notes
    -----
    You might get slightly different results with the solver liblinear than
    with the others since this uses LIBLINEAR which penalizes the intercept.

    .. versionchanged:: 0.19
        The "copy" parameter was removed.
       csrr1   sagr2   )accept_sparsedtypeaccept_large_sparseFN)	ensure_2drQ   rA   r   z&To fit OvR, use the pos_class argumentr)   T)rQ   copyclassesyr@   rQ   r1         r           balanced)rO   r2   rH   	newton-cgnewton-choleskyrT   F)orderrQ   rH   r]   r^   z;Initialization coef is of shape %d, expected shape %d or %dzMInitialization coef is of shape (%d, %d), expected shape (%d, %d) or (%d, %d))ra   )rC   )	base_lossfit_interceptrH   r]   coefr^   axisrI   )rY   2   r)   rF   e   )r   r)   r      zL-BFGS-Brh   @   )maxitermaxlsiprintgtolftol)methodjacargsoptions)extra_warning_msg)	grad_hessfuncgradx0rs   rl   tolverbose)re   linear_lossl2_reg_strengthrz   max_iter	n_threadsr{   )XrW   sample_weightr   rO   r2   logl1r3   r2   )is_sagazRsolver must be one of {'liblinear', 'lbfgs', 'newton-cg', 'sag'}, got '%s' instead)B
isinstancenumbersr   nplogspacer<   r   float64r   shapeuniquer   rD   lensizer7   r&   rQ   r   dictr   fit_transformzerosintonesarrayastyper   hstacksumravelr.   r
   loss_gradientlossgradientgradient_hessian_productTr	   expand_dimslistint32	enumeratesearchsortedr   minimizefinfofloatepsr!    _LOGISTIC_SOLVER_CONVERGENCE_MSGxfunr"   r-   solve	iterationr   concatenateitemr/   maxreshapenewaxisappendrT   )7r   rW   	pos_classCsrd   r~   rz   r{   r8   re   class_weightr:   r9   intercept_scalingrB   random_statecheck_inputmax_squared_sumr   l1_ratior   	n_samples
n_featuresrV   leclass_weight_w0masky_binmask_classesY_multilbinsw_sumrC   r   targetrw   rx   hesswarm_start_sagcoefsn_iteriCr}   rn   opt_resn_iter_irs   solcoef_
intercept_alphabetamulti_w0s7                                                          r;   _logistic_regression_pathr   c   sA
   X "g&'' $[Q##67D11F  &* &.J J	
 
 
 U$7771%%%GIzillG%l33L$[&#g,,GGK[M99<!EFFFAJ	 L$<,]AQWSWXXX
 
B,%% <}$$)A,\7aPPPr'7'7':':;; eXj3}#5#55QWEEEI~qw///[  8RG,,LE4%LL 8QF++LE4%L :%%0le  M ]2+;+;E+B+BCCM MMM
 B&&q))00u0EEGG "##D((++G}Q1$$)Q['$:;;X\:M(:(::;3ag
 
 
 ::: ,39N9N%yRW 555 Qy*bg67   #B{{OO  IA~~	z!}	))TZ]QC . . !1 
1
1""Q	   A~~*.1o
1o%&)-1o
1o%&&)-111o
1o%&m##>>>
 $$B)GLAAA'
 
 
 W%DD{""9D=D0D "$W"*,,M  D %DD{"""*,,M  D 9D=D0DD((("*,,M  D !".!"<"<"<=FFEXc"ggRX...F" E E1W!QZ0O*** 6 6@@F '!K'$%!44   G ."B	  H y'+BB{""!QZ0Ov}oyID% 	 	 	LB (((!QZ0O&  /!#  C Q&FFB}HH{""
 !+  	   #^U[[]]J$?@@[[]]  }}HH&&m++qwU;;$$QwDaqQ\2a8++56), , ,(B..$ 8:@A  
 -''Aw|,,IBBB:b9b/EEEA~~#A;rz111}5LL))))LL###q		8E??BHRLL&00r=   c                    | |         }| |         }||         }||         }d\  }}| t          ||           }||         }||         }t          ||fi d|d|d|d|d|d|
d	|d
|d|	d|d|d|d|d|ddd|d|\  }}}t          ||          }|dk    rt          j        ddg          |_        n2|dk    rt          j        |          |_        nt          d|z            |1||k    }t          j        |j	        t          j
                  }d|| <   t                      } t          |          }|D ]}!|dk    r|!t          j        ddf         }!|r%|!ddddf         |_        |!dddf         |_        n|!|_        d|_        |,|                     |                    |||                     |pi }t%          | ||          }|                      ||||fi |           ||t          j        |           |fS ) a#  Computes scores across logistic_regression_path

    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 labels.

    train : list of indices
        The indices of the train set.

    test : list of indices
        The indices of the test set.

    pos_class : int
        The class with respect to which we perform a one-vs-all fit.
        If None, then it is assumed that the given problem is binary.

    Cs : int or list of floats
        Each of the values in Cs describes the inverse of
        regularization strength. If Cs is as an int, then a grid of Cs
        values are chosen in a logarithmic scale between 1e-4 and 1e4.

    scoring : callable
        A string (see :ref:`scoring_parameter`) or
        a scorer callable object / function with signature
        ``scorer(estimator, X, y)``. For a list of scoring functions
        that can be used, look at :mod:`sklearn.metrics`.

    fit_intercept : bool
        If False, then the bias term is set to zero. Else the last
        term of each coef_ gives us the intercept.

    max_iter : int
        Maximum number of iterations for the solver.

    tol : float
        Tolerance for stopping criteria.

    class_weight : dict or 'balanced'
        Weights associated with classes in the form ``{class_label: weight}``.
        If not given, all classes are supposed to have weight one.

        The "balanced" mode uses the values of y to automatically adjust
        weights inversely proportional to class frequencies in the input data
        as ``n_samples / (n_classes * np.bincount(y))``

        Note that these weights will be multiplied with sample_weight (passed
        through the fit method) if sample_weight is specified.

    verbose : int
        For the liblinear and lbfgs solvers set verbose to any positive
        number for verbosity.

    solver : {'lbfgs', 'liblinear', 'newton-cg', 'newton-cholesky', 'sag', 'saga'}
        Decides which solver to use.

    penalty : {'l1', 'l2', 'elasticnet'}
        Used to specify the norm used in the penalization. The 'newton-cg',
        'sag' and 'lbfgs' solvers support only l2 penalties. 'elasticnet' is
        only supported by the 'saga' solver.

    dual : bool
        Dual or primal formulation. Dual formulation is only implemented for
        l2 penalty with liblinear solver. Prefer dual=False when
        n_samples > n_features.

    intercept_scaling : float
        Useful only when the solver 'liblinear' is used
        and self.fit_intercept is set to True. In this case, x becomes
        [x, self.intercept_scaling],
        i.e. a "synthetic" feature with constant value equals to
        intercept_scaling is appended to the instance vector.
        The intercept becomes intercept_scaling * synthetic feature weight
        Note! the synthetic feature weight is subject to l1/l2 regularization
        as all other features.
        To lessen the effect of regularization on synthetic feature weight
        (and therefore on the intercept) intercept_scaling has to be increased.

    multi_class : {'auto', 'ovr', 'multinomial'}
        If the option chosen is 'ovr', then a binary problem is fit for each
        label. For 'multinomial' the loss minimised is the multinomial loss fit
        across the entire probability distribution, *even when the data is
        binary*. 'multinomial' is unavailable when solver='liblinear'.

    random_state : int, RandomState instance
        Used when ``solver`` == 'sag', 'saga' or 'liblinear' to shuffle the
        data. See :term:`Glossary <random_state>` for details.

    max_squared_sum : float
        Maximum squared sum of X over samples. Used only in SAG solver.
        If None, it will be computed, going through all the samples.
        The value should be precomputed to speed up cross validation.

    sample_weight : array-like of shape(n_samples,)
        Array of weights that are assigned to individual samples.
        If not provided, then each sample is given unit weight.

    l1_ratio : float
        The Elastic-Net mixing parameter, with ``0 <= l1_ratio <= 1``. Only
        used if ``penalty='elasticnet'``. Setting ``l1_ratio=0`` is equivalent
        to using ``penalty='l2'``, while setting ``l1_ratio=1`` is equivalent
        to using ``penalty='l1'``. For ``0 < l1_ratio <1``, the penalty is a
        combination of L1 and L2.

    score_params : dict
        Parameters to pass to the `score` method of the underlying scorer.

    Returns
    -------
    coefs : ndarray of shape (n_cs, n_features) or (n_cs, n_features + 1)
        List of coefficients for the Logistic Regression model. If
        fit_intercept is set to True then the second dimension will be
        n_features + 1, where the last item represents the intercept.

    Cs : ndarray
        Grid of Cs used for cross-validation.

    scores : ndarray of shape (n_cs,)
        Scores obtained for each Cs.

    n_iter : ndarray of shape(n_cs,)
        Actual number of iteration for each Cs.
    )NNNr   r   rd   r8   r~   r   r   rB   rz   r{   r:   r9   r   r   r   Fr   r   )r8   rB   r@   rY   r)   rA   z7multi_class should be either multinomial or ovr, got %drX   rZ   r[   r   )r   paramsindices)r&   r   LogisticRegressionr   r   classes_r   r7   r   r   r   r   r   r   r   r   r   scorer%   )"r   rW   traintestr   r   scoringrd   r~   rz   r   r{   r8   r9   r:   r   rB   r   r   r   r   score_paramsX_trainX_testy_trainy_testsw_trainsw_testr   r   log_regr   scoresws"                                     r;   _log_reg_scoring_pathr   H  s   n hGtWFhGtWF"Hg ,]A>> '%1   2 	
 $m v  "\ )  K C  T  ,+  "\!" E#$ (%& h'E2v, !KHHHG e8RG,,		%	%9W--ES
 
 	
 "RZ888uVVF!!G L L%"*aaa- A 	%aaa"fIGM!"111b5GGM!$G?MM'--g-NNOOOO'-2L/!LRVWWWLMM'''66JJ\JJKKKK"bhv&&..r=   c                       e Zd ZU dZ eh d          dgdg eeddd          g eeddd          gdg eeddd	          ge ed
h          dgdg eh d          g eeddd          gdgdgdeg eeddd          dg eh d           e	 edh                    gdZ
eed<   	 d"ddddddddddddddddZ ed          d#d            Z fdZd  Z fd!Z xZS )$r   a3  
    Logistic Regression (aka logit, MaxEnt) classifier.

    This class implements regularized logistic regression using the
    'liblinear' library, 'newton-cg', 'sag', 'saga' and 'lbfgs' solvers. **Note
    that regularization is applied by default**. It can handle both dense
    and sparse input. Use C-ordered arrays or CSR matrices containing 64-bit
    floats for optimal performance; any other input format will be converted
    (and copied).

    The 'newton-cg', 'sag', and 'lbfgs' solvers support only L2 regularization
    with primal formulation, or no regularization. The 'liblinear' solver
    supports both L1 and L2 regularization, with a dual formulation only for
    the L2 penalty. The Elastic-Net regularization is only supported by the
    'saga' solver.

    For :term:`multiclass` problems, only 'newton-cg', 'sag', 'saga' and 'lbfgs'
    handle multinomial loss. 'liblinear' and 'newton-cholesky' only handle binary
    classification but can be extended to handle multiclass by using
    :class:`~sklearn.multiclass.OneVsRestClassifier`.

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

    Parameters
    ----------
    penalty : {'l1', 'l2', 'elasticnet', None}, default='l2'
        Specify the norm of the penalty:

        - `None`: no penalty is added;
        - `'l2'`: add a L2 penalty term and it is the default choice;
        - `'l1'`: add a L1 penalty term;
        - `'elasticnet'`: both L1 and L2 penalty terms are added.

        .. warning::
           Some penalties may not work with some solvers. See the parameter
           `solver` below, to know the compatibility between the penalty and
           solver.

        .. versionadded:: 0.19
           l1 penalty with SAGA solver (allowing 'multinomial' + L1)

    dual : bool, default=False
        Dual (constrained) or primal (regularized, see also
        :ref:`this equation <regularized-logistic-loss>`) formulation. Dual formulation
        is only implemented for l2 penalty with liblinear solver. Prefer dual=False when
        n_samples > n_features.

    tol : float, default=1e-4
        Tolerance for stopping criteria.

    C : float, default=1.0
        Inverse of regularization strength; must be a positive float.
        Like in support vector machines, smaller values specify stronger
        regularization.

    fit_intercept : bool, default=True
        Specifies if a constant (a.k.a. bias or intercept) should be
        added to the decision function.

    intercept_scaling : float, default=1
        Useful only when the solver 'liblinear' is used
        and self.fit_intercept is set to True. In this case, x becomes
        [x, self.intercept_scaling],
        i.e. a "synthetic" feature with constant value equal to
        intercept_scaling is appended to the instance vector.
        The intercept becomes ``intercept_scaling * synthetic_feature_weight``.

        Note! the synthetic feature weight is subject to l1/l2 regularization
        as all other features.
        To lessen the effect of regularization on synthetic feature weight
        (and therefore on the intercept) intercept_scaling has to be increased.

    class_weight : dict or 'balanced', default=None
        Weights associated with classes in the form ``{class_label: weight}``.
        If not given, all classes are supposed to have weight one.

        The "balanced" mode uses the values of y to automatically adjust
        weights inversely proportional to class frequencies in the input data
        as ``n_samples / (n_classes * np.bincount(y))``.

        Note that these weights will be multiplied with sample_weight (passed
        through the fit method) if sample_weight is specified.

        .. versionadded:: 0.17
           *class_weight='balanced'*

    random_state : int, RandomState instance, default=None
        Used when ``solver`` == 'sag', 'saga' or 'liblinear' to shuffle the
        data. See :term:`Glossary <random_state>` for details.

    solver : {'lbfgs', 'liblinear', 'newton-cg', 'newton-cholesky', 'sag', 'saga'},             default='lbfgs'

        Algorithm to use in the optimization problem. Default is 'lbfgs'.
        To choose a solver, you might want to consider the following aspects:

        - For small datasets, 'liblinear' is a good choice, whereas 'sag'
          and 'saga' are faster for large ones;
        - For :term:`multiclass` problems, all solvers except 'liblinear' minimize the
          full multinomial loss;
        - 'liblinear' can only handle binary classification by default. To apply a
          one-versus-rest scheme for the multiclass setting one can wrap it with the
          :class:`~sklearn.multiclass.OneVsRestClassifier`.
        - 'newton-cholesky' is a good choice for
          `n_samples` >> `n_features * n_classes`, especially with one-hot encoded
          categorical features with rare categories. Be aware that the memory usage
          of this solver has a quadratic dependency on `n_features * n_classes`
          because it explicitly computes the full Hessian matrix.

        .. warning::
           The choice of the algorithm depends on the penalty chosen and on
           (multinomial) multiclass support:

           ================= ============================== ======================
           solver            penalty                        multinomial multiclass
           ================= ============================== ======================
           'lbfgs'           'l2', None                     yes
           'liblinear'       'l1', 'l2'                     no
           'newton-cg'       'l2', None                     yes
           'newton-cholesky' 'l2', None                     no
           'sag'             'l2', None                     yes
           'saga'            'elasticnet', 'l1', 'l2', None yes
           ================= ============================== ======================

        .. note::
           'sag' and 'saga' fast convergence is only guaranteed on features
           with approximately the same scale. You can preprocess the data with
           a scaler from :mod:`sklearn.preprocessing`.

        .. seealso::
           Refer to the :ref:`User Guide <Logistic_regression>` for more
           information regarding :class:`LogisticRegression` and more specifically the
           :ref:`Table <logistic_regression_solvers>`
           summarizing solver/penalty supports.

        .. versionadded:: 0.17
           Stochastic Average Gradient descent solver.
        .. versionadded:: 0.19
           SAGA solver.
        .. versionchanged:: 0.22
            The default solver changed from 'liblinear' to 'lbfgs' in 0.22.
        .. versionadded:: 1.2
           newton-cholesky solver.

    max_iter : int, default=100
        Maximum number of iterations taken for the solvers to converge.

    multi_class : {'auto', 'ovr', 'multinomial'}, default='auto'
        If the option chosen is 'ovr', then a binary problem is fit for each
        label. For 'multinomial' the loss minimised is the multinomial loss fit
        across the entire probability distribution, *even when the data is
        binary*. 'multinomial' is unavailable when solver='liblinear'.
        'auto' selects 'ovr' if the data is binary, or if solver='liblinear',
        and otherwise selects 'multinomial'.

        .. versionadded:: 0.18
           Stochastic Average Gradient descent solver for 'multinomial' case.
        .. versionchanged:: 0.22
            Default changed from 'ovr' to 'auto' in 0.22.
        .. deprecated:: 1.5
           ``multi_class`` was deprecated in version 1.5 and will be removed in 1.7.
           From then on, the recommended 'multinomial' will always be used for
           `n_classes >= 3`.
           Solvers that do not support 'multinomial' will raise an error.
           Use `sklearn.multiclass.OneVsRestClassifier(LogisticRegression())` if you
           still want to use OvR.

    verbose : int, default=0
        For the liblinear and lbfgs solvers set verbose to any positive
        number for verbosity.

    warm_start : bool, default=False
        When set to True, reuse the solution of the previous call to fit as
        initialization, otherwise, just erase the previous solution.
        Useless for liblinear solver. See :term:`the Glossary <warm_start>`.

        .. versionadded:: 0.17
           *warm_start* to support *lbfgs*, *newton-cg*, *sag*, *saga* solvers.

    n_jobs : int, default=None
        Number of CPU cores used when parallelizing over classes if
        multi_class='ovr'". This parameter is ignored when the ``solver`` is
        set to 'liblinear' regardless of whether 'multi_class' is specified or
        not. ``None`` means 1 unless in a :obj:`joblib.parallel_backend`
        context. ``-1`` means using all processors.
        See :term:`Glossary <n_jobs>` for more details.

    l1_ratio : float, default=None
        The Elastic-Net mixing parameter, with ``0 <= l1_ratio <= 1``. Only
        used if ``penalty='elasticnet'``. Setting ``l1_ratio=0`` is equivalent
        to using ``penalty='l2'``, while setting ``l1_ratio=1`` is equivalent
        to using ``penalty='l1'``. For ``0 < l1_ratio <1``, the penalty is a
        combination of L1 and L2.

    Attributes
    ----------

    classes_ : ndarray of shape (n_classes, )
        A list of class labels known to the classifier.

    coef_ : ndarray of shape (1, n_features) or (n_classes, n_features)
        Coefficient of the features in the decision function.

        `coef_` is of shape (1, n_features) when the given problem is binary.
        In particular, when `multi_class='multinomial'`, `coef_` corresponds
        to outcome 1 (True) and `-coef_` corresponds to outcome 0 (False).

    intercept_ : ndarray of shape (1,) or (n_classes,)
        Intercept (a.k.a. bias) added to the decision function.

        If `fit_intercept` is set to False, the intercept is set to zero.
        `intercept_` is of shape (1,) when the given problem is binary.
        In particular, when `multi_class='multinomial'`, `intercept_`
        corresponds to outcome 1 (True) and `-intercept_` corresponds to
        outcome 0 (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

    n_iter_ : ndarray of shape (n_classes,) or (1, )
        Actual number of iterations for all classes. If binary or multinomial,
        it returns only 1 element. For liblinear solver, only the maximum
        number of iteration across all classes is given.

        .. versionchanged:: 0.20

            In SciPy <= 1.0.0 the number of lbfgs iterations may exceed
            ``max_iter``. ``n_iter_`` will now report at most ``max_iter``.

    See Also
    --------
    SGDClassifier : Incrementally trained logistic regression (when given
        the parameter ``loss="log_loss"``).
    LogisticRegressionCV : Logistic regression with built-in cross validation.

    Notes
    -----
    The underlying C implementation uses a random number generator to
    select features when fitting the model. It is thus not uncommon,
    to have slightly different results for the same input data. If
    that happens, try with a smaller tol parameter.

    Predict output may not match that of standalone liblinear in certain
    cases. See :ref:`differences from liblinear <liblinear_differences>`
    in the narrative documentation.

    References
    ----------

    L-BFGS-B -- Software for Large-scale Bound-constrained Optimization
        Ciyou Zhu, Richard Byrd, Jorge Nocedal and Jose Luis Morales.
        http://users.iems.northwestern.edu/~nocedal/lbfgsb.html

    LIBLINEAR -- A Library for Large Linear Classification
        https://www.csie.ntu.edu.tw/~cjlin/liblinear/

    SAG -- Mark Schmidt, Nicolas Le Roux, and Francis Bach
        Minimizing Finite Sums with the Stochastic Average Gradient
        https://hal.inria.fr/hal-00860051/document

    SAGA -- Defazio, A., Bach F. & Lacoste-Julien S. (2014).
            :arxiv:`"SAGA: A Fast Incremental Gradient Method With Support
            for Non-Strongly Convex Composite Objectives" <1407.0202>`

    Hsiang-Fu Yu, Fang-Lan Huang, Chih-Jen Lin (2011). Dual coordinate descent
        methods for logistic regression and maximum entropy models.
        Machine Learning 85(1-2):41-75.
        https://www.csie.ntu.edu.tw/~cjlin/papers/maxent_dual.pdf

    Examples
    --------
    >>> from sklearn.datasets import load_iris
    >>> from sklearn.linear_model import LogisticRegression
    >>> X, y = load_iris(return_X_y=True)
    >>> clf = LogisticRegression(random_state=0).fit(X, y)
    >>> clf.predict(X[:2, :])
    array([0, 0])
    >>> clf.predict_proba(X[:2, :])
    array([[9.8...e-01, 1.8...e-02, 1.4...e-08],
           [9.7...e-01, 2.8...e-02, ...e-08]])
    >>> clf.score(X, y)
    0.97...

    For a comaprison of the LogisticRegression with other classifiers see:
    :ref:`sphx_glr_auto_examples_classification_plot_classification_probability.py`.
    >   r   r3   r4   Nbooleanr   leftclosedrightneitherr\   r   >   rO   r2   rH   r1   r]   r^   r{   r)   both>   r@   r?   rA   
deprecated)r9   r:   rz   r   rd   r   r   r   r8   r~   r{   
warm_startn_jobsr   rB   _parameter_constraintsr3   FrG   rI   TrH   rF   )r:   rz   r   rd   r   r   r   r8   r~   rB   r{   r   r   r   c                    || _         || _        || _        || _        || _        || _        || _        || _        |	| _        |
| _	        || _
        || _        || _        || _        || _        d S N)r9   r:   rz   r   rd   r   r   r   r8   r~   rB   r{   r   r   r   )selfr9   r:   rz   r   rd   r   r   r   r8   r~   rB   r{   r   r   r   s                   r;   __init__zLogisticRegression.__init__h  sv    & 	*!2(( &$ r=   prefer_skip_nested_validationc                 j
    t           j         j         j                   j        dk    r3 j        ,t          j        d                     j                              j        dk    r j        t          d           j        . j	        dk    rt          j        d           t          j        dn j	         j        dk    rt          j        }nt          j        t          j        g}t           d	|d
dv          \  t                     t          j                   _         j         j        dk    r3t'           j                  dk    rt          j        dt(                     nL j        dv rt          j        dt(                     n( j        dk    rt          j        dt(                     ndt+          t'           j                            dk    rt-           j                  dk    r9t          j        d                    t-           j                                       t1           j	         j         j         j         j         j         j         j         j         j                  \   _          _!         _"         S dv r$tG          d          $                                ndt'           j                  } j        }|dk     rt          d|d         z            t'           j                  dk    rd}|dd         } j%        rtM           dd          }nd}|7 j        r0t          j'        | j!        ddt          j(        f         d          }dk    rdg}|g}|dg|z  }tS          tT                    dv rd }nd!}d"v r.t'          |          dk    rt-           j                  dk    rdnd tW           j         j        |#           fd$tY          ||          D                       }	tY          |	 \  }	}
}t          j-        |t          j.        %          dddf          _"        j/        d         }dk    r|	d         d          _         nNt          j-        |	           _          j         0                    ||tc           j                  z              _          j        r/ j         ddd&f          _!         j         dddd&f          _         nt          j2        |           _!         S )'an  
        Fit the model according to the given training data.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            Training vector, where `n_samples` is the number of samples and
            `n_features` is the number of features.

        y : array-like of shape (n_samples,)
            Target vector relative to X.

        sample_weight : array-like of shape (n_samples,) default=None
            Array of weights that are assigned to individual samples.
            If not provided, then each sample is given unit weight.

            .. versionadded:: 0.17
               *sample_weight* support to LogisticRegression.

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

        Notes
        -----
        The SAGA solver supports both float64 and float32 bit arrays.
        r4   NzNl1_ratio parameter is only used when penalty is 'elasticnet'. Got (penalty={})z6l1_ratio must be specified when penalty is elasticnet.rI   z>Setting penalty=None will ignore the C and l1_ratio parametersr3   rH   rM   r   rN   rP   rQ   ra   rR   rA   r   'multi_class' was deprecated in version 1.5 and will be removed in 1.7. From then on, binary problems will be fit as proper binary  logistic regression models (as if multi_class='ovr' were set). Leave it to its default value to avoid this warning.rA   r?   'multi_class' was deprecated in version 1.5 and will be removed in 1.7. From then on, it will always use 'multinomial'. Leave it to its default value to avoid this warning.r@   z'multi_class' was deprecated in version 1.5 and will be removed in 1.7. Use OneVsRestClassifier(LogisticRegression(..)) instead. Leave it to its default value to avoid this warning.r?   r1   r)   z]'n_jobs' > 1 does not have any effect when 'solver' is set to 'liblinear'. Got 'n_jobs' = {}.r   r   TsquaredeThis solver needs samples of at least 2 classes in the data, but the data contains only one class: %rr   r   rf   threads	processesrb   r   r{   preferc              3      K   | ]f\  }} fi d |dgdj         dj        dj        dj        dddj        d	j        d
ddj        d|d	dd
dV  gdS )r   r   r   rd   rz   r{   r8   rB   r~   r   r   Fr   re   r9   r   r   r   N)r   rd   rz   r{   r~   r   r   ).0class_warm_start_coef_C_r   r   rB   r   	path_funcr9   r   r   r8   rW   s      r;   	<genexpr>z)LogisticRegression.fit.<locals>.<genexpr>F  s@      X
 X
, )(+ I   !& 44	
  #00 HH  v (K  ".. "E ".. &%   !" !0#$ ,m%& $)'X
 X
 X
 X
 X
 X
r=   rX   rY   )3r<   r8   r9   r:   r   warningswarnformatr7   r   r   infr   float32r(   r    r   r   rB   r   FutureWarningrD   r   r   r   rd   r   r   r{   r~   rz   r   r   r   n_iter_r   r   r   getattrr   r   r$   r   r#   zipasarrayr   r   r   r   r   )r   r   rW   r   _dtyperC   r   warm_start_coefr  fold_coefs__r  r   r  r   rB   r   r  r9   r8   s   ````         @@@@@@@r;   fitzLogisticRegression.fit  s   < t{DL$)DD<<''DM,EM%vdl33   <<''DM,AUVVV<v}}T   BGGBlGWZFFj"*-F &.J J
 
 
1 	%Q'''	! &},,T]1C1Cq1H1HML
     !888ML     &&ML     !K(fc$->P>PQQ[  ,,11#V$4T[$A$ABB  
 9G"&!	!+9 9 95DJ K_$$'4888<<>>OO"O&&	=q=='{+   t}""I|H? 	#%dGT::OO"O&4+=& iBJ!?a  O
 -''vH./O"#fy0O566	 _$$FF F ???H"" --22 IIIWhdk4<PVWWW X
 X
 X
 X
 X
 X
 X
 X
 X
 X
 X
 X
 X
 X
, -0/,J,J-X
 X
 X
 
 
2 #&{"3Qz':::111a4@WQZ
-''$Q*DJJK00DJ++:D,>(?(?? DJ  	2"jB/DOAAAssF+DJJ hy11DOr=   c                 T   t          |            | j        dv p#| j        dv o| j        j        dk    p
| j        dk    }|r!t                                          |          S |                     |          }|j        dk    rt          j
        | |f         }n|}t          |d          S )a  
        Probability estimates.

        The returned estimates for all classes are ordered by the
        label of classes.

        For a multi_class problem, if multi_class is set to be "multinomial"
        the softmax function is used to find the predicted probability of
        each class.
        Else use a one-vs-rest approach, i.e. calculate the probability
        of each class assuming it to be positive using the logistic function
        and normalize these values across all the classes.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            Vector to be scored, where `n_samples` is the number of samples and
            `n_features` is the number of features.

        Returns
        -------
        T : array-like of shape (n_samples, n_classes)
            Returns the probability of the sample for each class in the model,
            where classes are ordered as they are in ``self.classes_``.
        )r@   r  )r?   r   r   r1   r)   Fr_   )r'   rB   r   r   r8   super_predict_proba_lrdecision_functionndimr   c_r   )r   r   r@   decisiondecision_2d	__class__s        r;   predict_probaz LogisticRegression.predict_probas  s    4 	/1 
 66 H#q(FDK;,F 	  
	477,,Q///--a00H}!! !eXIx$78&;U3333r=   c                 P    t          j        |                     |                    S )ap  
        Predict logarithm of probability estimates.

        The returned estimates for all classes are ordered by the
        label of classes.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            Vector to be scored, where `n_samples` is the number of samples and
            `n_features` is the number of features.

        Returns
        -------
        T : array-like of shape (n_samples, n_classes)
            Returns the log-probability of the sample for each class in the
            model, where classes are ordered as they are in ``self.classes_``.
        )r   r   r'  )r   r   s     r;   predict_log_probaz$LogisticRegression.predict_log_proba  s"    & vd((++,,,r=   c                 `    t                                                      }d|j        _        |S NTr  __sklearn_tags__
input_tagssparser   tagsr&  s     r;   r-  z#LogisticRegression.__sklearn_tags__  '    ww''))!%r=   )r3   r   )__name__
__module____qualname____doc__r   r   r   r   r   r   r   __annotations__r   r   r  r'  r)  r-  __classcell__r&  s   @r;   r   r   '  s4        e eP	 J999::DAq$v6667htQW5556#&htQYGGGHzz:,77>'(JUUU 

 Xh4???@; k"XdAq888$?J55566F::|n--..
'$ $D   6 !! 
 #!! !! !! !! !!F \555e e e 65eN*4 *4 *4 *4 *4X- - -*        r=   r   c                       e Zd ZU dZi ej        Zeed<   dD ]Ze	                    e           e
                     eeddd          dgd	g e e e                                edgddgd
g eh d          gd           dddddddddddddddddddZ ed          dd            ZddZd Zd Z fdZ xZS ) LogisticRegressionCVa95  Logistic Regression CV (aka logit, MaxEnt) classifier.

    See glossary entry for :term:`cross-validation estimator`.

    This class implements logistic regression using liblinear, newton-cg, sag
    or lbfgs optimizer. The newton-cg, sag and lbfgs solvers support only L2
    regularization with primal formulation. The liblinear solver supports both
    L1 and L2 regularization, with a dual formulation only for the L2 penalty.
    Elastic-Net penalty is only supported by the saga solver.

    For the grid of `Cs` values and `l1_ratios` values, the best hyperparameter
    is selected by the cross-validator
    :class:`~sklearn.model_selection.StratifiedKFold`, but it can be changed
    using the :term:`cv` parameter. The 'newton-cg', 'sag', 'saga' and 'lbfgs'
    solvers can warm-start the coefficients (see :term:`Glossary<warm_start>`).

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

    Parameters
    ----------
    Cs : int or list of floats, default=10
        Each of the values in Cs describes the inverse of regularization
        strength. If Cs is as an int, then a grid of Cs values are chosen
        in a logarithmic scale between 1e-4 and 1e4.
        Like in support vector machines, smaller values specify stronger
        regularization.

    fit_intercept : bool, default=True
        Specifies if a constant (a.k.a. bias or intercept) should be
        added to the decision function.

    cv : int or cross-validation generator, default=None
        The default cross-validation generator used is Stratified K-Folds.
        If an integer is provided, then it is the number of folds used.
        See the module :mod:`sklearn.model_selection` module for the
        list of possible cross-validation objects.

        .. versionchanged:: 0.22
            ``cv`` default value if None changed from 3-fold to 5-fold.

    dual : bool, default=False
        Dual (constrained) or primal (regularized, see also
        :ref:`this equation <regularized-logistic-loss>`) formulation. Dual formulation
        is only implemented for l2 penalty with liblinear solver. Prefer dual=False when
        n_samples > n_features.

    penalty : {'l1', 'l2', 'elasticnet'}, default='l2'
        Specify the norm of the penalty:

        - `'l2'`: add a L2 penalty term (used by default);
        - `'l1'`: add a L1 penalty term;
        - `'elasticnet'`: both L1 and L2 penalty terms are added.

        .. warning::
           Some penalties may not work with some solvers. See the parameter
           `solver` below, to know the compatibility between the penalty and
           solver.

    scoring : str or callable, default=None
        A string (see :ref:`scoring_parameter`) or
        a scorer callable object / function with signature
        ``scorer(estimator, X, y)``. For a list of scoring functions
        that can be used, look at :mod:`sklearn.metrics`. The
        default scoring option used is 'accuracy'.

    solver : {'lbfgs', 'liblinear', 'newton-cg', 'newton-cholesky', 'sag', 'saga'},             default='lbfgs'

        Algorithm to use in the optimization problem. Default is 'lbfgs'.
        To choose a solver, you might want to consider the following aspects:

        - For small datasets, 'liblinear' is a good choice, whereas 'sag'
          and 'saga' are faster for large ones;
        - For multiclass problems, all solvers except 'liblinear' minimize the full
          multinomial loss;
        - 'liblinear' might be slower in :class:`LogisticRegressionCV`
          because it does not handle warm-starting.
        - 'liblinear' can only handle binary classification by default. To apply a
          one-versus-rest scheme for the multiclass setting one can wrap it with the
          :class:`~sklearn.multiclass.OneVsRestClassifier`.
        - 'newton-cholesky' is a good choice for
          `n_samples` >> `n_features * n_classes`, especially with one-hot encoded
          categorical features with rare categories. Be aware that the memory usage
          of this solver has a quadratic dependency on `n_features * n_classes`
          because it explicitly computes the full Hessian matrix.

        .. warning::
           The choice of the algorithm depends on the penalty chosen and on
           (multinomial) multiclass support:

           ================= ============================== ======================
           solver            penalty                        multinomial multiclass
           ================= ============================== ======================
           'lbfgs'           'l2'                           yes
           'liblinear'       'l1', 'l2'                     no
           'newton-cg'       'l2'                           yes
           'newton-cholesky' 'l2',                          no
           'sag'             'l2',                          yes
           'saga'            'elasticnet', 'l1', 'l2'       yes
           ================= ============================== ======================

        .. note::
           'sag' and 'saga' fast convergence is only guaranteed on features
           with approximately the same scale. You can preprocess the data with
           a scaler from :mod:`sklearn.preprocessing`.

        .. versionadded:: 0.17
           Stochastic Average Gradient descent solver.
        .. versionadded:: 0.19
           SAGA solver.
        .. versionadded:: 1.2
           newton-cholesky solver.

    tol : float, default=1e-4
        Tolerance for stopping criteria.

    max_iter : int, default=100
        Maximum number of iterations of the optimization algorithm.

    class_weight : dict or 'balanced', default=None
        Weights associated with classes in the form ``{class_label: weight}``.
        If not given, all classes are supposed to have weight one.

        The "balanced" mode uses the values of y to automatically adjust
        weights inversely proportional to class frequencies in the input data
        as ``n_samples / (n_classes * np.bincount(y))``.

        Note that these weights will be multiplied with sample_weight (passed
        through the fit method) if sample_weight is specified.

        .. versionadded:: 0.17
           class_weight == 'balanced'

    n_jobs : int, default=None
        Number of CPU cores used during the cross-validation loop.
        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

    verbose : int, default=0
        For the 'liblinear', 'sag' and 'lbfgs' solvers set verbose to any
        positive number for verbosity.

    refit : bool, default=True
        If set to True, the scores are averaged across all folds, and the
        coefs and the C that corresponds to the best score is taken, and a
        final refit is done using these parameters.
        Otherwise the coefs, intercepts and C that correspond to the
        best scores across folds are averaged.

    intercept_scaling : float, default=1
        Useful only when the solver 'liblinear' is used
        and self.fit_intercept is set to True. In this case, x becomes
        [x, self.intercept_scaling],
        i.e. a "synthetic" feature with constant value equal to
        intercept_scaling is appended to the instance vector.
        The intercept becomes ``intercept_scaling * synthetic_feature_weight``.

        Note! the synthetic feature weight is subject to l1/l2 regularization
        as all other features.
        To lessen the effect of regularization on synthetic feature weight
        (and therefore on the intercept) intercept_scaling has to be increased.

    multi_class : {'auto, 'ovr', 'multinomial'}, default='auto'
        If the option chosen is 'ovr', then a binary problem is fit for each
        label. For 'multinomial' the loss minimised is the multinomial loss fit
        across the entire probability distribution, *even when the data is
        binary*. 'multinomial' is unavailable when solver='liblinear'.
        'auto' selects 'ovr' if the data is binary, or if solver='liblinear',
        and otherwise selects 'multinomial'.

        .. versionadded:: 0.18
           Stochastic Average Gradient descent solver for 'multinomial' case.
        .. versionchanged:: 0.22
            Default changed from 'ovr' to 'auto' in 0.22.
        .. deprecated:: 1.5
           ``multi_class`` was deprecated in version 1.5 and will be removed in 1.7.
           From then on, the recommended 'multinomial' will always be used for
           `n_classes >= 3`.
           Solvers that do not support 'multinomial' will raise an error.
           Use `sklearn.multiclass.OneVsRestClassifier(LogisticRegressionCV())` if you
           still want to use OvR.

    random_state : int, RandomState instance, default=None
        Used when `solver='sag'`, 'saga' or 'liblinear' to shuffle the data.
        Note that this only applies to the solver and not the cross-validation
        generator. See :term:`Glossary <random_state>` for details.

    l1_ratios : list of float, default=None
        The list of Elastic-Net mixing parameter, with ``0 <= l1_ratio <= 1``.
        Only used if ``penalty='elasticnet'``. A value of 0 is equivalent to
        using ``penalty='l2'``, while 1 is equivalent to using
        ``penalty='l1'``. For ``0 < l1_ratio <1``, the penalty is a combination
        of L1 and L2.

    Attributes
    ----------
    classes_ : ndarray of shape (n_classes, )
        A list of class labels known to the classifier.

    coef_ : ndarray of shape (1, n_features) or (n_classes, n_features)
        Coefficient of the features in the decision function.

        `coef_` is of shape (1, n_features) when the given problem
        is binary.

    intercept_ : ndarray of shape (1,) or (n_classes,)
        Intercept (a.k.a. bias) added to the decision function.

        If `fit_intercept` is set to False, the intercept is set to zero.
        `intercept_` is of shape(1,) when the problem is binary.

    Cs_ : ndarray of shape (n_cs)
        Array of C i.e. inverse of regularization parameter values used
        for cross-validation.

    l1_ratios_ : ndarray of shape (n_l1_ratios)
        Array of l1_ratios used for cross-validation. If no l1_ratio is used
        (i.e. penalty is not 'elasticnet'), this is set to ``[None]``

    coefs_paths_ : ndarray of shape (n_folds, n_cs, n_features) or                    (n_folds, n_cs, n_features + 1)
        dict with classes as the keys, and the path of coefficients obtained
        during cross-validating across each fold and then across each Cs
        after doing an OvR for the corresponding class as values.
        If the 'multi_class' option is set to 'multinomial', then
        the coefs_paths are the coefficients corresponding to each class.
        Each dict value has shape ``(n_folds, n_cs, n_features)`` or
        ``(n_folds, n_cs, n_features + 1)`` depending on whether the
        intercept is fit or not. If ``penalty='elasticnet'``, the shape is
        ``(n_folds, n_cs, n_l1_ratios_, n_features)`` or
        ``(n_folds, n_cs, n_l1_ratios_, n_features + 1)``.

    scores_ : dict
        dict with classes as the keys, and the values as the
        grid of scores obtained during cross-validating each fold, after doing
        an OvR for the corresponding class. If the 'multi_class' option
        given is 'multinomial' then the same scores are repeated across
        all classes, since this is the multinomial class. Each dict value
        has shape ``(n_folds, n_cs)`` or ``(n_folds, n_cs, n_l1_ratios)`` if
        ``penalty='elasticnet'``.

    C_ : ndarray of shape (n_classes,) or (n_classes - 1,)
        Array of C that maps to the best scores across every class. If refit is
        set to False, then for each class, the best C is the average of the
        C's that correspond to the best scores for each fold.
        `C_` is of shape(n_classes,) when the problem is binary.

    l1_ratio_ : ndarray of shape (n_classes,) or (n_classes - 1,)
        Array of l1_ratio that maps to the best scores across every class. If
        refit is set to False, then for each class, the best l1_ratio is the
        average of the l1_ratio's that correspond to the best scores for each
        fold.  `l1_ratio_` is of shape(n_classes,) when the problem is binary.

    n_iter_ : ndarray of shape (n_classes, n_folds, n_cs) or (1, n_folds, n_cs)
        Actual number of iterations for all classes, folds and Cs.
        In the binary or multinomial cases, the first dimension is equal to 1.
        If ``penalty='elasticnet'``, the shape is ``(n_classes, n_folds,
        n_cs, n_l1_ratios)`` or ``(1, n_folds, n_cs, n_l1_ratios)``.

    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
    --------
    LogisticRegression : Logistic regression without tuning the
        hyperparameter `C`.

    Examples
    --------
    >>> from sklearn.datasets import load_iris
    >>> from sklearn.linear_model import LogisticRegressionCV
    >>> X, y = load_iris(return_X_y=True)
    >>> clf = LogisticRegressionCV(cv=5, random_state=0).fit(X, y)
    >>> clf.predict(X[:2, :])
    array([0, 0])
    >>> clf.predict_proba(X[:2, :]).shape
    (2, 3)
    >>> clf.score(X, y)
    0.98...
    r   )r   r   r   r)   Nr   r   z
array-like	cv_objectr   >   r   r3   r4   )r   cvr   	l1_ratiosrefitr9   rE   TFr3   rH   rG   rF   r   rI   r   )r   rd   r=  r:   r9   r   r8   rz   r~   r   r   r{   r?  r   rB   r   r>  c                    || _         || _        || _        || _        || _        || _        || _        |	| _        |
| _        || _	        || _
        || _        || _        || _        || _        || _        || _        d S r   )r   rd   r=  r:   r9   r   rz   r~   r   r   r{   r8   r?  r   rB   r   r>  )r   r   rd   r=  r:   r9   r   r8   rz   r~   r   r   r{   r?  r   rB   r   r>  s                     r;   r   zLogisticRegressionCV.__init__  s    * *	 (
!2&("r=   r   c                 \    !"#$%&'() t          | d           t           j         j         j                  ) j        dk    r\ j        6t           j                  dk    st          d  j        D                       rt          d j        z             j        #n6 j        ,t          j
        d                     j                             dg#t           dt          j        d	)d
v          \  t                      j         t#                                                    $$                              t)           t*                    r $fd                                 D              $j        x} _        $                    $j                  } j        & j        dk    r3t           j                  dk    rt          j
        dt2                     nL j        dv rt          j
        dt2                     n( j        dk    rt          j
        dt2                     nd&t5          &)t          |                    &)dv r$t7          d                                          %nd%t;                      rt=           dfdi|(nIt?                      (t?          i           (_         t?          |          (_!        (j!        j"        d<   tG           j$        d          }tK           |j&        fi (j         j&                  "t          |          }|dk     rt          d|d         z            |dk    rd}|dd         }|dd         }&dk    rdgx}	}
n|}	|}
 dk    rRtO           t          j(        t           j                                       t+          tS                                tU          tV                    ' j        dv rd }nd!} tY           j-         j.        |"           "#%&'( )fd#|	D                       }t_          | \  !}}}|d          _0        &dk    rt          j1        !t          "          t          #          t           j0                  z  |d$f          !t          j2        !dd          !t          j2        !dd          !t          j1        |dt          "          t           j0                  t          #          z  f           _3        t          j4        ||ddf          }nt          j1        !|t          "          t           j0                  t          #          z  d$f          !t          j1        ||t          "          t           j0                  t          #          z  f           _3        t          j1        ||t          "          d$f          }t+          t_          ||                     _5        t+          t_          |!                     _6        tK                       _7        tK                       _8        t          j9        |j:        d         f           _;        t          j<        |           _=        tS          t_          |
|	                    D ]\  }\  }}&dk    r j5        |         } j6        |         !n|d         } j>        ri|?                    d%          @                                }|t           j0                  z  } j0        |         } j7        A                    |           |t           j0                  z  }#|         } j8        A                    |           &dk    r't          jB        !dddd|ddf         d%          }n#t          jB        !dd|ddf         d%          }t          fi d&|d'|gd()d) jD        d*|d+ jE        d, jF        d- j        d. d/&d0t9          d j.        dz
            d1 jG        d2d3d4%dd5|\  }}}|d         }nTt          j@        |d%          &dk    r>t          jB        !fd6t          t          "                    D             d%          }n=t          jB        !fd7t          t          "                    D             d%          }t           j0                  z  } j7        A                    t          jB         j0        |                               j        dk    rJt           j0                  z  } j8        A                    t          jB        #|                              n j8        A                    d           &dk    rvt          j4         j7        |           _7        t          j4         j8        |           _8        |dddj:        d         f          _;         jD        r|ddd$f          _=        s|dj:        d                   j;        |<    jD        r|d$          j=        |<   t          jI         j7                   _7        t          jI         j8                   _8        t          jI        #           _J         j        t j6                                        D ]o\  }}|1                    t          "           jJ        jK         j0        jK        d$f           j6        |<   t          jL         j6        |         d8           j6        |<   p j5                                        D ]n\  }}|1                    t          "           jJ        jK         j0        jK        f           j5        |<   t          jL         j5        |         d9           j5        |<   o j3        1                    d$t          "           jJ        jK         j0        jK        f           _3        t          jL         j3        d:           _3         S );a@  Fit the model according to the given training data.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            Training vector, where `n_samples` is the number of samples and
            `n_features` is the number of features.

        y : array-like of shape (n_samples,)
            Target vector relative to X.

        sample_weight : array-like of shape (n_samples,) default=None
            Array of weights that are assigned to individual samples.
            If not provided, then each sample is given unit weight.

        **params : dict
            Parameters to pass to the underlying splitter and scorer.

            .. versionadded:: 1.4

        Returns
        -------
        self : object
            Fitted LogisticRegressionCV estimator.
        r  r4   Nr   c              3   d   K   | ]+}t          |t          j                   p|d k     p|dk    V  ,dS )r   r)   N)r   r   Number)r	  r   s     r;   r  z+LogisticRegressionCV.fit.<locals>.<genexpr>7  s_         !	 'x@@@ (#a<(#a<	     r=   zGl1_ratios must be a list of numbers between 0 and 1; got (l1_ratios=%r)zOl1_ratios parameter is only used when penalty is 'elasticnet'. Got (penalty={})rM   r   rN   r   c                 P    i | ]"\  }}                     |g          d          |#S )r   )	transform)r	  clsvlabel_encoders      r;   
<dictcomp>z,LogisticRegressionCV.fit.<locals>.<dictcomp>_  sA       9?a''..q11  r=   rA   r   r   r   r   r@   z'multi_class' was deprecated in version 1.5 and will be removed in 1.7. Use OneVsRestClassifier(LogisticRegressionCV(..)) instead. Leave it to its default value to avoid this warning.r?   r   Tr  r   )splitr   )
classifierr  r)   r\   rU   r  r  r  c           	   3   *  K   | ]}D ]\  }}D ]} ||fi d |dj         dj        dj        dj        ddj        dj        dj        d	d
j        d
dj        dj	        d	dd|dj
        j        V  dS )r   r   rd   r9   r:   r8   rz   r~   r{   r   r   rB   r   r   r   r   r   r   N)r   rd   r9   r:   rz   r~   r{   r   r   r   scorerr   )r	  labelr   r   r   r   r   folds
l1_ratios_r   rB   r  routed_paramsr   r   r8   rW   s        r;   r  z+LogisticRegressionCV.fit.<locals>.<genexpr>  s      X
 X
2 $5X
 X
4 t&7X
 X
6 5 I	  
  % 77 #00  YY v HH   *\   (K!" #'"8"8#$ "..%& !0'( ,m)* "+, +177-X
 X
 X
 X
 X
 X
 X
 X
r=   rY   rf   r   r   r8   rd   re   r~   rz   r9   r   rB   r{   r   r   Fr   r   c                 6    g | ]}||         d d f         S r    r	  r   best_indicescoefs_pathss     r;   
<listcomp>z,LogisticRegressionCV.fit.<locals>.<listcomp>R  s-    WWWQQ%:;WWWr=   c                 <    g | ]}d d ||         d d f         S r   rT  rU  s     r;   rX  z,LogisticRegressionCV.fit.<locals>.<listcomp>W  sC        ! (1l1oqqq(@A  r=   )r   r   r)   rj   )r   r   r)   )r   r)   rj   r   )Mr   r<   r8   r9   r:   r>  r   anyr7   r  r  r  r(   r   r   r    r   r   r  rE  r   r   itemsr   rB   r  rD   r   r   r   r   r   splitterrN  r   r   r=  r   rJ  r   aranger   r$   r   r#   r   r{   r  Cs_r   swapaxesr  tilescores_coefs_paths_r  	l1_ratio_emptyr   r   r   r   r?  r   argmaxr   meanr   rd   r~   rz   r   ranger  rQ  r   	transpose)*r   r   rW   r   r   rV   encoded_labelsr=  rC   iter_encoded_labelsiter_classesr  r  r   r   r  indexrF  encoded_label
best_indexbest_index_Cr  best_index_l1rc  	coef_initr   r  best_indices_Cbest_indices_l1
coefs_pathr   rV  r   rW  rP  rQ  rH  r   rB   r  rR  r8   s*   ````                           @@@@@@@@@@@r;   r  zLogisticRegressionCV.fit  s4   6 	&$...t{DL$)DD<<''&t~&&!++   %)N     , !248NC   JJ~)88>t|8L8L  
 J* &.J J
 
 
1 	%Q'''( %**1--##A&&lD)) 	   COCUCUCWCW  L
 #0"88$-&001GHH &},,T]1C1Cq1H1HML
     !888ML     &&ML     !K(fc'llKK_$$'4888<<>>OO"O 	L+  , 	 MM "GGM%*___M"#(v#6#6#6M (>K$*?; dgqT222XRXaCCm&<&BCCDD ''	q==&qz*   >> I+ABB/NabbkG -''267,,"0"L :%%/biDM0B0B&C&Cq  L  	, 7 788L122	 ;/))FF FWhdk4<PVWWW X
 X
 X
 X
 X
 X
 X
 X
 X
 X
 X
 X
 X
 X
 X
2 -3X
 X
 X
 
 
R ,/+<(Ra5-''*US__s48}}<iL K +k1a88K+k1a88K:!SZZTXZ)HI DL WViA%677FF*CJJDHJ(GL K :)SZZTXZ1PQ DL FYE

B$?@@C0011 Wk!:!:;;&&Xy!'!*566
(9--+4122,
 ,
 ]	3 ]	3'E'C e##c*"/4   z F0 $ZZQZ//6688
)CMM9Xl+r""" *c$(mm ;&}5	%%i000-// "AAAqqq*aaa4G(Hq Q Q QII "AAAz1114D(EA N N NI 4   ,m tt	
 "6 #'"4"4 # "]]  !LL ". !,  4<!#3444 "&!2!2 !&  %4O!" #0-#$ 'Y%1a( aD
  "ya888%''WWWWWU3u::EVEVWWW  AA
     %*3u::%6%6     A ".DH!=rwtx'?@@AAA<<//&2c$(mm&CON))"'*_2M*N*NOOOON))$///m++'$'955!#!C!Cqqq,AGAJ,/
% /&'2hDO$%l
lO
5!% 3-.rUDOE**TW%%DN33*Z00 >% $(#4#:#:#<#<  Z)3););ZZ!5tx}bI* *!#& *,%c*L* *!#&& #l0022 O O
U$)MMZZ!5tx}E% %S! %'Lc1BI$N$NS!!<//SZZ!5tx}E DL <lCCDLr=   c                    t          || d           |                                 }t                      rt          | dfd|i|}n4t	                      }t	          i           |_        |||j        j        d<    || ||fi |j        j        S )am  Score using the `scoring` option on the given test data and labels.

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

        y : array-like of shape (n_samples,)
            True labels for X.

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

        **score_params : dict
            Parameters to pass to the `score` method of the underlying scorer.

            .. versionadded:: 1.4

        Returns
        -------
        score : float
            Score of self.predict(X) w.r.t. y.
        r   r   rK  )r   _get_scorerr   r   r   rN  r   )r   r   rW   r   r   r   rR  s          r;   r   zLogisticRegressionCV.score  s    0 	,g666""$$ 	L+  , 	 MM "GGM#(r???M (>K$*?;w
 
 "(	
 
 	
r=   c                    t          | j        j                                      |                               | j        t                                          dd                                        |                                 t                                          dd                              dd                    }|S )aj  Get metadata routing of this object.

        Please check :ref:`User Guide <metadata_routing>` on how the routing
        mechanism works.

        .. versionadded:: 1.4

        Returns
        -------
        routing : MetadataRouter
            A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating
            routing information.
        )ownerr  rJ  )callercallee)r\  method_mappingr   )rN  r{  )r   r&  r3  add_self_requestaddr=  r   rv  )r   routers     r;   get_metadata_routingz)LogisticRegressionCV.get_metadata_routing  s      !8999d##S,22%2PP    S'')),GG44E'22	    	 r=   c                 2    | j         pd}t          |          S )zpGet the scorer based on the scoring method specified.
        The default scoring method is `accuracy`.
        accuracy)r   r   )r   r   s     r;   rv  z LogisticRegressionCV._get_scorer  s     ,,*'"""r=   c                 `    t                                                      }d|j        _        |S r+  r,  r0  s     r;   r-  z%LogisticRegressionCV.__sklearn_tags__  r2  r=   r   )r3  r4  r5  r6  r   r   r   r7  parampopupdater   r   r   setr   callabler   r   r  r   r  rv  r-  r8  r9  s   @r;   r;  r;    s        ` `D	 $Q&8&O#PDPPP0 * *""5))))!!8Haf===|L-"
33'7'7'9'9#:#:;;XtL&-["
#=#=#=>>?	
 	
	 	 	  '%# %# %# %# %#N \555   65B-
 -
 -
 -
^  ># # #        r=   r;  )NrE   TrF   rG   r   rH   NNFr3   rI   r?   NTNNNr)   )Lr6  r   r  r   r   numpyr   joblibr   scipyr   sklearn.metricsr   
_loss.lossr	   r
   baser   metricsr   model_selectionr   preprocessingr   r   	svm._baser   utilsr   r   r   r   r   utils._param_validationr   r   r   utils.extmathr   r   utils.metadata_routingr   r   r   r   r   utils.multiclassr    utils.optimizer!   r"   utils.parallelr#   r$   utils.validationr%   r&   r'   r(   _baser*   r+   r,   _glm.glmr-   _linear_lossr.   _sagr/   r   r<   rD   r   r   r   r;  rT  r=   r;   <module>r     s      " " " " " " " "     # # # # # #       , , , , , , > > > > > > > >                   & & & & & & 8 8 8 8 8 8 8 8 & & & & & &              C B B B B B B B B B . . . . . . . .              < ; ; ; ; ; ? ? ? ? ? ? ? ? . . . . . . . .            I H H H H H H H H H * * * * * * ) ) ) ) ) )       !  (  * 			+a1 a1 a1 a1J\/ \/ \/~P
 P
 P
 P
 P
. P
 P
 P
ft t t t t-/Dm t t t t tr=   