
    0Phg                    r   d Z ddlZddlmZmZ ddlmZmZ ddlZ	ddl
mZmZmZ ddlmZmZmZmZmZmZ ddlmZ dd	lmZmZ dd
lmZmZ ddlmZmZm Z  ddl!m"Z" ddl#m$Z$ ddl%m&Z& ddl'm(Z(m)Z) ddl*m+Z+m,Z,m-Z- ddl.m/Z/m0Z0m1Z1 ddl2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9 dddddddZ:dddddZ;dZ< e	j=        e	j>                  j?        Z@ G d d          ZA G d de0ee          ZBd.d!ZC	 	 d/d"ZDd# ZE G d$ d%e/eBe          ZF G d& d'eF          ZG G d( d)eeB          ZH G d* d+eH          ZI G d, d-eeB          ZJdS )0zVClassification, 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                        e Zd ZdZddZd ZdS )_ValidationScoreCallbackz5Callback for early stopping based on validation scoreNc                     t          |          | _        d| j        _        ||| j        _        || _        || _        || _        d S )Nr!   )r   	estimatort_classes_X_valy_valsample_weight_val)selfr>   rA   rB   rC   classess         i/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sklearn/linear_model/_stochastic_gradient.py__init__z!_ValidationScoreCallback.__init__?   sG    y))&-DN#

!2    c                     | j         }|                    dd          |_        t          j        |          |_        |                    | j        | j        | j	                  S )Nr!   )
r>   reshapecoef_np
atleast_1d
intercept_scorerA   rB   rC   )rD   coef	interceptests       rF   __call__z!_ValidationScoreCallback.__call__H   sL    nLLB''	y11yyTZ1GHHHrH   N)__name__
__module____qualname____doc__rG   rT    rH   rF   r<   r<   <   sB        ??3 3 3 3I I I I IrH   r<   c                      e Zd ZU dZdg eeddd          g eeddd          dgdgdgd	gdg eeddd          dgd
Zee	d<   dddddddddddddddddddddZ
ed             Zd#dZd Zd Zd Z	 	 	 d$d Zd! Z	 d%d"ZdS )&BaseSGDz1Base class for SGD classification and regression.booleanr!   Nleftclosedr   verboserandom_state)fit_interceptmax_itertolshufflera   rb   
warm_startaverage_parameter_constraintsr7   -C6?      ?333333?T  MbP?r:   r1                 ?Fr.   )penaltyalphaCl1_ratiorc   rd   re   rf   ra   epsilonrb   learning_rateeta0power_tearly_stoppingvalidation_fractionn_iter_no_changerg   rh   c                   || _         || _        || _        || _        || _        || _        || _        || _        |	| _        || _	        |
| _
        || _        || _        || _        || _        || _        || _        || _        || _        || _        d S rU   )lossrq   rv   ru   rr   rs   rt   rc   rf   rb   ra   rw   rx   ry   rz   r{   rg   rh   rd   re   )rD   r}   rq   rr   rs   rt   rc   rd   re   rf   ra   ru   rb   rv   rw   rx   ry   rz   r{   rg   rh   s                        rF   rG   zBaseSGD.__init__]   s    0 	*
 *(	,#6  0$ rH   c                     dS )z
Fit model.NrZ   rD   Xys      rF   fitzBaseSGD.fit   s      rH   c                 .   | j         r|rt          d          | j        dv r| j        dk    rt          d          | j        dk    r| j        dk    rt          d          |                     | j                   |                     | j                   dS )	zValidate input params.z/early_stopping should be False with partial_fit)r0   r2   r3   ro   zeta0 must be > 0r1   r   zgalpha must be > 0 since learning_rate is 'optimal'. alpha is used to compute the optimal learning rate.N)ry   
ValueErrorrv   rw   rr   _get_penalty_typerq   _get_learning_rate_type)rD   for_partial_fits     rF   _more_validate_paramszBaseSGD._more_validate_params   s     	P? 	PNOOO"HHH	S  /000**tzQ8   	t|,,,$$T%788888rH   c                 b    | j         |         }|d         |dd         }}|dv r| j        f} || S )z6Get concrete ``LossFunction`` object for str ``loss``.r   r!   N)huberepsilon_insensitivesquared_epsilon_insensitive)loss_functionsru   )rD   r}   loss_
loss_classargss        rF   _get_loss_functionzBaseSGD._get_loss_function   sF    #D) 8U122YD
RRRL?Dz4  rH   c                     t           |         S rU   )LEARNING_RATE_TYPES)rD   rv   s     rF   r   zBaseSGD._get_learning_rate_type   s    "=11rH   c                 ^    t          |                                          }t          |         S rU   )strlowerPENALTY_TYPES)rD   rq   s     rF   r   zBaseSGD._get_penalty_type   s$    g,,$$&&W%%rH   c                    |dk    r|;t          j        ||d          }|j        ||fk    rt          d          || _        nt          j        ||f|d          | _        |;t          j        |d|          }|j        |fk    rt          d          || _        n:t          j        ||d          | _        n|Nt          j        ||d          }|                                }|j        |fk    rt          d          || _        nt          j        ||d          | _        |st          j        ||	          }|j        d
k    r|j        dk    rt          d          |r|                    d          | _	        nV|                    d          | _        n;|rt          j        d|d          | _	        nt          j        d|d          | _        | j
        dk    rx| j        | _        t          j        | j        j        |d          | _        |rd| j	        z
  | _        n| j        | _        t          j        | j        j        |d          | _        dS dS )z4Allocate mem for parameters; initialize if provided.r   Nrs   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!   rZ   r!   r   )rM   asarrayshaper   rL   zerosrO   ravelrK   offset_rh   _standard_coef_average_coef_standard_intercept_average_intercept)rD   	n_classes
