
    -i"`                    V   S r SSKrSSKJrJr  SSKJrJr  SSKr	SSK
JrJrJr  SSKJrJrJrJrJrJr  SSKJr  SS	KJrJr  SS
KJrJr  SSKJrJrJ r   SSK!J"r"  SSK#J$r$  SSK%J&r&  SSK'J(r(J)r)  SSK*J+r+J,r,J-r-  SSK.J/r/J0r0J1r1  SSK2J3r3J4r4J5r5J6r6J7r7J8r8J9r9  SSSSSSS.r:SSSSS.r;Sr<\	Rz                  " \	R|                  5      R~                  r@ " S S5      rA " S S\0\\S9rBS-S  jrC  S.S! jrDS" rE " S# S$\/\B\S9rF " S% S&\F5      rG " S' S(\\B5      rH " S) S*\H5      rI " S+ S,\\B5      rJg)/zVClassification, regression and One-Class SVM using Stochastic Gradient
Descent (SGD).
    N)ABCMetaabstractmethod)IntegralReal   )CyHalfBinomialLossCyHalfSquaredErrorCyHuberLoss)BaseEstimatorOutlierMixinRegressorMixin_fit_contextcloneis_classifier)ConvergenceWarning)ShuffleSplitStratifiedShuffleSplit)check_random_statecompute_class_weight)HiddenInterval
StrOptions)safe_sparse_dot)available_if)_check_partial_fit_first_call)Paralleldelayed)_check_sample_weightcheck_is_fittedvalidate_data   )LinearClassifierMixinSparseCoefMixinmake_dataset)EpsilonInsensitiveHingeModifiedHuberSquaredEpsilonInsensitiveSquaredHinge_plain_sgd32_plain_sgd64            )constantoptimal
invscalingadaptivepa1pa2)nonel2l1
elasticnet皙?c                   (    \ rS rSrSrSS jrS rSrg)_ValidationScoreCallback<   z5Callback for early stopping based on validation scoreNc                     [        U5      U l        SU R                  l        Ub  XPR                  l        X l        X0l        X@l        g )Nr!   )r   	estimatort_classes_X_valy_valsample_weight_val)selfr?   rB   rC   rD   classess         \/var/www/html/venv/lib/python3.13/site-packages/sklearn/linear_model/_stochastic_gradient.py__init__!_ValidationScoreCallback.__init__?   s:    y)&-NN#

