`L i̧`ddlZddlmZmZddlmZmZddlZddl m Z ddl m Z mZmZddlmZmZddlmZddlmZmZmZmZdd lmZmZdd lmZdd lm Z dd l!m"Z"m#Z#dd l$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*ddl+m,Z-ddl+m.Z/ddl+m0Z1gdZ2dZ3Gdde eZ4Gddee4eZ5dZ6 ddZ7y)N)ABCMetaabstractmethod)IntegralReal) BaseEstimatorClassifierMixin _fit_context)ConvergenceWarningNotFittedError) LabelEncoder) check_arraycheck_random_state column_or_1dcompute_class_weight)Interval StrOptions)safe_sparse_dot) available_if)_ovr_decision_functioncheck_classification_targets)_check_large_sparse_check_sample_weight _num_samplescheck_consistent_lengthcheck_is_fitted validate_data) _liblinear)_libsvm)_libsvm_sparse)c_svcnu_svc one_class epsilon_svrnu_svrc |jddz}g}tjtjdg|g}t |D]}|||||dzddf}t |dz|D]e}|||||dzddf} ||dz ||||dzf} ||||||dzf} |j t | |t | | zg|S)zGenerate primal coefficients from dual coefficients for the one-vs-one multi class LibSVM in the case of a linear kernel.rrN)shapenpcumsumhstackrangeappendr) dual_coef n_supportsupport_vectorsn_classcoefsv_locsclass1sv1class2sv2alpha1alpha2s W/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sklearn/svm/_base.py_one_vs_one_coefr;%sooa 1$G Dii A3 "234G. Ugfo 0CCQFGFQJ0 UF!'&/GFQJ4G"G"JKCvz76?WVaZ=P+PPQFvwv!9L'LLMF KK4vs7SS T U U KceZdZUdZehdegeedddgeddheed ddgeeddd geed dd geed dd geed d d geed ddgd gd geeddd gedhe dgdgeedddgdgdZ e e d<gdZ e dZfdZedd)dZdZdZdZdZdZdZd Zd!Zd"Zd#Zd$Zd%Zed&Zd'Z ed(Z!xZ"S)* BaseLibSVMzBase class for estimators that use libsvm as backing library. This implements support vector machine classification and regression. Parameter documentation is in the derived `SVC` class. >rbfpolylinearsigmoid precomputedrNleft)closedscaleautoneitherright?booleanbalancedverbose random_statekerneldegreegammacoef0tolCnuepsilon shrinking probability cache_size class_weightrNmax_iterrP_parameter_constraints)rAr@r?rBrCc:|jtvr tdtd|jd||_||_||_||_||_||_||_ ||_ | |_ | |_ | |_ | |_| |_||_||_y)Nzimpl should be one of z, z was given)_impl LIBSVM_IMPL ValueErrorrRrSrTrUrVrWrXrYrZr[r\r]rNr^rP)selfrRrSrTrUrVrWrXrYrZr[r\r]rNr^rPs r:__init__zBaseLibSVM.__init__js& ::[ (r tAdd|jCtjDdjF} | |||||| tI|dr |j$n|f|_%|jLjO|_(|jR|_*|j dvr?tW|jXdk(r'|xjLdzc_&|jR |_)|jr|jTjZn |jT} tj\|jPj_} tj\| j_}| r|s t'd|j dvr|j`|_1|S|j`je|_1|S) aFit the SVM model according to the given training data. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples) Training vectors, where `n_samples` is the number of samples and `n_features` is the number of features. For kernel="precomputed", the expected shape of X is (n_samples, n_samples). y : array-like of shape (n_samples,) Target values (class labels in classification, real numbers in regression). sample_weight : array-like of shape (n_samples,), default=None Per-sample weights. Rescale C per sample. Higher weights force the classifier to put more emphasis on these points. Returns ------- self : object Fitted estimator. Notes ----- If X and y are not C-ordered and contiguous arrays of np.float64 and X is not a scipy.sparse.csr_matrix, X and/or y may be copied. If X is a dense array, then the other methods will not support sparse matrices as input. rCz-Sparse precomputed kernels are not supported.rWcsrF)dtypeorder accept_sparseaccept_large_sparsersrrz"X and y have incompatible shapes. zX has z samples, but y has .rzDPrecomputed matrix must be a square matrix. Input is a {}x{} matrix.z.sample_weight and X have incompatible shapes: z vs zT Note: Sparse matrices cannot be indexed w/boolean masks (use `indices=True` in CV).rHrFrKrGz[LibSVM]endi) random_seedr(r"r#rOzxThe dual coefficients or intercepts are not finite. The input data may contain large values and need to be preprocessed.)3rrPspissparserR TypeErrorcallable_sparserrr)float64_validate_targetsasarrayrbindexrarr(rcformat_gamma isinstancerTstrmultiplymeanvarr _sparse_fit _dense_fitrNprintrandintiinfomaxhasattr shape_fit_ intercept_copy _intercept_ dual_coef_ _dual_coef_lenclasses_dataisfiniteall _num_itern_iter_item)rdXy sample_weightrndrl solver_type n_samplesrRX_varfitseedr.intercept_finitenessdual_coef_finitenesss r:rzBaseLibSVM.fitsD!!2!23Q dkk]2KL L;ht{{&;"; DKK #Aq ) jj#$)DAq  " "1 % 'B]"** "'' 3 !O !  QWWQZ 757@!''!*MN  ;;- 'I,C,,2F1771:qwwqz,J    q !A %-*=*=a*@I*M !&& 1 #+4;;"7T[[ ] "DK  C (zzW$DJA,,.!&&(q@PQPUPUPW>DL  >>..0DL r<cZt|djtjdS)zxValidation of y and class_weight. Default implementation for SVR and one-class; overridden in BaseSVC. TwarnF)r)rastyper)r)rdrs r:rzBaseLibSVM._validate_targets's% AD)00%0HHr<c|jdvsJ|jdk(r(tjd|jztyy)NrrrznSolver terminated early (max_iter=%i). Consider pre-processing your data with StandardScaler or MinMaxScaler.) fit_status_warningsrr^r rds r:_warn_from_fit_statusz BaseLibSVM._warn_from_fit_status.sL6)))   q MM359]]C#   !r<c  t|jrB||_|j|}|jd|jdk7r t dt j|jt j||fid|d|dt|dtjdd|d |jd |jd |jd |j d |j"d|j$d|j&d|j(d|j*d|j,d|j.d|\ |_|_|_|_|_|_|_|_|_ |jCy)Nrrz(X.shape[0] should be equal to X.shape[1]svm_typerr] class_weight_rRrWrXr[rSrZrVr\rUrTrYr^r})"rrR_BaseLibSVM__Xfit_compute_kernelr(rclibsvmset_verbosity_wraprNrgetattrr)emptyrWrXr[rSrZrVr\rUrrYr^support_support_vectors_ _n_supportrr_probA_probBrrr)rdrrrrrRr}s r:rzBaseLibSVM._dense_fit8s DKK DK$$Q'AwwqzQWWQZ' !KLL!!$,,/ JJ  ! (  ! D    ff ww (( ;; nn   ** ++ LL! "]]# $$%  M  ! O O O K K   N, ""$r<ctj|jtjd|_|j |j j |}tj|jtj|jd|j|j|j||||j|j|j |j"|j$t'|dtj(d||j*|j,|j.t1|j2t1|j4|j6|\ |_|_}|_|_|_ |_!|_"|_#|jItK|drtM|jNdz } nd} |j:jd} tjPtjR| | } | stUjVg|_,ytjRd| jZdz| jZ| z } tUjV|| | f| | f|_,y)NrWrsrtrrrr).r)rrr sort_indices_sparse_kernelsr libsvm_sparserrNlibsvm_sparse_trainr(indicesindptrrSrrUrVrWrrrXr\rYintrZr[r^rrrrrrrrrrrrtilearanger csr_matrixrsize) rdrrrrrRr} kernel_typedual_coef_datar1n_SVdual_coef_indicesdual_coef_indptrs r:rzBaseLibSVM._sparse_fitgsAFF"**C@ **008 ((6  - - GGAJ FF II HH   KK KK JJ HH FF D/288A; 7  GG OO LL     ! MM +  M  !  O O K K   N2 ""$ 4 $$--(1,GG$$**1-GGBIIdOW= mmB/DO!yy$))A-/@/E/E/O  !mm!24DEQUDOr<c||j|}|jr |jn |j}||S)aPerform regression on samples in X. For an one-class model, +1 (inlier) or -1 (outlier) is returned. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) For kernel="precomputed", the expected shape of X is (n_samples_test, n_samples_train). Returns ------- y_pred : ndarray of shape (n_samples,) The predicted values. )_validate_for_predictr_sparse_predict_dense_predict)rdrpredicts r:rzBaseLibSVM.predicts7  & &q )*.,,$&&D$,,x 7LEt*%%&  ;;- 'wwqzT__Q// =wwqz4??1#567 " "||! 0C0C0ERS0T1$..2I2I1J,W r<c|jdk7r td|j}tj|rd|j j _|Sd|j _|S)zWeights assigned to the features when `kernel="linear"`. Returns ------- ndarray of shape (n_features, n_classes) rAz2coef_ is only available when using a linear kernelF)rRAttributeError _get_coefrrrflags writeablerdr2s r:coef_zBaseLibSVM.coef_s` ;;( " !UV V~~ ;;t (-DIIOO % $)DJJ  r<cBt|j|jSN)rrrrs r:rzBaseLibSVM._get_coefst//1F1FGGr<c t|tj |j }|dvr |j Stj|j dgS#t$rtwxYw)z)Number of support vectors for each class.rr) rr rrbrrarr)array)rdrs r:rzBaseLibSVM.n_support_sk ! D !$$TZZ0 v ?? "88T__Q/01 1 !  !s AA/r)#r __module__ __qualname____doc__rrrrrdictr___annotations__rrrerir rrrrrrrrrrrrrpropertyrrr __classcell__ros@r:r>r>Es J K  Haf=> ( ) T3V 4 4tI>?sD;<tS$w7 8c3w78T3V<=[!{ai@A#ZL14>;hD@A'(+$D6JO%)%)N5K6KZI-%^;z(  D" H < 0! F'R,H 2 2r<r>) metaclassc2eZdZUdZiej eddhgdgdZeed<dD]Z eje e fdZ d Z d Zfd Zd Zeed ZeedZdZdZdZedZedZfdZxZS)BaseSVCz!ABC for LibSVM-based classifiers.ovrovorL)decision_function_shape break_tiesr_)rYrXc^||_||_t| |||||||d|| | | | | |y)NrHrQ)rrrhre)rdrRrSrTrUrVrWrXrZr[r\r]rNr^rrPrros r:rezBaseSVC.__init__sS((?$$ #!%%  r<cDt|d}t|tj|d\}}t |j |||_t|dkrtdt|z||_ tj|tjdS) NTr)return_inverse)classesrrz>The number of classes has to be greater than one; got %d classrWr) rrr)uniquerr]rrrcrrr)rdry_clss r:rzBaseSVC._validate_targetss !$ '$Q'2d3Q1$2C2CSTVW s8a<Pc(   zz!2::S99r<c|j|}|jdk(r`_ for further details. If decision_function_shape='ovr', the decision function is a monotonic transformation of ovo decision function. rrr)rrrrr)rdrdecs r:rzBaseSVC.decision_functionsU6%%a(  ' '5 0S5G!5K)#'C4T]]9KL L r<ct||jr|jdk(r td|jrN|jdk(r?t |j dkDr't j|j|d}nt|)|}|j jt j|t jS)aPerform classification on samples in X. For an one-class model, +1 or -1 is returned. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples_test, n_samples_train) For kernel="precomputed", the expected shape of X is (n_samples_test, n_samples_train). Returns ------- y_pred : ndarray of shape (n_samples,) Class labels for samples in X. rz>break_ties must be False when decision_function_shape is 'ovo'rrr)axisrw)rrrrcrrr)argmaxrrhrtakerintp)rdrrros r:rzBaseSVC.predicts"  ??t;;uDP  OO,,5DMM"Q& $003!??r<cd|js td|jdvr tdy)Nz5predict_proba is not available when probability=Falser~z0predict_proba only implemented for SVC and NuSVCT)r[rrars r: _check_probazBaseSVC._check_proba=s9 G  ::0 0 !ST Tr<c|j|}|jjdk(s|jjdk(r t d|j r |j n |j}||S)aCompute probabilities of possible outcomes for samples in X. The model needs to have probability information computed at training time: fit with attribute `probability` set to True. Parameters ---------- X : array-like of shape (n_samples, n_features) For kernel="precomputed", the expected shape of X is (n_samples_test, n_samples_train). Returns ------- T : ndarray of shape (n_samples, n_classes) Returns the probability of the sample for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute :term:`classes_`. Notes ----- The probability model is created using cross validation, so the results can be slightly different than those obtained by predict. Also, it will produce meaningless results on very small datasets. rzApredict_proba is not available when fitted with probability=False)rprobA_rprobB_r r_sparse_predict_proba_dense_predict_proba)rdr pred_probas r: predict_probazBaseSVC.predict_probaFsq6  & &q ) ;;  q DKK$4$4$9 S +/,,D & &Dr_rrr  unused_parampoprrerrrr#rr*r-r(r'rr r%r&rir r s@r:rrs+$  + +$$.u~$>#? k$D *1 ""<01% % N :@@J," "H,- -:6! F r<rc jddiddddddd iidd id d ddddd iiddddidd}|dk(r||S|dk7rtd|z|j|d}|d|z}n@|j|d}| d|d|d}n"|j|d}| d|d|d|}n|Std|d|d|d|)aFind the liblinear magic number for the solver. This number depends on the values of the following attributes: - multi_class - penalty - loss - dual The same number is also internally used by LibLinear to determine which solver to use. Fr)FT)l1l2r@Trr )logistic_regressionhinge squared_hingeepsilon_insensitivesquared_epsilon_insensitivecrammer_singerrLrz<`multi_class` must be one of `ovr`, `crammer_singer`, got %rNzloss='%s' is not supportedzThe combination of penalty='z ' and loss='z' is not supportedz' are not supported when dual=zUnsupported set of arguments: z, Parameters: penalty=z, loss=z, dual=)rcget) multi_classpenaltylossdual_solver_type_dict _solver_pen error_string _solver_dual solver_nums r:_get_liblinear_solver_typerWs("(-aj8KLq "!& !12EF $tRj1(,b.C'D && --   J[ X  $''d3K3d: "w5  D"  &))$5J!CJ4QUW "!  $ . r<c| dvrVt}|j|}|j}t|dkrt d|dzt ||||}n't jdt j}|}tj|t| }|r tdd d }|r|dkrt d |z|}tj|tj|tj|tj |r t#|t j$|t jj'}t j(|d }t+||t j}t-| || |}tj.||tj ||| |||| |j1t j2dj4|| \}}t5|}|| k\rt7j8dt:|r|ddddf}||dddfz}n|}d}|||fS)aUsed by Logistic Regression (and CV) and LinearSVC/LinearSVR. Preprocessing is done in this function before supplying it to liblinear. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training vector, where `n_samples` is the number of samples and `n_features` is the number of features. y : array-like of shape (n_samples,) Target vector relative to X C : float Inverse of cross-validation parameter. The lower the C, the higher the penalization. fit_intercept : bool Whether or not to fit an intercept. If set to True, the feature vector is extended to include an intercept term: ``[x_1, ..., x_n, 1]``, where 1 corresponds to the intercept. If set to False, no intercept will be used in calculations (i.e. data is expected to be already centered). intercept_scaling : float Liblinear internally penalizes the intercept, treating it like any other term in the feature vector. To reduce the impact of the regularization on the intercept, the `intercept_scaling` parameter can be set to a value greater than 1; the higher the value of `intercept_scaling`, the lower the impact of regularization on it. Then, the weights become `[w_x_1, ..., w_x_n, w_intercept*intercept_scaling]`, where `w_x_1, ..., w_x_n` represent the feature weights and the intercept weight is scaled by `intercept_scaling`. This scaling allows the intercept term to have a different regularization behavior compared to the other features. class_weight : dict or 'balanced', default=None Weights associated with classes in the form ``{class_label: weight}``. If not given, all classes are supposed to have weight one. For multi-output problems, a list of dicts can be provided in the same order as the columns of y. 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))`` penalty : {'l1', 'l2'} The norm of the penalty used in regularization. dual : bool Dual or primal formulation, verbose : int Set verbose to any positive number for verbosity. max_iter : int Number of iterations. tol : float Stopping condition. random_state : int, RandomState instance or None, default=None Controls the pseudo random number generation for shuffling the data. Pass an int for reproducible output across multiple function calls. See :term:`Glossary `. multi_class : {'ovr', 'crammer_singer'}, default='ovr' `ovr` trains n_classes one-vs-rest classifiers, while `crammer_singer` optimizes a joint objective over all classes. While `crammer_singer` is interesting from an theoretical perspective as it is consistent it is seldom used in practice and rarely leads to better accuracy and is more expensive to compute. If `crammer_singer` is chosen, the options loss, penalty and dual will be ignored. loss : {'logistic_regression', 'hinge', 'squared_hinge', 'epsilon_insensitive', 'squared_epsilon_insensitive}, default='logistic_regression' The loss function used to fit the model. epsilon : float, default=0.1 Epsilon parameter in the epsilon-insensitive loss function. Note that the value of this parameter depends on the scale of the target variable y. If unsure, set epsilon=0. sample_weight : array-like of shape (n_samples,), default=None Weights assigned to each sample. Returns ------- coef_ : ndarray of shape (n_features, n_features + 1) The coefficient vector got by minimizing the objective function. intercept_ : float The intercept term added to the vector. n_iter_ : array of int Number of iterations run across for each class. )rJrKrzeThis solver needs samples of at least 2 classes in the data, but the data contains only one class: %rr)rrrrwz [LibLinear]ryrzgzqIntercept scaling is %r but needs to be greater than 0. To disable fitting an intercept, set fit_intercept=False.W) requirementsr|z@Liblinear failed to converge, increase the number of iterations.NrOrH)r fit_transformrrrcrr)rr liblinearrrrrrrrrrrrequirerrW train_wraprrrrrr )rrrW fit_interceptintercept_scalingr]rOrQrNr^rVrPrNrPrYrency_indrrrbiasr raw_coef_r n_iter_maxrrs r:_fit_liblinearrf*s/h IIn!!!$<< x=1 '{+  - (a} "**5    ) \ *C m$ D  !,.?@  %D g&$$W-   ) {{1~A JJuBJJ / 5 5 7E JJu3 /E(LM,['4NK"--   A    BHHSM%%& Iw$WJX N  !SbS&!&1b5)99  *g %%r<)NrrGg?N)8rabcrrnumbersrrnumpyr) scipy.sparserlrbaserr r exceptionsr r preprocessingr utilsrrrrutils._param_validationrr utils.extmathrutils.metaestimatorsrutils.multiclassrrutils.validationrrrrrrryrr\r rr!rrbr;r>rrWrfr<r:rus'"??;(WW:+/S& -G @n 2'n 2bxozWxv 6J  !D&r<