n_featuresinput_dtype	coef_initintercept_init	one_classs          rF   _allocate_parameter_memzBaseSGD._allocate_parameter_mem   s    q==$Jy3OOO	?y*&===$%RSSS&

X
+;c  

 )!#"#[" " " "'I<77$%VWWW"0"$(9Ks"S"S"S $Jy3OOO	%OO--	?zm33$%QRRR&

Xj3OOO
 )!#N+!N!N!N!'4//N4HB4N4N$%VWWW #1#9#9$ $DLL '5&<&<' 'DOO  P#%8A[#L#L#LDLL&(hq3&O&O&ODO <!"&*D!#
 3" " "D  ;+,t|+;((+/?(&(h(.k' ' 'D### rH   c                 j   |j         d         }t          j        |t          j                  }| j        s|S t          |           rt          }nt          } || j        | j	                  }t          |                    t          j        |j         d         df          |                    \  }}t          j        ||                   st          d          |j         d         dk    s|j         d         dk    r1t          d|| j        |j         d         |j         d         fz            d||<   |S )	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_sizerb   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   rM   r   bool_ry   r   r   r   rz   rb   nextsplitanyr   )	rD   r   sample_mask	n_samplesvalidation_masksplitter_typecv	idx_trainidx_vals	            rF   _make_validation_splitzBaseSGD._make_validation_split   sR   " GAJ	(9BH===" 	#"" 	)2MM(M].T=N
 
 
 ""((28171:q/+J+J+JA"N"NOO	7vk'*++ 	+  
 ?1""gmA&6!&;&;@
 ,OA&M!$			   $( rH   c                 `    | j         sd S t          | ||         ||         ||         |          S )NrE   )ry   r<   )rD   r   r   r   sample_weightrE   s         rF   _make_validation_score_cbz!BaseSGD._make_validation_score_cb5  sI     " 	4'oo/*
 
 
 	
rH   )F)NNr   rU   )rV   rW   rX   rY   r   r   r   ri   dict__annotations__rG   r   r   r   r   r   r   r   r   r   rZ   rH   rF   r\   r\   O   s        ;; $Xh4???@q$v666=;;'( kHXq$v>>>	J	$ 	$D 	 	 	 
-+ + + + +Z   ^9 9 9 9(! ! !2 2 2& & & K K K KZ5 5 5p =A
 
 
 
 
 
rH   r\   )	metaclassTc                 x   t          j        |j        |d          }|rd||| j        |         k    <   nd||| j        |         k    <   d}d}t	          | j                  dk    r{| j        s'| j                                        }| j        d         }	n| j	                                        }| j
        d         }	| j                                        }| j        d         }nV| j        s| j        |         }| j        |         }	n4| j	        |         }| j
        |         }	| j        |         }| j        |         }|||	||fS )zeInitialization for fit_binary.

    Returns y, coef, intercept, average_coef, average_intercept.
    rs   r   ro   g      r   Nr   )rM   onesr   r@   lenrh   rL   r   rO   r   r   r   r   )
rS   r   ir   label_encodey_iaverage_interceptaverage_coefrQ   rR   s
             rF   _prepare_fit_binaryr   D  sL   
 '!'C
8
8
8C )$'Aa !! %)Aa !L
3<A{ 	:9??$$Dq)II%++--D/2I,2244L # 6q 9{ 	:9Q<Dq)II%a(D/2I,Q/L # 6q 9i/@@@rH   c                 ^   t          | j        t                    }t          | |||j        |          \  }}}}}|j        d         |j        d         cxk    r|
j        d         k    sn J t          |          }t          |||
|          \  }}|                     | j	                  }| 
                    |          }||                     ||
dk              }t          j        ddg|j                  }|                     ||||
|	          }|                    t                     }| j        | j        nt          j         }t'          |j        
          } |||||| j        |||| j        ||| j        |t-          | j                  ||t-          | j                  t-          | j                  t-          | j                  |||	|| j        | j        d| j        || j                  \  }}}}}| j        r-t?          | j                   dk    r|| j!        d<   n
|| j!        |<   |||fS )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   rb   Nr   rJ   r!   r   r   r   r   )"
isinstance_loss_function_r   r   r   r   r   r$   r   rq   r   r   rM   arrayr   randintMAX_INTre   inf_get_plain_sgd_functionrt   ry   intr{   rc   ra   rf   rw   rx   r?   rh   r   r@   r   )rS   r   r   r   rr   rs   rv   rd   
pos_weight
neg_weightr   r   rb   r   r   rQ   rR   r   r   datasetintercept_decaypenalty_typelearning_rate_typerE   validation_score_cbseedre   
_plain_sgdn_iter_s                                rF   
fit_binaryr   i  sw   F c13EFFL<OQqw\= = =9Cy,(9 9Q<171:????)<Q)???????%l33L+	3L     G_ ((55L44]CC44SmVWFW4XXhAwci000G77C 8   ((DW(#''rvgC(TZ@@@J@J
	C !!CCKCK	;A A=D)\#4g@ { :s|!!(9C"1%%(9C"1%G##rH   c                 >    | t           j        k    rt          nt          S rU   )rM   float32r*   r+   r   s    rF   r   r     s    &"*44<<,FrH   c                       e Zd ZU edfedfedfefefefee	fe
e	fee	fd	Zi ej         e ee                    gdg eeddd          g eedd	d
          ged	g edh          ed	gdZeed<   e	 d$dddddddde	d	d	ddddddd	ddd fd            Zd Z	 	 	 d%dZd Zd Z ed           d&d!            Z ed           d%d"            Z fd#Z xZ S )'BaseSGDClassifierrk   ro   )	hingesquared_hinge
perceptronlog_lossmodified_hubersquared_errorr   r   r   r]   r   r!   neitherr_   Nr^   balanced)r}   ry   rz   r{   n_jobsclass_weightri   r   r7   rj   rl   Trm   rn   r1   rp   Fr:   r.   rq   rr   rt   rc   rd   re   rf   ra   ru   r   rb   rv   rw   rx   ry   rz   r{   r   rg   rh   c                    t                                          |||||||||	|
|||||||||           || _        || _        d S N)r}   rq   rr   rt   rc   rd   re   rf   ra   ru   rb   rv   rw   rx   ry   rz   r{   rg   rh   )superrG   r   r   rD   r}   rq   rr   rt   rc   rd   re   rf   ra   ru   r   rb   rv   rw   rx   ry   rz   r{   r   rg   rh   	__class__s                         rF   rG   zBaseSGDClassifier.__init__  st    4 	'%') 3-!' 	 	
 	
 	
* )rH   c           
         t          | d           }t          | ||dt          j        t          j        gdd|          \  }}|rKt          | j        t          t          j        f          s%| j        dk    rt          j
        dt                     |j        \  }}t          | |           | j        j        d         }t          | j        | j        |          | _        t%          |	||j        	          }	t)          | d
d           |
 |                     |||j        |
|           n:|| j        j        d         k    r$t/          d|| j        j        d         fz            |                     |          | _        t          | d          sd| _        |dk    r|                     ||||||	|           n5|dk    r|                     ||||||	|           nt/          d|z            | S )Nr@   csrrs   Faccept_sparser   r   accept_large_sparseresetr   rPassing average=0 to disable averaging is deprecated and will be removed in 1.7. Please use average=False instead.)rE   r   r   rL   r   r   r   r   r   rJ   6Number of features %d does not match previous data %d.r?   rk   r   rr   rs   rv   r   rd   z>The number of classes has to be greater than one; got %d class)hasattrr    rM   float64r   r   rh   boolr   warningswarnFutureWarningr   r   r@   r   r   _expanded_class_weightr   r   getattrr   rL   r   r   r   r?   _fit_multiclass_fit_binary)rD   r   r   rr   rs   r}   rv   rd   rE   r   r   r   
first_callr   r   r   s                   rF   _partial_fitzBaseSGDClassifier._partial_fit>  sr    !z222
:rz* %	
 	
 	
1  		dlT28,<== $,RSBSBSP "   !"	:%dG444M'*	 ';t}'
 '
 '
# -]AQWMMM4$''/93H((#%G#- )     4:+B///Htz/345  
  $66t<<tT"" 	DG q==  ++! !     !^^++!      P  
 rH   c
                    t          | d          rt          | d           t          | j        t          t
          j        f          s%| j        dk    rt          j        dt                     t          | |          }t          j        |          }
| j        r#t          | d          r|| j        }|| j        }nd | _        d | _        | j        dk    r&| j        | _        | j        | _        d | _        d | _        d| _        |                     ||||||| j        |
|	||           | j        @| j        t
          j         k    r*| j        | j        k    rt          j        dt2                     | S )Nr@   r   r   )r   rL   rk   hMaximum number of iteration reached before convergence. Consider increasing max_iter to improve the fit.)r   delattrr   rh   r  rM   r   r  r  r  r    uniquerg   rL   rO   r   r   r   r   r?   r  rd   re   r   r   r   )rD   r   r   rr   rs   r}   rv   r   r   r   rE   s              rF   _fitzBaseSGDClassifier._fit  s    4$$ 	&D*%%% $,rx(899 	dla>O>OMH    $!$$$)A,,? 	#wtW55 	#  J	%!%DJ"DO<!"&*D'+D$!%D&*D# M	
 	
 	
 H BF7""--M' #   rH   c                 R   t          | d||||||| j        d         | j        d         || j                  \  }}	}
| xj        |
|j        d         z  z  c_        |
| _        | j        dk    r| j        | j        dz
  k    r.| j                            dd          | _	        | j
        | _        dS | j                            dd          | _	        t          j        |	          | _        | j        | _        dS |                    dd          | _	        t          j        |	          | _        dS )z#Fit a binary classifier on X and y.r!   r   r   rJ   N)r   r  rb   r?   r   r   rh   r   rK   rL   r   rO   r   rM   rN   r   )rD   r   r   rr   rs   r   rv   rd   rQ   rR   r   s              rF   r	  zBaseSGDClassifier._fit_binary  s&   #-'*'**$
 $
 $
 i 	7QWQZ'' <!|tw{**!/772>>
"&"9!088B??
+-=+C+C("&":a,,DJ mI66DOOOrH   c                                           dk              t           j                  }|                    t          t           j                            }	 t           j         j	        d           f	dt          |	          D                       }
d}t          |
          D ]#\  }\  }}}| j        |<   t          ||          }$ xj        |j        d         z  z  c_        | _         j        dk    re j         j        dz
  k    r j         _         j         _        d	S  j         _        t+          j         j                   _         j         _        d	S d	S )
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   ra   requirec              3      	K   | ]<\  }} t          t                    	|	j        |         d 
|          V  =dS )rk   )r   rb   N)r   r   r  ).0r   r   rs   r   rr   rv   rd   r   rD   r   r   s      rF   	<genexpr>z4BaseSGDClassifier._fit_multiclass.<locals>.<genexpr>   s       

 

  4  GJ+A. /!  

 

 

 

 

 

rH   ro   rk   N)r   r   rb   r   r   r   r@   r   r   ra   	enumeraterO   maxr?   r   r   rh   r   rL   r   r   rM   rN   r   )rD   r   r   rr   rs   rv   r   rd   rb   seedsresultr   r   _rR   n_iter_ir   s   ````````        @rF   r  z!BaseSGDClassifier._fit_multiclass  s    55a]UVEV5WW *$*;<<$$W3t}3E3E$FF
;k
 
 


 

 

 

 

 

 

 

 

 

 

 

  %U++!

 

 


 
, +4V+<+< 	- 	-'A'9h!*DOA'8,,GG7QWQZ''<!|tw},,!/
"&"9!0
+-=+I+I("&": rH   prefer_skip_nested_validationc                    t          | d          sH|                     d           | j        dk    r't          d                    | j                            |                     ||| j        d| j        | j        d||dd	          S )
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, 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.
        r@   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.rk   r!   N)	rr   rs   r}   rv   rd   rE   r   r   r   )	r   r   r   r   formatr  rr   r}   rv   )rD   r   r   rE   r   s        rF   partial_fitzBaseSGDClassifier.partial_fitE  s    D tZ(( 	&&t&<<< J.. ! "((9!:!:
 
 
   *,' ! 
 
 	
rH   c                     |                                   |                     ||| j        d| j        | j        |||	  	        S )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.
        rk   rr   rs   r}   rv   r   r   r   r   r  rr   r}   rv   rD   r   r   r   r   r   s         rF   r   zBaseSGDClassifier.fit  sS    : 	""$$$yy*,)'  

 

 
	
rH   c                 `    t                                                      }d|j        _        |S NTr   __sklearn_tags__
input_tagssparserD   tagsr   s     rF   r,  z"BaseSGDClassifier.__sklearn_tags__  '    ww''))!%rH   r   NNNNN)!rV   rW   rX   r&   r)   r   r'   r	   r
   DEFAULT_EPSILONr%   r(   r   r\   ri   r   setr   r   r   r   r   r   rG   r  r  r	  r  r   r$  r   r,  __classcell__r   s   @rF   r   r     sU        &,cl')(*,./ 2OD(A?'S
 
N$

($CC//001$+ (q!I F F FG%Xh4GGGHT"#ZL114>$ $ $D     / // / / / / / ^/b^ ^ ^P L L L L\ 7  7  7D5; 5; 5;n \555=
 =
 =
 65=
~ \555(
 (
 (
 65(
T        rH   r   c                       e Zd ZU dZi ej         eh d          dg eeddd          g eeddd          g eeddd	          g eeddd          g eh d
           e	 eddh                    g eeddd          gdZe
ed<   	 d!ddddddddedddddddddddd fdZd Z ee          d             Z ee          d              Z xZS )"SGDClassifiera.  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]`.

    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   r^   r_   r!   bothr   >   r1   r3   r0   r2   r4   r5   )rq   rr   rt   rx   ru   rv   rw   ri   r   r7   rj   rl   Trm   rn   r1   ro   rp   Fr:   r.   r   c                t    t                                          |||||||||	|
|||||||||||           d S )N)r}   rq   rr   rt   rc   rd   re   rf   ra   ru   r   rb   rv   rw   rx   ry   rz   r{   r   rg   rh   r   rG   r   s                         rF   rG   zSGDClassifier.__init__  so    2 	'%') 3-%!+ 	 	
 	
 	
 	
 	
rH   c                 F    | j         dvrt          d| j         z            dS )N)r   r   z3probability estimates are not available for loss=%rT)r}   AttributeError)rD   s    rF   _check_probazSGDClassifier._check_proba  s3    9::: E	Q   trH   c                    t          |            | j        dk    r|                     |          S | j        dk    rt          | j                  dk    }|                     |          }|r.t          j        |j        d         df          }|dddf         }n|}t          j	        |dd|           |dz  }|d	z  }|r|dddfxx         |z  cc<   |}nu|
                    d
          }|dk    }t          j        |          r d||ddf<   t          | j                  ||<   ||                    |j        d         df          z  }|S t          d| j        z            )ah  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!   rJ   rk   g       @)axisz[predict_(log_)proba only supported when loss='log_loss' or loss='modified_huber' (%r given))r   r}   _predict_proba_lrr   r@   decision_functionrM   r   r   clipsumr   rK   NotImplementedError)rD   r   binaryscoresprob2probprob_sumall_zeros           rF   predict_probazSGDClassifier.predict_proba  s   J 	9