!2    c                     U R                   nUR                  SS5      Ul        [        R                  " U5      Ul        UR                  U R                  U R                  U R                  5      $ )Nr!   )
r?   reshapecoef_np
atleast_1d
intercept_scorerB   rC   rD   )rE   coef	interceptests       rG   __call__!_ValidationScoreCallback.__call__H   sN    nnLLB'	y1yyTZZ1G1GHHrJ   )rB   r?   rD   rC   N)__name__
__module____qualname____firstlineno____doc__rH   rV   __static_attributes__ rJ   rG   r<   r<   <   s    ?3IrJ   r<   c                       \ rS rSr% SrS/\" \SSSS9/\" \SSSS9S/S/S	/S
/S/\" \SSSS9S/S.r\	\
S'   SSSSSSSSSSSSSSSSSSSS.S jr\S 5       rS'S jrS rS  rS! rS" r   S(S# jrS$ r S)S% jrS&rg)*BaseSGDO   z1Base class for SGD classification and regression.booleanr!   Nleftclosedr   verboserandom_stateneither)fit_interceptmax_itertolshufflerg   rh   
warm_startaverage_parameter_constraintsr7   -C6?      ?333333?T  MbP?r:   r1                 ?Fr.   )penaltyalphaCl1_ratiorj   rk   rl   rm   rg   epsilonrh   learning_rateeta0power_tearly_stoppingvalidation_fractionn_iter_no_changern   ro   c                    Xl         X l        Xl        Xl        X0l        X@l        XPl        X`l        Xl        Xl	        Xl
        Xl        Xl        UU l        UU l        UU l        UU l        UU l        Xpl        Xl        g rX   )lossrx   r}   r|   ry   rz   r{   rj   rm   rh   rg   r~   r   r   r   r   rn   ro   rk   rl   )rE   r   rx   ry   rz   r{   rj   rk   rl   rm   rg   r|   rh   r}   r~   r   r   r   r   rn   ro   s                        rG   rH   BaseSGD.__init__]   sx    0 	*
 *(	,#6  0$ rJ   c                     g)z
Fit model.Nr_   rE   Xys      rG   fitBaseSGD.fit   s    rJ   c                    U R                   (       a  U(       a  [        S5      eU R                  S;   a  U R                  S::  a  [        S5      eU R                  S:X  a  U R                  S:X  a  [        S5      eU R
                  S:X  a  U R                  c  [        S
5      eU R                  U R
                  5        U R                  U R                  5        g	)zValidate input params.z/early_stopping should be False with partial_fit)r0   r2   r3   rv   zeta0 must be > 0r1   r   zgalpha must be > 0 since learning_rate is 'optimal'. alpha is used to compute the optimal learning rate.r9   Nz1l1_ratio must be set when penalty is 'elasticnet')	r   
ValueErrorr}   r~   ry   rx   r{   _get_penalty_type_get_learning_rate_type)rE   for_partial_fits     rG   _more_validate_paramsBaseSGD._more_validate_params   s    ?NOO"HH		S /00*tzzQ8 
 <<<'DMM,APQQ 	t||,$$T%7%78rJ   c                 6    U R                   c  gU R                   $ )Nrv   )r{   rE   s    rG   _get_l1_ratioBaseSGD._get_l1_ratio   s    ==  }}rJ   c                 b    U R                   U   nUS   USS pCUS;   a  U R                  4nU" U6 $ )z6Get concrete ``LossFunction`` object for str ``loss``.r   r!   N)huberepsilon_insensitivesquared_epsilon_insensitive)loss_functionsr|   )rE   r   loss_
loss_classargss        rG   _get_loss_functionBaseSGD._get_loss_function   sB    ##D) 8U12YDRRLL?D4  rJ   c                     [         U   $ rX   )LEARNING_RATE_TYPES)rE   r}   s     rG   r   BaseSGD._get_learning_rate_type   s    "=11rJ   c                 F    [        U5      R                  5       n[        U   $ rX   )strlowerPENALTY_TYPES)rE   rx   s     rG   r   BaseSGD._get_penalty_type   s    g,$$&W%%rJ   c                    US:  a  Ub8  [         R                  " XCSS9nUR                  X4:w  a  [        S5      eX@l        O[         R
                  " X4USS9U l        Ub:  [         R                  " USUS9nUR                  U4:w  a  [        S5      eXPl        GO6[         R
                  " XSS9U l        GOUbH  [         R                  " XCSS9nUR                  5       nUR                  U4:w  a  [        S5      eX@l        O[         R
                  " X#SS9U l        Ubt  [         R                  " XSS	9nUR                  S
:w  a  UR                  S:w  a  [        S5      eU(       a  UR                  S5      U l	        OUUR                  S5      U l        O>U(       a  [         R
                  " SUSS9U l	        O[         R
                  " SUSS9U l        U R                  S:  a  U R                  U l        [         R
                  " U R                  R                  USS9U l        U(       a  SU R                  -
  U l        OU R                  U l        [         R
                  " U R                  R                  USS9U l        gg)z4Allocate mem for parameters; initialize if provided.r   Nrz   dtypeorderz+Provided ``coef_`` does not match dataset. )r   r   z/Provided intercept_init does not match dataset.z*Provided coef_init does not match dataset.r   )r!   r_   r!   r   )rO   asarrayshaper   rN   zerosrQ   ravelrM   offset_ro   _standard_coef_average_coef_standard_intercept_average_intercept)rE   	n_classes
n_featuresinput_dtype	coef_initintercept_init	one_classs          rG   _allocate_parameter_memBaseSGD._allocate_parameter_mem   s"    q=$JJy3O	??y&==$%RSS&
XX+;c

 )!#"#[" "''I<7$%VWW"0"$((9s"S $JJy3O	%OO-	??zm3$%QRR&
XXj3O
 )!#N!N!''4/N4H4HB4N$%VWW#1#9#9$DL '5&<&<'DO #%88A[#LDL&(hhq3&ODO <<!"&**D!#

  3"D +,t||+;(+/??(&(hh((..k'D# rJ   c                    UR                   S   n[        R                  " U[        R                  S9nU R                  (       d  U$ [        U 5      (       a  [        nO[        nU" U R                  U R                  S9n[        UR                  [        R                  " UR                   S   S4S9U5      5      u  px[        R                  " X(   5      (       d  [        S5      eUR                   S   S:X  d  UR                   S   S:X  a6  [        SUU R                  UR                   S   UR                   S   4-  5      eSXH'   U$ )	a  Split the dataset between training set and validation set.

Parameters
----------
y : ndarray of shape (n_samples, )
    Target values.

sample_mask : ndarray of shape (n_samples, )
    A boolean array indicating whether each sample should be included
    for validation set.

Returns
-------
validation_mask : ndarray of shape (n_samples, )
    Equal to True on the validation set, False on the training set.
r   r   )	test_sizerh   r!   )r   z\The sample weights for validation set are all zero, consider using a different random state.zSplitting %d samples into a train set and a validation set with validation_fraction=%r led to an empty set (%d and %d samples). Please either change validation_fraction, increase number of samples, or disable early_stopping.T)r   rO   r   bool_r   r   r   r   r   rh   nextsplitanyr   )	rE   r   sample_mask	n_samplesvalidation_masksplitter_typecv	idx_trainidx_vals	            rG   _make_validation_splitBaseSGD._make_validation_split  s-   " GGAJ	((9BHH=""""2M(M..T=N=N
 ""((2881771:q/+JA"NO	vvk*+++ 
 ??1"gmmA&6!&;@
 ,,OOA&MM!$			  $( rJ   c                 L    U R                   (       d  g [        U X!   X1   XA   US9$ )NrF   )r   r<   )rE   r   r   r   sample_weightrF   s         rG   _make_validation_score_cb!BaseSGD._make_validation_score_cb>  s5     ""'*
 	
rJ   )rz   r   r   r   r   ry   ro   rN   r   r|   r~   rj   rQ   r{   r}   r   rk   r   r   rx   r   rh   rm   rl   r   rg   rn   )F)NNr   rX   )rY   rZ   r[   r\   r]   r   r   r   rp   dict__annotations__rH   r   r   r   r   r   r   r   r   r   r   r^   r_   rJ   rG   ra   ra   O   s    ; $h4?@q$v6=;;'( kXq$yA9M	$D 	 
-+Z  9,!2& KZ5p =A
rJ   ra   )	metaclassc                    [         R                  " UR                  USS9nU(       a  SXQU R                  U   :g  '   OSXQU R                  U   :g  '   SnSn[	        U R                  5      S:X  a  U R
                  (       d*  U R                  R                  5       nU R                  S   n	OU R                  R                  5       nU R                  S   n	U R                  R                  5       nU R                  S   nOlU R
                  (       d  U R                  U   nU R                  U   n	O<U R                  U   nU R                  U   n	U R                  U   nU R                  U   nXXXU4$ )z]Initialization for fit_binary.

Returns y, coef, intercept, average_coef, average_intercept.
rz   r   rv   g      r   Nr   )rO   onesr   rA   lenro   rN   r   rQ   r   r   r   r   )
rU   r   ir   label_encodey_iaverage_interceptaverage_coefrS   rT   s
             rG   _prepare_fit_binaryr   M  sD   
 ''!''C
8C$'a ! %)a !L
3<<A{{99??$Dq)I%%++-D//2I,,224L # 6 6q 9{{99Q<Dq)I%%a(D//2I,,Q/L # 6 6q 9i/@@@rJ   c                    [        U R                  [        5      n[        XXR                  US9u  pnnnUR
                  S   UR
                  S   s=:X  a  U
R
                  S   :X  d   e   e[        U5      n[        X.XS9u  nnU R                  U R                  5      nU R                  U5      nUc  U R                  XS:  S9n[        R                  " SS/UR                  S9nU R                  XXUS9nUR                  [         5      nU R"                  b  U R"                  O[        R$                  * n['        UR                  S	9nU" UUUUU R                  UUUU R)                  5       UUU R*                  U[-        U R.                  5      UU[-        U R0                  5      [-        U R2                  5      [-        U R4                  5      UUU	UU R6                  U R8                  SU R:                  UU R<                  5      u  nnnnnU R<                  (       a8  [?        U R@                  5      S
:X  a  UU RB                  S'   OUU RB                  U'   UUU4$ )a  Fit a single binary classifier.

The i'th class is considered the "positive" class.

Parameters
----------
est : Estimator object
    The estimator to fit

i : int
    Index of the positive class

X : numpy array or sparse matrix of shape [n_samples,n_features]
    Training data

y : numpy array of shape [n_samples, ]
    Target values

alpha : float
    The regularization parameter

C : float
    Maximum step size for passive aggressive

learning_rate : str
    The learning rate. Accepted values are 'constant', 'optimal',
    'invscaling', 'pa1' and 'pa2'.

max_iter : int
    The maximum number of iterations (epochs)

pos_weight : float
    The weight of the positive class

neg_weight : float
    The weight of the negative class

sample_weight : numpy array of shape [n_samples, ]
    The weight of each sample

validation_mask : numpy array of shape [n_samples, ], default=None
    Precomputed validation mask in case _fit_binary is called in the
    context of a one-vs-rest reduction.

random_state : int, RandomState instance, default=None
    If int, random_state is the seed used by the random number generator;
    If RandomState instance, random_state is the random number generator;
    If None, the random number generator is the RandomState instance used
    by `np.random`.
)r   r   r   rh   r   rL   r!   r   r   r   r   )"
isinstance_loss_function_r   r   r   r   r   r$   r   rx   r   r   rO   arrayr   randintMAX_INTrl   inf_get_plain_sgd_functionr   r   intr   rj   rg   rm   r~   r   r@   ro   r   rA   r   )rU   r   r   r   ry   rz   r}   rk   
pos_weight
neg_weightr   r   rh   r   r   rS   rT   r   r   datasetintercept_decaypenalty_typelearning_rate_typerF   validation_score_cbseedrl   
_plain_sgdn_iter_s                                rG   
fit_binaryr   r  sC   F c113EFL<Oww\=9Cy,(9 99Q<1771:?)<)<Q)??????%l3L+	 G_ ((5L44]C44SVWFW4XhhAwcii0G77C 8  (DWW(#''rvvgC(TZZ@J@J	C  !CCKKCKK	;A=D)\#4g@ {{s||!(9C""1%(9C""1%G##rJ   c                 B    U [         R                  :X  a  [        $ [        $ rX   )rO   float32r*   r+   r   s    rG   r   r     s    &"**4<F,FrJ   c                     ^  \ rS rSr% \S4\S4\S4\4\4\4\	\
4\\
4\\
4S.	r0 \R                  E\" \" \5      5      /S/\" \SSSS	9/\" \SS
SS	9/\S
/\" S15      \S
/S.Er\\S'   \ S%SSSSSSSS\
S
S
SSSSSSS
SSS.U 4S jjj5       rS r   S&S jrS rS r\" SS 9S'S! j5       r\" SS 9S&S" j5       rU 4S# jr S$r!U =r"$ )(BaseSGDClassifieri  rr   rv   )	hingesquared_hinge
perceptronlog_lossmodified_hubersquared_errorr   r   r   rc   r   r!   ri   re   Nrd   balanced)r   r   r   r   n_jobsclass_weightrp   r7   rq   rs   Trt   ru   r1   rw   Fr:   r.   rx   ry   r{   rj   rk   rl   rm   rg   r|   r  rh   r}   r~   r   r   r   r   r  rn   ro   c                ^   > [         TU ]  UUUUUUUUU	U
UUUUUUUUUS9  UU l        Xl        g N)r   rx   ry   r{   rj   rk   rl   rm   rg   r|   rh   r}   r~   r   r   r   r   rn   ro   )superrH   r  r  rE   r   rx   ry   r{   rj   rk   rl   rm   rg   r|   r  rh   r}   r~   r   r   r   r   r  rn   ro   	__class__s                         rG   rH   BaseSGDClassifier.__init__  s_    4 	'%') 3-!' 	 	
* )rJ   c                 &   [        U S5      (       + n[        U UUS[        R                  [        R                  /SSUS9u  pUR
                  u  p[        X5        U R                  R
                  S   n[        U R                  U R                  US9U l
        [        XUR                  S9n	[        U S	S 5      b  U
b  U R                  UUUR                  U
US
9  OBXR                  R
                  S   :w  a&  [!        SXR                  R
                  S   4-  5      eU R#                  U5      U l        [        U S5      (       d  SU l        US:  a  U R)                  UUUUUU	US9  U $ US:X  a  U R+                  UUUUUU	US9  U $ [!        SU-  5      e)NrA   csrrz   Faccept_sparser   r   accept_large_sparseresetr   )rF   r   r   rN   r   r   r   r   r   rL   6Number of features %d does not match previous data %d.r@   rr   r   ry   rz   r}   r   rk   z>The number of classes has to be greater than one; got %d class)hasattrr    rO   float64r   r   r   rA   r   r  _expanded_class_weightr   r   getattrr   rN   r   r   r   r@   _fit_multiclass_fit_binary)rE   r   r   ry   rz   r   r}   rk   rF   r   r   r   
first_callr   r   r   s                   rG   _partial_fitBaseSGDClassifier._partial_fitG  s    !z22
::rzz* %	
 !"	%d4MM''*	 ';t}}'
# -]QWWM4$'/93H((#%GG#- )  ::++B//Hzz//345 
  $66t<tT""DG q=  ++! ! 2 ! !^++!    P rJ   c
                    [        U S5      (       a  [        U S5        [        XS9n[        R                  " U5      n
U R
                  (       a0  [        U S5      (       a  Uc  U R                  nUc  U R                  nOS U l        S U l        U R                  S:  a0  U R                  U l	        U R                  U l
        S U l        S U l        SU l        U R                  UUUUUUU R                  U
U	UU5        U R                   bT  U R                   [        R"                  * :  a5  U R$                  U R                  :X  a  [&        R(                  " S[*        5        U $ )NrA   )r   rN   r   rr   hMaximum number of iteration reached before convergence. Consider increasing max_iter to improve the fit.)r  delattrr    rO   uniquern   rN   rQ   ro   r   r   r   r   r@   r  rk   rl   r   r   warningswarnr   )rE   r   r   ry   rz   r   r}   r   r   r   rF   s              rG   _fitBaseSGDClassifier._fit  s/    4$$D*% $$))A,??wtW55  JJ	%!%DJ"DO<<!"&**D'+D$!%D&*D# MM	
 HH BFF7"-MM' # rJ   c                    [        U SUUUUUUU R                  S   U R                  S   UU R                  S9u  pn
U =R                  XR                  S   -  -  sl        Xl        U R                  S:  a  U R                  U R                  S-
  ::  a3  U R                  R                  SS5      U l	        U R                  U l        gU R                  R                  SS5      U l	        [        R                  " U	5      U l        U R                  U l        gUR                  SS5      U l	        [        R                  " U	5      U l        g)z#Fit a binary classifier on X and y.r!   r   r   rL   N)r   r  rh   r@   r   r   ro   r   rM   rN   r   rQ   r   rO   rP   r   )rE   r   r   ry   rz   r   r}   rk   rS   rT   r   s              rG   r  BaseSGDClassifier._fit_binary  s   #-''*''***$
  	7WWQZ'' <<!||tww{*!//772>
"&"9"9!0088B?
+-==+C("&":":a,DJ mmI6DOrJ   c                 $  ^ ^^^^^^^^ T R                  TTS:  S9m[        T R                  5      nUR                  [        [        T R                  5      S9n	[        T R                  T R                  SS9" UUUUUUU UU4	S j[        U	5       5       5      n
Sn[        U
5       H#  u  nu  pnUT R                  U'   [        X5      nM%     T =R                  UTR                  S   -  -  sl        UT l        T R                   S:  a  T R                   T R                  S-
  ::  a#  T R"                  T l        T R&                  T l        g	T R(                  T l        [*        R,                  " T R                  5      T l        T R.                  T l        g	g	)
zFit a multi-class classifier by combining binary classifiers

Each binary classifier predicts one class versus all others. This
strategy is called OvA (One versus All) or OvR (One versus Rest).
r   r   )size	sharedmem)r  rg   requirec              3      >	#    U  H3  u  p[        [        5      " T	UTTTTTTT	R                  U   S TT
US9v   M5     g7f)rr   )r   rh   N)r   r   r  ).0r   r   rz   r   ry   r}   rk   r   rE   r   r   s      rG   	<genexpr>4BaseSGDClassifier._fit_multiclass.<locals>.<genexpr>  sZ      

  , J++A. /! ,s   ;>rv   rr   N)r   r   rh   r   r   r   rA   r   r  rg   	enumeraterQ   maxr@   r   r   ro   r   rN   r   r   rO   rP   r   )rE   r   r   ry   rz   r}   r   rk   rh   seedsresultr   r   _rT   n_iter_ir   s   ````````        @rG   r  !BaseSGDClassifier._fit_multiclass  sR    55a]UVEV5W *$*;*;<$$W3t}}3E$F;;k


 

  %U+!


, +4V+<'A'h!*DOOA',G ,= 	7QWWQZ''<<!||tww},!//
"&"9"9!00
+-==+I("&":": rJ   prefer_skip_nested_validationc                    [        U S5      (       dC  U R                  SS9  U R                  S:X  a$  [        SR	                  U R                  5      5      eU R                  UUU R                  SU R                  U R                  SUUSSS	9$ )
ac  Perform one epoch of stochastic gradient descent on given samples.

Internally, this method uses ``max_iter = 1``. Therefore, it is not
guaranteed that a minimum of the cost function is reached after calling
it once. Matters such as objective convergence, early stopping, and
learning rate adjustments should be handled by the user.

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

y : ndarray of shape (n_samples,)
    Subset of the target values.

classes : ndarray of shape (n_classes,), default=None
    Classes across all calls to partial_fit.
    Can be obtained by via `np.unique(y_all)`, where y_all is the
    target vector of the entire dataset.
    This argument is required for the first call to partial_fit
    and can be omitted in the subsequent calls.
    Note that y doesn't need to contain all labels in `classes`.

sample_weight : array-like, shape (n_samples,), default=None
    Weights applied to individual samples.
    If not provided, uniform weights are assumed.

Returns
-------
self : object
    Returns an instance of self.
rA   Tr   r   aQ  class_weight '{0}' is not supported for partial_fit. In order to use 'balanced' weights, use compute_class_weight('{0}', classes=classes, y=y). In place of y you can use a large enough sample of the full training set target to properly estimate the class frequency distributions. Pass the resulting weights as the class_weight parameter.rr   r!   N)	ry   rz   r   r}   rk   rF   r   r   r   )	r  r   r  r   formatr  ry   r   r}   )rE   r   r   rF   r   s        rG   partial_fitBaseSGDClassifier.partial_fit9  s    D tZ((&&t&<  J. ! "((9(9!:
 
   **,,' ! 
 	
rJ   c                     U R                  5         U R                  UUU R                  SU R                  U R                  UUUS9	$ )a   Fit linear model with Stochastic Gradient Descent.

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

y : ndarray of shape (n_samples,)
    Target values.

coef_init : ndarray of shape (n_classes, n_features), default=None
    The initial coefficients to warm-start the optimization.

intercept_init : ndarray of shape (n_classes,), default=None
    The initial intercept to warm-start the optimization.

sample_weight : array-like, shape (n_samples,), default=None
    Weights applied to individual samples.
    If not provided, uniform weights are assumed. These weights will
    be multiplied with class_weight (passed through the
    constructor) if class_weight is specified.

Returns
-------
self : object
    Returns an instance of self.
rr   ry   rz   r   r}   r   r   r   r   r"  ry   r   r}   rE   r   r   r   r   r   s         rG   r   BaseSGDClassifier.fity  sO    : 	""$yy**,,)'  

 
	
rJ   c                 F   > [         TU ]  5       nSUR                  l        U$ NTr  __sklearn_tags__
input_tagssparserE   tagsr  s     rG   rD  "BaseSGDClassifier.__sklearn_tags__  !    w')!%rJ   )r   r   r  r   r   r   r  rN   rQ   r   r  r@   r   NNNNN)#rY   rZ   r[   r\   r&   r)   r   r'   r	   r
   DEFAULT_EPSILONr%   r(   r   ra   rp   r   setr   r   r   r   r   r   rH   r  r"  r  r  r   r:  r   rD  r^   __classcell__r  s   @rG   r   r     s   &,cl')(*,./ 2OD(A?'S
N$

(
($C/01$+ (q!I FG%h4GHT"#ZL14>$D   / // / /bSz BH 7D5;n 5=
 6=
~ 5(
 6(
T rJ   r   c                   p  ^  \ rS rSr% Sr0 \R                  E\" 1 Sk5      S/\" \	SSSS9/\" \	SSS	S9S/\" \	SSS
S9/\" \	SSSS9/\" 1 Sk5      \
" \" SS15      5      /\" \	SSSS9/S.Er\\S'    S"SSSSSSSS\SSSSSSSSSSSS.U 4S jjjrS r\" \5      S 5       r\" \5      S  5       rS!rU =r$ )#SGDClassifieri  a^+  Linear classifiers (SVM, logistic regression, etc.) with SGD training.

This estimator implements regularized linear models with stochastic
gradient descent (SGD) learning: the gradient of the loss is estimated
each sample at a time and the model is updated along the way with a
decreasing strength schedule (aka learning rate). SGD allows minibatch
(online/out-of-core) learning via the `partial_fit` method.
For best results using the default learning rate schedule, the data should
have zero mean and unit variance.

This implementation works with data represented as dense or sparse arrays
of floating point values for the features. The model it fits can be
controlled with the loss parameter; by default, it fits a linear support
vector machine (SVM).

The regularizer is a penalty added to the loss function that shrinks model
parameters towards the zero vector using either the squared euclidean norm
L2 or the absolute norm L1 or a combination of both (Elastic Net). If the
parameter update crosses the 0.0 value because of the regularizer, the
update is truncated to 0.0 to allow for learning sparse models and achieve
online feature selection.

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

Parameters
----------
loss : {'hinge', 'log_loss', 'modified_huber', 'squared_hinge',        'perceptron', 'squared_error', 'huber', 'epsilon_insensitive',        'squared_epsilon_insensitive'}, default='hinge'
    The loss function to be used.

    - 'hinge' gives a linear SVM.
    - 'log_loss' gives logistic regression, a probabilistic classifier.
    - 'modified_huber' is another smooth loss that brings tolerance to
      outliers as well as probability estimates.
    - 'squared_hinge' is like hinge but is quadratically penalized.
    - 'perceptron' is the linear loss used by the perceptron algorithm.
    - The other losses, 'squared_error', 'huber', 'epsilon_insensitive' and
      'squared_epsilon_insensitive' are designed for regression but can be useful
      in classification as well; see
      :class:`~sklearn.linear_model.SGDRegressor` for a description.

    More details about the losses formulas can be found in the :ref:`User Guide
    <sgd_mathematical_formulation>` and you can find a visualisation of the loss
    functions in
    :ref:`sphx_glr_auto_examples_linear_model_plot_sgd_loss_functions.py`.

penalty : {'l2', 'l1', 'elasticnet', None}, default='l2'
    The penalty (aka regularization term) to be used. Defaults to 'l2'
    which is the standard regularizer for linear SVM models. 'l1' and
    'elasticnet' might bring sparsity to the model (feature selection)
    not achievable with 'l2'. No penalty is added when set to `None`.

    You can see a visualisation of the penalties in
    :ref:`sphx_glr_auto_examples_linear_model_plot_sgd_penalties.py`.

alpha : float, default=0.0001
    Constant that multiplies the regularization term. The higher the
    value, the stronger the regularization. Also used to compute the
    learning rate when `learning_rate` is set to 'optimal'.
    Values must be in the range `[0.0, inf)`.

l1_ratio : float, default=0.15
    The Elastic Net mixing parameter, with 0 <= l1_ratio <= 1.
    l1_ratio=0 corresponds to L2 penalty, l1_ratio=1 to L1.
    Only used if `penalty` is 'elasticnet'.
    Values must be in the range `[0.0, 1.0]` or can be `None` if
    `penalty` is not `elasticnet`.

    .. versionchanged:: 1.7
        `l1_ratio` can be `None` when `penalty` is not "elasticnet".

fit_intercept : bool, default=True
    Whether the intercept should be estimated or not. If False, the
    data is assumed to be already centered.

max_iter : int, default=1000
    The maximum number of passes over the training data (aka epochs).
    It only impacts the behavior in the ``fit`` method, and not the
    :meth:`partial_fit` method.
    Values must be in the range `[1, inf)`.

    .. versionadded:: 0.19

tol : float or None, default=1e-3
    The stopping criterion. If it is not None, training will stop
    when (loss > best_loss - tol) for ``n_iter_no_change`` consecutive
    epochs.
    Convergence is checked against the training loss or the
    validation loss depending on the `early_stopping` parameter.
    Values must be in the range `[0.0, inf)`.

    .. versionadded:: 0.19

shuffle : bool, default=True
    Whether or not the training data should be shuffled after each epoch.

verbose : int, default=0
    The verbosity level.
    Values must be in the range `[0, inf)`.

epsilon : float, default=0.1
    Epsilon in the epsilon-insensitive loss functions; only if `loss` is
    'huber', 'epsilon_insensitive', or 'squared_epsilon_insensitive'.
    For 'huber', determines the threshold at which it becomes less
    important to get the prediction exactly right.
    For epsilon-insensitive, any differences between the current prediction
    and the correct label are ignored if they are less than this threshold.
    Values must be in the range `[0.0, inf)`.

n_jobs : int, default=None
    The number of CPUs to use to do the OVA (One Versus All, for
    multi-class problems) computation.
    ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
    ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
    for more details.

random_state : int, RandomState instance, default=None
    Used for shuffling the data, when ``shuffle`` is set to ``True``.
    Pass an int for reproducible output across multiple function calls.
    See :term:`Glossary <random_state>`.
    Integer values must be in the range `[0, 2**32 - 1]`.

learning_rate : str, default='optimal'
    The learning rate schedule:

    - 'constant': `eta = eta0`
    - 'optimal': `eta = 1.0 / (alpha * (t + t0))`
      where `t0` is chosen by a heuristic proposed by Leon Bottou.
    - 'invscaling': `eta = eta0 / pow(t, power_t)`
    - 'adaptive': `eta = eta0`, as long as the training keeps decreasing.
      Each time n_iter_no_change consecutive epochs fail to decrease the
      training loss by tol or fail to increase validation score by tol if
      `early_stopping` is `True`, the current learning rate is divided by 5.

    .. versionadded:: 0.20
        Added 'adaptive' option.

eta0 : float, default=0.0
    The initial learning rate for the 'constant', 'invscaling' or
    'adaptive' schedules. The default value is 0.0 as eta0 is not used by
    the default schedule 'optimal'.
    Values must be in the range `[0.0, inf)`.

power_t : float, default=0.5
    The exponent for inverse scaling learning rate.
    Values must be in the range `(-inf, inf)`.

early_stopping : bool, default=False
    Whether to use early stopping to terminate training when validation
    score is not improving. If set to `True`, it will automatically set aside
    a stratified fraction of training data as validation and terminate
    training when validation score returned by the `score` method is not
    improving by at least tol for n_iter_no_change consecutive epochs.

    See :ref:`sphx_glr_auto_examples_linear_model_plot_sgd_early_stopping.py` for an
    example of the effects of early stopping.

    .. versionadded:: 0.20
        Added 'early_stopping' option

validation_fraction : float, default=0.1
    The proportion of training data to set aside as validation set for
    early stopping. Must be between 0 and 1.
    Only used if `early_stopping` is True.
    Values must be in the range `(0.0, 1.0)`.

    .. versionadded:: 0.20
        Added 'validation_fraction' option

n_iter_no_change : int, default=5
    Number of iterations with no improvement to wait before stopping
    fitting.
    Convergence is checked against the training loss or the
    validation loss depending on the `early_stopping` parameter.
    Integer values must be in the range `[1, max_iter)`.

    .. versionadded:: 0.20
        Added 'n_iter_no_change' option

class_weight : dict, {class_label: weight} or "balanced", default=None
    Preset for the class_weight fit parameter.

    Weights associated with classes. 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))``.

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.
    See :term:`the Glossary <warm_start>`.

    Repeatedly calling fit or partial_fit when warm_start is True can
    result in a different solution than when calling fit a single time
    because of the way the data is shuffled.
    If a dynamic learning rate is used, the learning rate is adapted
    depending on the number of samples already seen. Calling ``fit`` resets
    this counter, while ``partial_fit`` will result in increasing the
    existing counter.

average : bool or int, default=False
    When set to `True`, computes the averaged SGD weights across all
    updates and stores the result in the ``coef_`` attribute. If set to
    an int greater than 1, averaging will begin once the total number of
    samples seen reaches `average`. So ``average=10`` will begin
    averaging after seeing 10 samples.
    Integer values must be in the range `[1, n_samples]`.

Attributes
----------
coef_ : ndarray of shape (1, n_features) if n_classes == 2 else             (n_classes, n_features)
    Weights assigned to the features.

intercept_ : ndarray of shape (1,) if n_classes == 2 else (n_classes,)
    Constants in decision function.

n_iter_ : int
    The actual number of iterations before reaching the stopping criterion.
    For multiclass fits, it is the maximum over every binary fit.

classes_ : array of shape (n_classes,)

t_ : int
    Number of weight updates performed during training.
    Same as ``(n_iter_ * n_samples + 1)``.

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
--------
sklearn.svm.LinearSVC : Linear support vector classification.
LogisticRegression : Logistic regression.
Perceptron : Inherits from SGDClassifier. ``Perceptron()`` is equivalent to
    ``SGDClassifier(loss="perceptron", eta0=1, learning_rate="constant",
    penalty=None)``.

Examples
--------
>>> import numpy as np
>>> from sklearn.linear_model import SGDClassifier
>>> from sklearn.preprocessing import StandardScaler
>>> from sklearn.pipeline import make_pipeline
>>> X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]])
>>> Y = np.array([1, 1, 2, 2])
>>> # Always scale the input. The most convenient way is to use a pipeline.
>>> clf = make_pipeline(StandardScaler(),
...                     SGDClassifier(max_iter=1000, tol=1e-3))
>>> clf.fit(X, Y)
Pipeline(steps=[('standardscaler', StandardScaler()),
                ('sgdclassifier', SGDClassifier())])
>>> print(clf.predict([[-0.8, -1]]))
[1]
>   r8   r7   r9   Nr   rd   re   r!   bothri   >   r1   r3   r0   r2   r4   r5   )rx   ry   r{   r   r|   r}   r~   rp   r7   rq   rs   Trt   ru   r1   rv   rw   Fr:   r.   r  c                H   > [         TU ]  UUUUUUUUU	U
UUUUUUUUUUUS9  g )N)r   rx   ry   r{   rj   rk   rl   rm   rg   r|   r  rh   r}   r~   r   r   r   r   r  rn   ro   r  rH   r  s                         rG   rH   SGDClassifier.__init__  sV    2 	'%') 3-%!+ 	 	
rJ   c                 T    U R                   S;  a  [        SU R                   -  5      eg)N)r   r   z3probability estimates are not available for loss=%rT)r   AttributeErrorr   s    rG   _check_probaSGDClassifier._check_proba  s-    99:: E		Q  rJ   c                    [        U 5        U R                  S:X  a  U R                  U5      $ U R                  S:X  Ga  [        U R                  5      S:H  nU R                  U5      nU(       a/  [        R                  " UR                  S   S45      nUSS2S4   nOUn[        R                  " USSU5        US-  nUS	-  nU(       a  WSS2S4==   U-  ss'   UnU$ UR                  SS
9nUS:H  n[        R                  " U5      (       a  SXWSS24'   [        U R                  5      Xg'   XVR                  UR                  S   S45      -  nU$ [        SU R                  -  5      e)a  Probability estimates.

This method is only available for log loss and modified Huber loss.

Multiclass probability estimates are derived from binary (one-vs.-rest)
estimates by simple normalization, as recommended by Zadrozny and
Elkan.

Binary probability estimates for loss="modified_huber" are given by
(clip(decision_function(X), -1, 1) + 1) / 2. For other loss functions
it is necessary to perform proper probability calibration by wrapping
the classifier with
:class:`~sklearn.calibration.CalibratedClassifierCV` instead.

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

Returns
-------
ndarray 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_`.