""))!,,,Y***''1,F++A..F a! 455QQQT{GFB4(((CKDCKD >aaadt#
  888++#q=6(## <()D111%),T]););HX& (($*Q-)<===K &#y)  rH   c                 P    t          j        |                     |                    S )a  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_`.
        )rM   logrN  rD   r   s     rF   predict_log_probazSGDClassifier.predict_log_probaU  s"    . vd((++,,,rH   r2  )rV   rW   rX   rY   r   ri   r   r   r   r   r   r   r5  rG   r@  r   rN  rR  r7  r8  s   @rF   r:  r:    s        E EN$

2$J999::DA(4D8889XdAq8889HT4i@@@AHT1d6:::;JHHHIIF::uen--..
 $47778$ $ $D     /
 //
 /
 /
 /
 /
 /
 /
b   \,N N  N` \,- -  - - - - -rH   r:  c                       e Zd ZU efeefeefeefdZi e	j
         e ee                    gdg eeddd          g eeddd          gd	Z
eed
<   e	 d#ddddddddedddddddddd fd            Zd Z ed          d$d            Z	 	 	 d%dZ ed          d%d            Zd Zd  Zd! Z fd"Z xZS )&BaseSGDRegressor)r   r   r   r   r]   r   r!   r   r_   Nr^   )r}   ry   rz   r{   ri   r   r7   rj   rl   Trm   rn   r2   {Gz?      ?Fr:   r.   rq   rr   rt   rc   rd   re   rf   ra   ru   rb   rv   rw   rx   ry   rz   r{   rg   rh   c                p    t                                          |||||||||	|
|||||||||           d S r   r=  rD   r}   rq   rr   rt   rc   rd   re   rf   ra   ru   rb   rv   rw   rx   ry   rz   r{   rg   rh   r   s                       rF   rG   zBaseSGDRegressor.__init__  si    0 	'%') 3-!' 	 	
 	
 	
 	
 	
rH   c                    t          | dd           d u }t          | ||dddt          j        t          j        gd|	  	        \  }}|                    |j        d          }|rKt          | j        t          t          j
        f          s%| j        dk    rt          j        dt                     |j        \  }}t          |||j        	          }|r|                     d
||j        |	|
           | j        dk    rSt          | dd           Bt          j        ||j        d          | _        t          j        d
|j        d          | _        |                     ||||||||           | S )NrL   r   Frs   )r   copyr   r   r   r   )r[  r   r   r   r!   r   r   r   )r  r    rM   r  r   astyper   r   rh   r  r   r  r  r  r   r   r   r   r   r   _fit_regressor)rD   r   r   rr   rs   r}   rv   rd   r   r   r   r
  r   r   s                 rF   r  zBaseSGDRegressor._partial_fit  s    T7D11T9
:rz* %

 

 

1 HHQW5H)) 		dlT28,<== $,RSBSBSP "   !"	:,]AQWMMM  	((%G#- )    <!ot D D L!#*AG3!O!O!OD&(hqs&K&K&KD#q%D-	
 	
 	
 rH   r  c                     t          | d          s|                     d           |                     ||| j        d| j        | j        d|dd
  
        S )aS  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.
        rL   Tr"  rk   r!   N)rs   r}   rv   rd   r   r   r   )r   r   r  rr   r}   rv   )rD   r   r   r   s       rF   r$  zBaseSGDRegressor.partial_fit  so    4 tW%% 	=&&t&<<<  J,' ! 
 
 	
rH   c
                    t          | j        t          t          j        f          s%| j        dk    rt          j        dt                     | j        r$t          | dd           || j
        }|| j        }nd | _
        d | _        d| _        |                     ||||||| j        |	||
  
         | j        @| j        t          j         k    r*| j        | j        k    rt          j        dt$                     | S Nr   r   rL   rk   r  )r   rh   r  rM   r   r  r  r  rg   r  rL   rO   r?   r  rd   re   r   r   r   )
rD   r   r   rr   rs   r}   rv   r   r   r   s
             rF   r  zBaseSGDRegressor._fit  s     $,rx(899 	dla>O>OMH    ? 	#wtWd;;G  J	%!%DJ"DO M	
 	
 	
 H BF7""--M' #   rH   c                     |                                   |                     ||| j        d| j        | j        |||	  	        S )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_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.
        rk   r&  r'  r(  s         rF   r   zBaseSGDRegressor.fitS  sS    4 	""$$$yy*,)'  

 

 
	
rH   c                     t          |            t          | |dd          }t          || j        j        d          | j        z   }|                                S )a  Predict 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   rL   TrO   r   )rD   r   rI  s      rF   _decision_functionz#BaseSGDRegressor._decision_function{  sU     	$eDDD DJLtDDDtV||~~rH   c                 ,    |                      |          S )a*  Predict 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.
        )rg  rQ  s     rF   predictzBaseSGDRegressor.predict  s     &&q)))rH   c	                 b   |                      |          }	|                     | j                  }
|                     |          }t	          | d          sd| _        |                     ||dk              }|                     ||||          }t          | j	                  }|
                    dt                    }t          ||||          \  }}| j        | j        nt          j         }| j        r| j        }| j        }| j        }| j        }n| j        }| j        }d }dg}t/          |j                  } |||d         ||d         |	|
||| j        ||| j        |t7          | j                  ||t7          | j                  t7          | j                  t7          | j                  |dd|| j         | j!        d| j        || j                  \  }}}}| _"        | xj        | j"        |j#        d         z  z  c_        | j        dk    rt          j$        |          | _        t          j$        |          | _        | j        | j        dz
  k    r"|| _        t          j$        |          | _        d S || _        t          j$        |          | _        d S t          j$        |          | _        d S )Nr?   rk   r   r   r   r   )%r   r   rq   r   r   r?   r   r   r   rb   r   r   r$   re   rM   r   rh   r   r   r   r   rL   rO   r   r   rt   ry   r   r{   rc   ra   rf   rw   rx   r   r   rN   )rD   r   r   rr   rs   r}   rv   r   rd   loss_functionr   r   r   r   rb   r   r   r   re   rQ   rR   r   r   r   s                           rF   r]  zBaseSGDRegressor._fit_regressor  s    //55--dl;;!99-HHtT"" 	DG55a]UVEV5WW"<<Q=
 
 *$*;<< ##Aw//#/q-l$
 $
 $
  (.dhhRVG< 		$&D0I-L $ 7:DIL!",DDD
ISaLa M%&&"##ILGL;J
 J
Fi'8$,@ 	4<!'!*,,<!&(m4E&F&FD#')}Y'?'?D$|tw},,)
"$-0A"B"B!
"$-	":": !mI66DOOOrH   c                 `    t                                                      }d|j        _        |S r*  r+  r/  s     rF   r,  z!BaseSGDRegressor.__sklearn_tags__  r1  rH   r   rU   r3  )rV   rW   rX   r	   r
   r5  r%   r(   r   r\   ri   r   r6  r   r   r   r   r   r   rG   r  r   r$  r  r   rg  ri  r]  r,  r7  r8  s   @rF   rT  rT  o  s        ,./ 2OD(A?'S	 N$

($CC//001$+ (q!I F F FG%Xh4GGGH$ $ $D     +
 "++
 +
 +
 +
 +
 +
 ^+
Z; ; ;z \555'
 '
 '
 65'
b = = = =~ \555%
 %
 %
 65%
N  &* * *U7 U7 U7n        rH   rT  c                   h    e Zd ZU dZi ej         eh d          dg eeddd          g eeddd          g eeddd	          g eh d
           e	 eddh                    g eeddd          g eeddd          gdZe
ed<   	 dddddddddedddddddddd fdZ xZS )SGDRegressora'  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]`.

    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   r^   r_   r!   r;  r   >   r1   r3   r0   r2   r4   r5   )rq   rr   rt   rx   rv   ru   rw   ri   r   r7   rj   rl   Trm   rn   r2   rU  rV  Fr:   r.   rW  c                p    t                                          |||||||||	|
|||||||||           d S r   r=  rY  s                       rF   rG   zSGDRegressor.__init__  si    . 	'%') 3-!' 	 	
 	
 	
 	
 	
rH   rm  )rV   rW   rX   rY   rT  ri   r   r   r   r   r   r   r5  rG   r7  r8  s   @rF   ro  ro    s        d dL$