References
----------
Zadrozny and Elkan, "Transforming classifier scores into multiclass
probability estimates", SIGKDD'02,
https://dl.acm.org/doi/pdf/10.1145/775047.775151

The justification for the formula in the loss="modified_huber"
case is in the appendix B in:
http://jmlr.csail.mit.edu/papers/volume2/zhang02c/zhang02c.pdf
r   r   r   r   Nr!   rL   rr   g       @)axisz[predict_(log_)proba only supported when loss='log_loss' or loss='modified_huber' (%r given))r   r   _predict_proba_lrr   rA   decision_functionrO   r   r   clipsumr   rM   NotImplementedError)rE   r   binaryscoresprob2probprob_sumall_zeros           rG   predict_probaSGDClassifier.predict_proba  s]   J 	99
"))!,,YY**'1,F++A.Fa! 45QT{GGFB4(CKDCKDadt# K  888+#q=66(##()D1%),T]]);H& (($**Q-)<==K &#yy) rJ   c                 L    [         R                  " U R                  U5      5      $ )aA  Log of probability estimates.

This method is only available for log loss and modified Huber loss.

When loss="modified_huber", probability estimates may be hard zeros
and ones, so taking the logarithm is not possible.

See ``predict_proba`` for details.

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

Returns
-------
T : array-like, 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_`.
)rO   logri  rE   r   s     rG   predict_log_probaSGDClassifier.predict_log_probaM  s    . vvd((+,,rJ   r_   rK  )rY   rZ   r[   r\   r]   r   rp   r   r   r   r   r   r   rN  rH   rZ  r   ri  rn  r^   rP  rQ  s   @rG   rS  rS    s?   IV$

2
2$9:DA4D89dAq8$?T4i@AT1d6:;HI:uen-.
 $478$D   /
 //
 /
b ,N  N` ,-  -rJ   rS  c                   \  ^  \ rS rSr% \4\\4\\4\\4S.r	0 \
R                  E\" \" \	5      5      /S/\" \SSSS9/\" \SSS	S9/S
.Er\\S'   \ S$SSSSSSSS\SSSSSSSSSS.U 4S jjj5       rS r\" SS9S%S j5       r   S&S jr\" SS9S&S j5       rS rS  rS! rU 4S" jrS#rU =r$ )'BaseSGDRegressorig  )r   r   r   r   rc   r   r!   ri   re   Nrd   )r   r   r   r   rp   r7   rq   rs   Trt   ru   r2   {Gz?      ?Fr:   r.   rx   ry   r{   rj   rk   rl   rm   rg   r|   rh   r}   r~   r   r   r   r   rn   ro   c                D   > [         TU ]  UUUUUUUUU	U
UUUUUUUUUS9  g r  rV  rE   r   rx   ry   r{   rj   rk   rl   rm   rg   r|   rh   r}   r~   r   r   r   r   rn   ro   r  s                       rG   rH   BaseSGDRegressor.__init__w  sP    0 	'%') 3-!' 	 	
rJ   c                 <   [        U SS 5      S L n[        U UUSSS[        R                  [        R                  /SUS9	u  pUR                  UR                  SS9nUR                  u  p[        XUR                  S9nU(       a  U R                  SUUR                  U	U
S	9  U R                  S
:  aW  [        U SS 5      cI  [        R                  " XR                  SS9U l        [        R                  " SUR                  SS9U l        U R                  XX4XVX5        U $ )NrN   r  Frz   )r  copyr   r   r  r  )ry  r   r!   r  r   r   r   )r  r    rO   r  r   astyper   r   r   r   ro   r   r   r   _fit_regressor)rE   r   r   ry   rz   r   r}   rk   r   r   r   r  r   r   s                 rG   r  BaseSGDRegressor._partial_fit  s    T7D1T9
::rzz* %

 HHQWW5H) !	,]QWWM ((%GG#- )  <<!ot D L!#*GG3!OD&(hhqs&KD#%D	
 rJ   r5  c                     [        U S5      (       d  U R                  SS9  U R                  UUU R                  SU R                  U R
                  SUSSS9
$ )a  Perform one epoch of stochastic gradient descent on given samples.

Internally, this method uses ``max_iter = 1``. Therefore, it is not
guaranteed that a minimum of the cost function is reached after calling
it once. Matters such as objective convergence and early stopping
should be handled by the user.

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

y : numpy array of shape (n_samples,)
    Subset of target values.

sample_weight : array-like, shape (n_samples,), default=None
    Weights applied to individual samples.
    If not provided, uniform weights are assumed.

Returns
-------
self : object
    Returns an instance of self.
rN   Tr8  rr   r!   N)rz   r   r}   rk   r   r   r   )r  r   r  ry   r   r}   )rE   r   r   r   s       rG   r:  BaseSGDRegressor.partial_fit  sf    4 tW%%&&t&<  JJ,,' ! 
 	