1$J999::DA(4D8889XdAq8889HT4i@@@AJHHHIIF::uen--..
 HT1d6:::;$47778$ $ $D     +
 "++
 +
 +
 +
 +
 +
 +
 +
 +
 +
 +
rH   ro  c            
           e Zd ZU dZdedfiZi ej         ee	ddd          g e
h d           e e
dd	h                    g ee	d
dd          g ee	ddd          gdZeed<   	 	 	 	 	 	 	 	 	 	 	 	 d! fd	Zd Zd Z ed          d"d            Z	 	 	 d#dZ ed          d$d            Zd Zd Zd Z fd Z xZS )%SGDOneClassSVMa  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   rk   ro   rightr_   >   r1   r3   r0   r2   r4   r5   r   Nr^   r   )nurv   rw   rx   ri   rp   Trm   rn   r1   Fc                     || _         t          t          |                               dddd|||||t          |||	|
ddd||           d S )	Nr   r7   rk   r   Fr:   r.   )r}   rq   rs   rt   rc   rd   re   rf   ra   ru   rb   rv   rw   rx   ry   rz   r{   rg   rh   )rt  r   rr  rG   r5  )rD   rt  rc   rd   re   rf   ra   rb   rv   rw   rx   rg   rh   r   s                rF   rG   zSGDOneClassSVM.__init__  sv     nd##,,'#%'  #!' 	- 	
 	
 	
 	
 	
rH   c                    |j         d         }t          j        ||j        d          }t	          |||          \  }	}
|                     | j                  }|                     |          }|                     ||dk              }| 	                    ||||          }t          | j                  }|                    dt          j        t          j                  j                  }| j        | j        nt          j         }d}d}d}| j        r| j        }| j        }| j        }| j        }n| j        }d| j        z
  }d}dg}t3          |j                  } |||d         ||d         | j        |||| j        |	|| j        |t;          | j                  ||t;          | j                  t;          | j                   t;          | j!                  ||||| j"        | j#        || j$        |