rJ   c
                    U R                   (       a-  [        U SS 5      b  Uc  U R                  nUc  U R                  nOS U l        S U l        SU l        U R                  UUUUUUU R                  U	UU5
        U R                  bT  U R                  [        R                  * :  a5  U R                  U R                  :X  a  [        R                  " S[        5        U $ NrN   rr   r  )rn   r  rN   rQ   r@   r  rk   rl   rO   r   r   r   r!  r   )
rE   r   r   ry   rz   r   r}   r   r   r   s
             rG   r"  BaseSGDRegressor._fit  s     ??wtWd;G  JJ	%!%DJ"DO MM	
 HH BFF7"-MM' # rJ   c                     U R                  5         U R                  UUU R                  SU R                  U R                  UUUS9	$ )az  Fit linear model with Stochastic Gradient Descent.

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

y : ndarray of shape (n_samples,)
    Target values.

coef_init : ndarray of shape (n_features,), default=None
    The initial coefficients to warm-start the optimization.

intercept_init : ndarray of shape (1,), default=None
    The initial intercept to warm-start the optimization.

sample_weight : array-like, shape (n_samples,), default=None
    Weights applied to individual samples (1. for unweighted).

Returns
-------
self : object
    Fitted `SGDRegressor` estimator.
rr   r=  r>  r?  s         rG   r   BaseSGDRegressor.fit6  sO    4 	""$yy**,,)'  

 
	
rJ   c                     [        U 5        [        XSSS9n[        XR                  R                  SS9U R
                  -   nUR                  5       $ )zPredict using the linear model

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

Returns
-------
ndarray of shape (n_samples,)
   Predicted target values per element in X.
r  Fr  r  Tdense_output)r   r    r   rN   TrQ   r   )rE   r   rd  s      rG   _decision_function#BaseSGDRegressor._decision_function^  sC     	$eD JJLLtDtV||~rJ   c                 $    U R                  U5      $ )zPredict using the linear model.

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

Returns
-------
ndarray of shape (n_samples,)
   Predicted target values per element in X.
)r  rm  s     rG   predictBaseSGDRegressor.predictq  s     &&q))rJ   c	                    U R                  U5      n	U R                  U R                  5      n
U R                  U5      n[	        U S5      (       d  SU l        U R                  X'S:  S9nU R                  XX'5      n[        U R                  5      nUR                  S[        5      n[        XX~S9u  nnU R                  b  U R                  O[        R                  * nU R                   (       a1  U R"                  nU R$                  nU R&                  nU R(                  nOU R*                  nU R,                  nS nS/n[/        UR0                  S9nU" UUS   UUS   U	U
UUU R3                  5       UUU R4                  U[7        U R8                  5      UU[7        U R:                  5      [7        U R<                  5      [7        U R>                  5      USSUU R@                  U RB                  SU R
                  UU R                   5      u  nnnnU l"        U =R
                  U RD                  URF                  S   -  -  sl        U R                   S:  a  [        RH                  " U5      U l        [        RH                  " U5      U l        U R                   U R
                  S-
  ::  a#  UU l        [        RH                  " U5      U l        g UU l        [        RH                  " U5      U l        g [        RH                  " U5      U l        g )Nr@   rr   r   r   r   r   )%r   r   rx   r   r  r@   r   r   r   rh   r   r   r$   rl   rO   r   ro   r   r   r   r   rN   rQ   r   r   r   r   r   r   rj   rg   rm   r~   r   r   r   rP   )rE   r   r   ry   rz   r   r}   r   rk   loss_functionr   r   r   r   rh   r   r   r   rl   rS   rT   r   r   r   s                           rG   r{  BaseSGDRegressor._fit_regressor  s    //5--dll;!99-HtT""DG55aUVEV5W"<<
 *$*;*;< ##Aw/#/-$
  ((.dhhRVVG<<&&D00I--L $ 7 7::DIL!",D
ISaLa  %%&""#IILLGGLL;J
Fi'8$,@ 	4<<!''!*,,<<!&(mm4E&FD#')}}Y'?D$||tww},)
"$--0A"B!
"$--	": !mmI6DOrJ   c                 F   > [         TU ]  5       nSUR                  l        U$ rB  rC  rG  s     rG   rD  !BaseSGDRegressor.__sklearn_tags__  rJ  rJ   )r   r   r   rN   rQ   r   r@   r   rX   rL  ) rY   rZ   r[   r\   r	   r
   rN  r%   r(   r   ra   rp   r   rO  r   r   r   r   r   r   rH   r  r   r:  r"  r   r  r  r{  rD  r^   rP  rQ  s   @rG   rq  rq  g  sC   ,./ 2OD(A?'S	N$

(
($C/01$+ (q!I FG%h4GH$D   +
 "++
 +
 +
Z0d 5'
 6'
b 3j 5%
 6%
N&*U7n rJ   rq  c                   .  ^  \ rS rSr% Sr0 \R                  E\" 1 Sk5      S/\" \	SSSS9/\" \	SSS	S9S/\" \	SSS
S9/\" 1 Sk5      \
" \" SS15      5      /\" \	SSSS9/\" \	SSSS9/S.Er\\S'    SSSSSSSSS\SSSSSSSSSS.U 4S jjjrSrU =r$ ) SGDRegressori  a$  Linear model fitted by minimizing a regularized empirical loss with SGD.

SGD stands for Stochastic Gradient Descent: the gradient of the loss is
estimated each sample at a time and the model is updated along the way with
a decreasing strength schedule (aka learning rate).

The regularizer is a penalty added to the loss function that shrinks model
parameters towards the zero vector using either the squared euclidean norm
L2 or the absolute norm L1 or a combination of both (Elastic Net). If the
parameter update crosses the 0.0 value because of the regularizer, the
update is truncated to 0.0 to allow for learning sparse models and achieve
online feature selection.

This implementation works with data represented as dense numpy arrays of
floating point values for the features.

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

Parameters
----------
loss : str, default='squared_error'
    The loss function to be used. The possible values are 'squared_error',
    'huber', 'epsilon_insensitive', or 'squared_epsilon_insensitive'

    The 'squared_error' refers to the ordinary least squares fit.
    'huber' modifies 'squared_error' to focus less on getting outliers
    correct by switching from squared to linear loss past a distance of
    epsilon. 'epsilon_insensitive' ignores errors less than epsilon and is
    linear past that; this is the loss function used in SVR.
    'squared_epsilon_insensitive' is the same but becomes squared loss past
    a tolerance of epsilon.

    More details about the losses formulas can be found in the
    :ref:`User Guide <sgd_mathematical_formulation>`.

penalty : {'l2', 'l1', 'elasticnet', None}, default='l2'
    The penalty (aka regularization term) to be used. Defaults to 'l2'
    which is the standard regularizer for linear SVM models. 'l1' and
    'elasticnet' might bring sparsity to the model (feature selection)
    not achievable with 'l2'. No penalty is added when set to `None`.

    You can see a visualisation of the penalties in
    :ref:`sphx_glr_auto_examples_linear_model_plot_sgd_penalties.py`.

alpha : float, default=0.0001
    Constant that multiplies the regularization term. The higher the
    value, the stronger the regularization. Also used to compute the
    learning rate when `learning_rate` is set to 'optimal'.
    Values must be in the range `[0.0, inf)`.

l1_ratio : float, default=0.15
    The Elastic Net mixing parameter, with 0 <= l1_ratio <= 1.
    l1_ratio=0 corresponds to L2 penalty, l1_ratio=1 to L1.
    Only used if `penalty` is 'elasticnet'.
    Values must be in the range `[0.0, 1.0]` or can be `None` if
    `penalty` is not `elasticnet`.

    .. versionchanged:: 1.7
        `l1_ratio` can be `None` when `penalty` is not "elasticnet".

fit_intercept : bool, default=True
    Whether the intercept should be estimated or not. If False, the
    data is assumed to be already centered.

max_iter : int, default=1000
    The maximum number of passes over the training data (aka epochs).
    It only impacts the behavior in the ``fit`` method, and not the
    :meth:`partial_fit` method.
    Values must be in the range `[1, inf)`.

    .. versionadded:: 0.19

tol : float or None, default=1e-3
    The stopping criterion. If it is not None, training will stop
    when (loss > best_loss - tol) for ``n_iter_no_change`` consecutive
    epochs.
    Convergence is checked against the training loss or the
    validation loss depending on the `early_stopping` parameter.
    Values must be in the range `[0.0, inf)`.

    .. versionadded:: 0.19

shuffle : bool, default=True
    Whether or not the training data should be shuffled after each epoch.

verbose : int, default=0
    The verbosity level.
    Values must be in the range `[0, inf)`.

epsilon : float, default=0.1
    Epsilon in the epsilon-insensitive loss functions; only if `loss` is
    'huber', 'epsilon_insensitive', or 'squared_epsilon_insensitive'.
    For 'huber', determines the threshold at which it becomes less
    important to get the prediction exactly right.
    For epsilon-insensitive, any differences between the current prediction
    and the correct label are ignored if they are less than this threshold.
    Values must be in the range `[0.0, inf)`.

random_state : int, RandomState instance, default=None
    Used for shuffling the data, when ``shuffle`` is set to ``True``.
    Pass an int for reproducible output across multiple function calls.
    See :term:`Glossary <random_state>`.

learning_rate : str, default='invscaling'
    The learning rate schedule:

    - 'constant': `eta = eta0`
    - 'optimal': `eta = 1.0 / (alpha * (t + t0))`
      where t0 is chosen by a heuristic proposed by Leon Bottou.
    - 'invscaling': `eta = eta0 / pow(t, power_t)`
    - 'adaptive': eta = eta0, as long as the training keeps decreasing.
      Each time n_iter_no_change consecutive epochs fail to decrease the
      training loss by tol or fail to increase validation score by tol if
      early_stopping is True, the current learning rate is divided by 5.

    .. versionadded:: 0.20
        Added 'adaptive' option.

eta0 : float, default=0.01
    The initial learning rate for the 'constant', 'invscaling' or
    'adaptive' schedules. The default value is 0.01.
    Values must be in the range `[0.0, inf)`.

power_t : float, default=0.25
    The exponent for inverse scaling learning rate.
    Values must be in the range `(-inf, inf)`.

early_stopping : bool, default=False
    Whether to use early stopping to terminate training when validation
    score is not improving. If set to True, it will automatically set aside
    a fraction of training data as validation and terminate
    training when validation score returned by the `score` method is not
    improving by at least `tol` for `n_iter_no_change` consecutive
    epochs.

    See :ref:`sphx_glr_auto_examples_linear_model_plot_sgd_early_stopping.py` for an
    example of the effects of early stopping.

    .. versionadded:: 0.20
        Added 'early_stopping' option

validation_fraction : float, default=0.1
    The proportion of training data to set aside as validation set for
    early stopping. Must be between 0 and 1.
    Only used if `early_stopping` is True.
    Values must be in the range `(0.0, 1.0)`.

    .. versionadded:: 0.20
        Added 'validation_fraction' option

n_iter_no_change : int, default=5
    Number of iterations with no improvement to wait before stopping
    fitting.
    Convergence is checked against the training loss or the
    validation loss depending on the `early_stopping` parameter.
    Integer values must be in the range `[1, max_iter)`.

    .. versionadded:: 0.20
        Added 'n_iter_no_change' option

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.
    See :term:`the Glossary <warm_start>`.

    Repeatedly calling fit or partial_fit when warm_start is True can
    result in a different solution than when calling fit a single time
    because of the way the data is shuffled.
    If a dynamic learning rate is used, the learning rate is adapted
    depending on the number of samples already seen. Calling ``fit`` resets
    this counter, while ``partial_fit``  will result in increasing the
    existing counter.

average : bool or int, default=False
    When set to True, computes the averaged SGD weights across all
    updates and stores the result in the ``coef_`` attribute. If set to
    an int greater than 1, averaging will begin once the total number of
    samples seen reaches `average`. So ``average=10`` will begin
    averaging after seeing 10 samples.

Attributes
----------
coef_ : ndarray of shape (n_features,)
    Weights assigned to the features.

intercept_ : ndarray of shape (1,)
    The intercept term.

n_iter_ : int
    The actual number of iterations before reaching the stopping criterion.

t_ : int
    Number of weight updates performed during training.
    Same as ``(n_iter_ * n_samples + 1)``.

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
--------
HuberRegressor : Linear regression model that is robust to outliers.
Lars : Least Angle Regression model.
Lasso : Linear Model trained with L1 prior as regularizer.
RANSACRegressor : RANSAC (RANdom SAmple Consensus) algorithm.
Ridge : Linear least squares with l2 regularization.
sklearn.svm.SVR : Epsilon-Support Vector Regression.
TheilSenRegressor : Theil-Sen Estimator robust multivariate regression model.

Examples
--------
>>> import numpy as np
>>> from sklearn.linear_model import SGDRegressor
>>> from sklearn.pipeline import make_pipeline
>>> from sklearn.preprocessing import StandardScaler
>>> n_samples, n_features = 10, 5
>>> rng = np.random.RandomState(0)
>>> y = rng.randn(n_samples)
>>> X = rng.randn(n_samples, n_features)
>>> # Always scale the input. The most convenient way is to use a pipeline.
>>> reg = make_pipeline(StandardScaler(),
...                     SGDRegressor(max_iter=1000, tol=1e-3))
>>> reg.fit(X, y)
Pipeline(steps=[('standardscaler', StandardScaler()),
                ('sgdregressor', SGDRegressor())])
>   r8   r7   r9   Nr   rd   re   r!   rT  ri   >   r1   r3   r0   r2   r4   r5   )rx   ry   r{   r   r}   r|   r~   rp   r7   rq   rs   Trt   ru   r2   rr  rs  Fr:   r.   rt  c                D   > [         TU ]  UUUUUUUUU	U
UUUUUUUUUS9  g r  rV  rv  s                       rG   rH   SGDRegressor.__init__  sP    . 	'%') 3-!' 	 	
rJ   r_   r  )rY   rZ   r[   r\   r]   rq  rp   r   r   r   r   r   r   rN  rH   r^   rP  rQ  s   @rG   r  r    s    hT$

1
1$9:DA4D89dAq8$?T4i@AHI:uen-.
 T1d6:;$478$D   +
 "++
 +
rJ   r  c                   \  ^  \ rS rSr% SrS\S40r0 \R                  E\	" \
SSSS9/\" 1 Sk5      \" \" S	S
15      5      /\	" \
SSSS9/\	" \
SSSS9/S.Er\\S'               SU 4S jjrS rS r\" SS9SS j5       r   S S jr\" SS9S!S j5       rS rS rS rU 4S jrSrU =r$ )"SGDOneClassSVMi  a2  Solves linear One-Class SVM using Stochastic Gradient Descent.

This implementation is meant to be used with a kernel approximation
technique (e.g. `sklearn.kernel_approximation.Nystroem`) to obtain results
similar to `sklearn.svm.OneClassSVM` which uses a Gaussian kernel by
default.

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

.. versionadded:: 1.0

Parameters
----------
nu : float, default=0.5
    The nu parameter of the One Class SVM: an upper bound on the
    fraction of training errors and a lower bound of the fraction of
    support vectors. Should be in the interval (0, 1]. By default 0.5
    will be taken.

fit_intercept : bool, default=True
    Whether the intercept should be estimated or not. Defaults to True.

max_iter : int, default=1000
    The maximum number of passes over the training data (aka epochs).
    It only impacts the behavior in the ``fit`` method, and not the
    `partial_fit`. Defaults to 1000.
    Values must be in the range `[1, inf)`.

tol : float or None, default=1e-3
    The stopping criterion. If it is not None, the iterations will stop
    when (loss > previous_loss - tol). Defaults to 1e-3.
    Values must be in the range `[0.0, inf)`.

shuffle : bool, default=True
    Whether or not the training data should be shuffled after each epoch.
    Defaults to True.

verbose : int, default=0
    The verbosity level.

random_state : int, RandomState instance or None, default=None
    The seed of the pseudo random number generator to use when shuffling
    the data.  If int, random_state is the seed used by the random number
    generator; If RandomState instance, random_state is the random number
    generator; If None, the random number generator is the RandomState
    instance used by `np.random`.

learning_rate : {'constant', 'optimal', 'invscaling', 'adaptive'}, default='optimal'
    The learning rate schedule to use with `fit`. (If using `partial_fit`,
    learning rate must be controlled directly).

    - 'constant': `eta = eta0`
    - 'optimal': `eta = 1.0 / (alpha * (t + t0))`
      where t0 is chosen by a heuristic proposed by Leon Bottou.
    - 'invscaling': `eta = eta0 / pow(t, power_t)`
    - 'adaptive': eta = eta0, as long as the training keeps decreasing.
      Each time n_iter_no_change consecutive epochs fail to decrease the
      training loss by tol or fail to increase validation score by tol if
      early_stopping is True, the current learning rate is divided by 5.

eta0 : float, default=0.0
    The initial learning rate for the 'constant', 'invscaling' or
    'adaptive' schedules. The default value is 0.0 as eta0 is not used by
    the default schedule 'optimal'.
    Values must be in the range `[0.0, inf)`.

power_t : float, default=0.5
    The exponent for inverse scaling learning rate.
    Values must be in the range `(-inf, inf)`.

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.
    See :term:`the Glossary <warm_start>`.

    Repeatedly calling fit or partial_fit when warm_start is True can
    result in a different solution than when calling fit a single time
    because of the way the data is shuffled.
    If a dynamic learning rate is used, the learning rate is adapted
    depending on the number of samples already seen. Calling ``fit`` resets
    this counter, while ``partial_fit``  will result in increasing the
    existing counter.

average : bool or int, default=False
    When set to True, computes the averaged SGD weights and stores the
    result in the ``coef_`` attribute. If set to an int greater than 1,
    averaging will begin once the total number of samples seen reaches
    average. So ``average=10`` will begin averaging after seeing 10
    samples.

Attributes
----------
coef_ : ndarray of shape (1, n_features)
    Weights assigned to the features.

offset_ : ndarray of shape (1,)
    Offset used to define the decision function from the raw scores.
    We have the relation: decision_function = score_samples - offset.

n_iter_ : int
    The actual number of iterations to reach the stopping criterion.

t_ : int
    Number of weight updates performed during training.
    Same as ``(n_iter_ * n_samples + 1)``.

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
--------
sklearn.svm.OneClassSVM : Unsupervised Outlier Detection.

Notes
-----
This estimator has a linear complexity in the number of training samples
and is thus better suited than the `sklearn.svm.OneClassSVM`
implementation for datasets with a large number of training samples (say
> 10,000).

Examples
--------
>>> import numpy as np
>>> from sklearn import linear_model
>>> X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]])
>>> clf = linear_model.SGDOneClassSVM(random_state=42)
>>> clf.fit(X)
SGDOneClassSVM(random_state=42)

>>> print(clf.predict([[4, 4]]))
[1]
r   rr   rv   rightre   >   r1   r3   r0   r2   r4   r5   r   Nrd   ri   )nur}   r~   r   rp   Tc                 X   > Xl         [        TU ]	  SSSSUUUUU[        UUU	U
SSSUUS9  g )	Nr   r7   rr   r   Fr:   r.   )r   rx   rz   r{   rj   rk   rl   rm   rg   r|   rh   r}   r~   r   r   r   r   rn   ro   )r  r  rH   rN  )rE   r  rj   rk   rl   rm   rg   rh   r}   r~   r   rn   ro   r  s                rG   rH   SGDOneClassSVM.__init__  sU     '#%'  #!' 	 	
rJ   c                 x   UR                   S   n[        R                  " XqR                  SS9n[	        XU5      u  pU R                  U R                  5      nU R                  U5      nU R                  XS:  S9nU R                  XX5      n[        U R                  5      nUR                  S[        R                  " [        R                  5      R                  5      nU R                   b  U R                   O[        R"                  * nSnSnSnU R$                  (       a1  U R&                  nU R(                  nU R*                  nU R,                  nO U R.                  nSU R0                  -
  nSnS/n[3        UR                  S9nU" UUS   UUS   U R4                  UUUU R6                  U	UU R8                  U[;        U R<                  5      UU[;        U R>                  5      [;        U R@                  5      [;        U RB                  5      UUUUU RD                  U RF                  UU RH                  U
U R$                  5      u  nnnnU l%        U =RH                  U RJ                  U-  -  sl$        U R$                  S:  a  [        RL                  " U5      U l        [        RL                  " U5      U l        U R$                  U RH                  S-
  ::  a&  UU l        S[        RL                  " U5      -
  U l        gUU l        S[        RL                  " U5      -
  U l        gS[        RL                  " U5      -
  U l        g)	z8Uses SGD implementation with X and y=np.ones(n_samples).r   rz   r   r   Nr!   r   rr   )'r   rO   r   r   r$   r   rx   r   r   r   r   rh   r   iinfoint32r/  rl   r   ro   r   r   r   r   rN   r   r   r   r{   r   r   r   rj   rg   rm   r~   r   r@   r   rP   )rE   r   ry   rz   r   r}   rk   r   r   r   offset_decayr   r   r   r   rh   r   rl   r   r   r   rS   rT   r   r   r   s                             rG   _fit_one_classSGDOneClassSVM._fit_one_class  s   
 GGAJ	GGIWWC8 ,Q= A--dll;!99-H 55aUVEV5W"<<
 *$*;*;< ##Arxx'9'='=>((.dhhRVVG	 

<<&&D00I--L $ 7 7::DDLL(IL!",D
ISaLa   MM%%&""#IILLGGLL;J
Fi'8$,@ 	4<<)++<<!&(mm4E&FD#')}}Y'?D$||tww},)
 2==1B#CC!
 2==#;; r}}Y77DLrJ   c
                    [        U SS 5      S L n
[        U US S[        R                  [        R                  /SSU
S9nUR
                  S   n[        XqUR                  S9n[        U SS 5      b  Ub  U R                  SUUR                  UU	SS9  OBXR                  R
                  S	   :w  a&  [        S
XR                  R
                  S	   4-  5      eU R                  (       aW  [        U SS 5      cI  [        R                  " XR                  SS9U l        [        R                  " SUR                  SS9U l        U R                  U5      U l        [#        U S5      (       d  SU l        U R'                  UUUUUUS9  U $ )NrN   r  rz   Fr  r!   r   )r   r   r   r   r   r   rL   r  r   r   r@   rr   r  )r  r    rO   r  r   r   r   r   r   rN   r   ro   r   r   r   r   r   r  r@   r  )rE   r   ry   rz   r   r}   rk   r   r   offset_initr  r   s               rG   r  SGDOneClassSVM._partial_fit%	  s    T7D1T9
::rzz* %	
 WWQZ
 -]QWWM
 4$'/93H((%GG#* )  ::++B//Hzz//345 
 <<GD/4@H!#*GG3!OD&(hhqs&KD##66t<tT""DG 	'' 	 	
 rJ   r5  c                     [        U S5      (       d  U R                  SS9  U R                  S-  nU R                  UUSU R                  U R
                  SUSSS9	$ )	a  Fit linear One-Class SVM with Stochastic Gradient Descent.

Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
    Subset of the training data.
y : Ignored
    Not used, present for API consistency by convention.

sample_weight : array-like, shape (n_samples,), optional
    Weights applied to individual samples.
    If not provided, uniform weights are assumed.

Returns
-------
self : object
    Returns a fitted instance of self.
rN   Tr8  r   rr   r!   N)rz   r   r}   rk   r   r   r  )r  r   r  r  r   r}   )rE   r   r   r   ry   s        rG   r:  SGDOneClassSVM.partial_fith	  sl    ( tW%%&&t&<!  ,,' ! 

 
	
rJ   c	                    U R                   (       a0  [        U S5      (       a  Uc  U R                  nUc  U R                  nOS U l        S U l        SU l        U R                  UUUUUU R                  UUU5	        U R                  bT  U R                  [        R                  * :  a5  U R                  U R                  :X  a  [        R                  " S[        5        U $ r  )rn   r  rN   r   r@   r  rk   rl   rO   r   r   r   r!  r   )	rE   r   ry   rz   r   r}   r   r  r   s	            rG   r"  SGDOneClassSVM._fit	  s     ??wtW55  JJ	""llDJDL MM
	
 HH BFF7"-MM' # rJ   c                     U R                  5         U R                  S-  nU R                  UUSU R                  U R                  UUUS9  U $ )a  Fit linear One-Class SVM with Stochastic Gradient Descent.

This solves an equivalent optimization problem of the
One-Class SVM primal optimization problem and returns a weight vector
w and an offset rho such that the decision function is given by
<w, x> - rho.

Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
    Training data.
y : Ignored
    Not used, present for API consistency by convention.

coef_init : array, shape (n_classes, n_features)
    The initial coefficients to warm-start the optimization.

offset_init : array, shape (n_classes,)
    The initial offset to warm-start the optimization.

sample_weight : array-like, shape (n_samples,), optional
    Weights applied to individual samples.
    If not provided, uniform weights are assumed. These weights will
    be multiplied with class_weight (passed through the
    constructor) if class_weight is specified.

Returns
-------
self : object
    Returns a fitted instance of self.
r   rr   )ry   rz   r   r}   r   r  r   )r   r  r"  r   r}   )rE   r   r   r   r  r   ry   s          rG   r   SGDOneClassSVM.fit	  sX    B 	""$!		,,#' 	 		
 rJ   c                     [        U S5        [        XSSS9n[        XR                  R                  SS9U R
                  -
  nUR                  5       $ )aA  Signed distance to the separating hyperplane.

Signed distance is positive for an inlier and negative for an
outlier.

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

Returns
-------
dec : array-like, shape (n_samples,)
    Decision function values of the samples.
rN   r  Fr  Tr  )r   r    r   rN   r  r   r   )rE   r   	decisionss      rG   r_   SGDOneClassSVM.decision_function	  sF    " 	g&$eD#Azz||$G$,,V	  rJ   c                 B    U R                  U5      U R                  -   nU$ )a  Raw scoring function of the samples.

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

Returns
-------
score_samples : array-like, shape (n_samples,)
    Unshiffted scoring function values of the samples.
)r_  r   )rE   r   score_sampless      rG   r  SGDOneClassSVM.score_samples
  s#     ..q1DLL@rJ   c                 v    U R                  U5      S:  R                  [        R                  5      nSX"S:H  '   U$ )zReturn labels (1 inlier, -1 outlier) of the samples.

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

Returns
-------
y : array, shape (n_samples,)
    Labels of the samples.
r   rL   )r_  rz  rO   r  r   s      rG   r  SGDOneClassSVM.predict
  s8     ##A&!+33BHH=q&	rJ   c                 F   > [         TU ]  5       nSUR                  l        U$ rB  rC  rG  s     rG   rD  SGDOneClassSVM.__sklearn_tags__)
  rJ  rJ   )	r   r   r   r   rN   r   r  r   r@   )rw   Trt   ru   Tr   Nr1   rv   rw   FFrM  rL  )NNNN)rY   rZ   r[   r\   r]   r&   r   ra   rp   r   r   r   r   r   r   rH   r  r  r   r:  r"  r   r_  r  r  rD  r^   rP  rQ  s   @rG   r  r    s(   KZ s|,N	$

(
(	$c3w78HI:uen-.
 $478T4i@A	$D 	 $
L^8@AF 5!
 6!
T 1f 5. 6.`!0 " rJ   r  )TrM  )Kr]   r   abcr   r   numbersr   r   numpyrO   _loss._lossr   r	   r
   baser   r   r   r   r   r   
exceptionsr   model_selectionr   r   utilsr   r   utils._param_validationr   r   r   utils.extmathr   utils.metaestimatorsr   utils.multiclassr   utils.parallelr   r   utils.validationr   r   r    _baser"   r#   r$   	_sgd_fastr%   r&   r'   r(   r)   r*   r+   r   r   rN  r  r  r/  r   r<   ra   r   r   r   r   rS  rq  r  r  r_   rJ   rG   <module>r     s;    ' "  M M  , B < B B + / < . S S G G     !1A> ((288

 
 I I&{
o} {
|"Ab E$PGi-w' iXz-% z-zs~w sld
# d
N	h\7 hrJ   