| j                  \  }}}}| _%        | xj$        | j%        |z  z  c_$        | j        dk    rt          j&        |          | _        t          j&        |          | _        | j        | j$        dz
  k    r%|| _        dt          j&        |          z
  | _        dS || _        dt          j&        |          z
  | _        dS dt          j&        |          z
  | _        dS )	z8Uses SGD implementation with X and y=np.ones(n_samples).r   rs   r   r   Nr!   r   rk   )'r   rM   r   r   r$   r   rq   r   r   r   r   rb   r   iinfoint32r  re   r   rh   r   r   r   r   rL   r   r   r   rt   ry   r   r{   rc   ra   rf   rw   rx   r?   r   rN   )rD   r   rr   rs   r   rv   rd   r   r   r   offset_decayr   r   r   r   rb   r   re   r   r   r   rQ   rR   r   r   r   s                             rF   _fit_one_classzSGDOneClassSVM._fit_one_class  s   
 GAJ	GIQWC888 ,Q= A A--dl;;!99-HH 55a]UVEV5WW"<<Q=
 
 *$*;<< ##Arx'9'9'=>>(.dhhRVG	 

< 		$&D0I-L $ 7:DDL(IL!",DDD
ISaLa  M%&&"##ILGL;J
 J
Fi'8$,@ 	4<)++<!&(m4E&F&FD#')}Y'?'?D$|tw},,)
 2=1B#C#CC!
 2=#;#;; r}Y777DLLLrH   c
           
         t          | dd           d u }
t          | |d dt          j        t          j        gdd|
          }|
rKt          | j        t          t          j        f          s%| j        dk    rt          j
        dt                     |j        d         }t          |||j        	          }t          | dd           |!|                     d||j        ||	d
           n:|| j        j        d         k    r$t#          d|| j        j        d         fz            | j        rSt          | dd           Bt          j        ||j        d          | _        t          j        d|j        d          | _        |                     |          | _        t/          | d          sd| _        |                     ||||||           | S )NrL   r   rs   Fr   r   r   r!   r   )r   r   r   r   r   r   rJ   r   r   r   r?   rk   r   )r  r    rM   r  r   r   rh   r  r   r  r  r  r   r   r   r   rL   r   r   r   r   r   r   r   r?   rz  )rD   r   rr   rs   r}   rv   rd   r   r   offset_initr
  r   s               rF   r  zSGDOneClassSVM._partial_fit>	  s    T7D11T9
:rz* %	
 	
 	
  		dlT28,<== $,RSBSBSP "   WQZ
 -]AQWMMM
 4$''/93H((%G#* )     4:+B///Htz/345  
 < 	LGD/4@@H!#*AG3!O!O!OD&(hqs&K&K&KD##66t<<tT"" 	DG 	'' 	 	
 	
 	
 rH   r  c                     t          | d          s|                     d           | j        dz  }|                     ||d| j        | j        d|dd	  	        S )	aD  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.
        rL   Tr"  r   rk   r!   N)rs   r}   rv   rd   r   r   r|  )r   r   rt  r  r}   rv   )rD   r   r   r   rr   s        rF   r$  zSGDOneClassSVM.partial_fit	  su    ( tW%% 	=&&t&<<<!  ,' ! 

 

 
	
rH   c	                    t          | j        t          t          j        f          s%| j        dk    rt          j        dt                     | j        r#t          | d          r|| j
        }|| j        }nd | _
        d | _        d| _        |                     |||||| j        |||	  	         | j        @| j        t          j         k    r*| j        | j        k    rt          j        dt$                     | S r`  )r   rh   r  rM   r   r  r  r  rg   r   rL   r   r?   r  rd   re   r   r   r   )	rD   r   rr   rs   r}   rv   r   r|  r   s	            rF   r  zSGDOneClassSVM._fit	  s    $,rx(899 	dla>O>OMH    ? 	 wtW55 	   J	""lDJDL M
	
 
	
 
	
 H BF7""--M' #   rH   c           
          |                                   | j        dz  }|                     ||d| j        | j        |||           | S )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   rk   )rr   rs   r}   rv   r   r|  r   )r   rt  r  r}   rv   )rD   r   r   r   r|  r   rr   s          rF   r   zSGDOneClassSVM.fit	  sa    B 	""$$$!		,#' 	 		
 		
 		
 rH   c                     t          | d           t          | |dd          }t          || j        j        d          | j        z
  }|                                S )a  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.
        rL   r   Frc  Trd  )r   r    r   rL   rf  r   r   )rD   r   	decisionss      rF   rD  z SGDOneClassSVM.decision_function
  sY    " 	g&&&$eDDD#Atz|$GGG$,V	   rH   c                 @    |                      |          | j        z   }|S )aL  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.
        )rD  r   )rD   r   score_sampless      rF   r  zSGDOneClassSVM.score_samples6
  s$     ..q11DL@rH   c                     |                      |          dk                        t          j                  }d||dk    <   |S )a/  Return 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   rJ   )rD  r\  rM   rx  r   s      rF   ri  zSGDOneClassSVM.predictF
  s>     ##A&&!+33BH==!q&	rH   c                 `    t                                                      }d|j        _        |S r*  r+  r/  s     rF   r,  zSGDOneClassSVM.__sklearn_tags__W
  r1  rH   )rp   Trm   rn   Tr   Nr1   ro   rp   FFr4  r3  )NNNN)rV   rW   rX   rY   r&   r   r\   ri   r   r   r   r   r   r   rG   rz  r  r   r$  r  r   rD  r  ri  r,  r7  r8  s   @rF   rr  rr    s!        K KZ s|,N	$

(	$xc3w7778JHHHIIF::uen--..
 $47778HT4i@@@A	$ 	$ 	$D 	 	 	 $
 $
 $
 $
 $
 $
L^8 ^8 ^8@L L L\ \555!
 !
 !
 65!
T ; ; ; ;z \555. . . 65.`! ! !0     "        rH   rr  )Tr4  )KrY   r  abcr   r   numbersr   r   numpyrM   _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   r5  rw  rx  r  r   r<   r\   r   r   r   r   r:  rT  ro  rr  rZ   rH   rF   <module>r     s/     ' ' ' ' ' ' ' ' " " " " " " " "     M M M M M M M M M M                , + + + + + B B B B B B B B < < < < < < < < B B B B B B B B B B + + + + + + / / / / / / < < < < < < . . . . . . . . S S S S S S S S S S G G G G G G G G G G                     !1A>> "(28


 I I I I I I I I&r
 r
 r
 r
 r
o} r
 r
 r
 r
j"A "A "A "Ab E$ E$ E$ E$PG G G~ ~ ~ ~ ~-w' ~ ~ ~ ~Bv- v- v- v- v-% v- v- v-rH H H H H~w H H HV`
 `
 `
 `
 `
# `
 `
 `
F	} } } } }\7 } } } } }rH   