`L ipdZddlZddlZddlmZmZddlmZmZddlZ ddl m Z ddl mZmZm Z ddlmZddlmZdd lmZmZmZmZmZdd lmZmZdd lmZmZm Z m!Z!m"Z"m#Z#dd l$m%Z%dd l&m'Z'm(Z(m)Z)m*Z*ddl+m,Z,ddl-m.Z.m/Z/ddl0m1Z1ddl2m3Z3m4Z4m5Z5dZ6d#dZ7ddddddZ8d$dZ9GddeeZ:GddeZ;GddZ<Gdd eee:Z= d%d!Z> d&d"Z?y)'z Generalized Linear Models. N)ABCMetaabstractmethod)IntegralReal)linalgoptimizesparse)lsqr)expit) BaseEstimatorClassifierMixinMultiOutputMixinRegressorMixin _fit_context) check_arraycheck_random_state)_asarray_with_order_average get_namespaceget_namespace_and_deviceindexing_dtypesupported_float_dtypes)Interval)ArrayDataset32ArrayDataset64 CSRDataset32 CSRDataset64)safe_sparse_dot)Paralleldelayed)mean_variance_axis)_check_sample_weightcheck_is_fitted validate_datag{Gz?ct|}|jdtjtjj }|j tjk(r t}t}n t}t}tj|r6||j|j|j |||}t"} || fStj$|}|||||}d} || fS)aDCreate ``Dataset`` abstraction for sparse and dense inputs. This also returns the ``intercept_decay`` which is different for sparse datasets. Parameters ---------- X : array-like, shape (n_samples, n_features) Training data y : array-like, shape (n_samples, ) Target values. sample_weight : numpy array of shape (n_samples,) The weight of each sample random_state : int, RandomState instance or None (default) Determines random number generation for dataset random sampling. It is not used for dataset shuffling. Pass an int for reproducible output across multiple function calls. See :term:`Glossary `. Returns ------- dataset The ``Dataset`` abstraction intercept_decay The intercept decay )seedg?)rrandintnpiinfoint32maxdtypefloat32rrrrspissparsedataindptrindicesSPARSE_INTERCEPT_DECAYascontiguousarray) Xy sample_weight random_staterngr(CSRData ArrayDatadatasetintercept_decays `/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sklearn/linear_model/_base.py make_datasetrA7s> \ *C ;;q"((288,00 1Dww"**" "  {{1~!&&!((AIIq-dS0 O ##   #Aq-d; O ##T)copycopy_yr9 check_inputct|||\}}} |j\} } tj|} t |t j rd}||j|}|r4t||ddgt|}t||j|d}nB|j||j|}|r"| r|j}nt|dd | }|j} |r[| rt|d | \}}n2t|d || }|j||jd}||z}t|d || }||z}nc|j!| |j| }|j"dk(r|jd| | }n!|j!|jd| | }|j%| |j| }|||||fS)aCommon data preprocessing for fitting linear models. This helper is in charge of the following steps: - Ensure that `sample_weight` is an array or `None`. - If `check_input=True`, perform standard input validation of `X`, `y`. - Perform copies if requested to avoid side-effects in case of inplace modifications of the input. Then, if `fit_intercept=True` this preprocessing centers both `X` and `y` as follows: - if `X` is dense, center the data and store the mean vector in `X_offset`. - if `X` is sparse, store the mean in `X_offset` without centering `X`. The centering is expected to be handled by the linear solver where appropriate. - in either case, always center `y` and store the mean in `y_offset`. - both `X_offset` and `y_offset` are always weighted by `sample_weight` if not set to `None`. If `fit_intercept=False`, no centering is performed and `X_offset`, `y_offset` are set to zero. Returns ------- X_out : {ndarray, sparse matrix} of shape (n_samples, n_features) If copy=True a copy of the input X is triggered, otherwise operations are inplace. If input X is dense, then X_out is centered. y_out : {ndarray, sparse matrix} of shape (n_samples,) or (n_samples, n_targets) Centered version of y. Possibly performed inplace on input y depending on the copy_y parameter. X_offset : ndarray of shape (n_features,) The mean per column of input X. y_offset : float or ndarray of shape (n_features,) X_scale : ndarray of shape (n_features,) Always an array of ones. TODO: refactor the code base to make it possible to remove this unused variable. Ncsrcsc)rC accept_sparser.F)r.rC ensure_2drCKT)orderrCxpr)axisweights)rOrPrN)r.devicer')rshaper0r1 isinstancenumbersNumberasarrayrrr.astyperCrr"rzerosndimones)r7r8 fit_interceptrCrDr9rErN_device_ n_samples n_features X_is_sparsedtype_X_offsetX_vary_offsetX_scales r@_preprocess_datarglsb.aMBNB7GGIz++a.K-0   =1   D>TUW>X  v G IIavI . FFH'4BG WWF 0MROHe=RHHyy177y?H MAAA}D X 88Jaggg8F 66Q;zz#VGzDHxx &xIHggjg@G a8W ,,rBc>t|||\}}|jd}|j|}tj|stj|rt j |df||f}tj|r t|}n|r ||dddfz}n ||dddfz}tj|r t|}nE|r"|jdk(r||z}n.||dddfz}n!|jdk(r||z}n ||dddfz}|||fS)aRescale data sample-wise by square root of sample_weight. For many linear models, this enables easy support for sample_weight because (y - X w)' S (y - X w) with S = diag(sample_weight) becomes ||y_rescaled - X_rescaled w||_2^2 when setting y_rescaled = sqrt(S) y X_rescaled = sqrt(S) X Returns ------- X_rescaled : {array-like, sparse matrix} y_rescaled : {array-like, sparse matrix} r)rSNr') rrSsqrtr0r1r dia_matrixrrZ) r7r8r9inplacerNr]r_sample_weight_sqrt sw_matrixs r@ _rescale_datarns&0 !Q .EB I/ {{1~Q%%  #Iy+A  {{1~ Iq )  #AtG, ,A&q$w//A {{1~ Iq ) vv{'''400vv{***1d733 a# ##rBc2eZdZdZedZdZdZdZy) LinearModelzBase class for Linear Modelscy)z Fit model.N)selfr7r8s r@fitzLinearModel.fitsrBct|t||gdd}|j}|jdk(r||z|jzS||j z|jzS)NrGrHcooFrIresetr')r$r%coef_rZ intercept_T)rsr7rzs r@_decision_functionzLinearModel._decision_functionsY $1Fe T  ::?u9t. .uww;0 0rBc$|j|S)a! Predict using the linear model. Parameters ---------- X : array-like or sparse matrix, shape (n_samples, n_features) Samples. Returns ------- C : array, shape (n_samples,) Returns predicted values. )r})rsr7s r@predictzLinearModel.predicts&&q))rBc>t|||\}}|jrz|j|j|jd}|j ||x}|_|j dk(r|||zz }||_y|||jzz }||_yd|_y)zSet the intercept_FrKr'rRN) rr\rXrzr.dividerZr|r{)rsrcrerfrNr]rzr{s r@_set_interceptzLinearModel._set_intercept,sh':A   IIdjj'--eIDE!#5'!: :EDJzzQ%5(88 )DO&577(:: (DO"DOrBN) __name__ __module__ __qualname____doc__rrtr}rrrrrBr@rprp s&&1* "rBrp) metaclassc"eZdZdZdZdZdZy)LinearClassifierMixinzRMixin for linear classifiers. Handles prediction for sparse and dense X. ct|t|\}}t||dd}t||jj d|j z}|jdkDr$|jddk(r|j|dS|S)a Predict confidence scores for samples. The confidence score for a sample is proportional to the signed distance of that sample to the hyperplane. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The data matrix for which we want to get the confidence scores. Returns ------- scores : ndarray of shape (n_samples,) or (n_samples, n_classes) Confidence scores per `(n_samples, n_classes)` combination. In the binary case, confidence score for `self.classes_[1]` where >0 means this class would be predicted. rGFrxT) dense_outputr')) r$rr%rrzr|r{rZrSreshape)rsr7rNr]scoress r@decision_functionz'LinearClassifierMixin.decision_functionJs& a A $e D DJJLLtDtV aFLLOq$8 JJvu %  rBct|\}}|j|}t|jdk(r|j |dkDt |}n|j |d}|j|j|dS)a~ Predict class labels for samples in X. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The data matrix for which we want to get the predictions. Returns ------- y_pred : ndarray of shape (n_samples,) Vector containing the class labels for each sample. r'rrO) rrlenrSrXrargmaxtakeclasses_)rsr7rNr]rr4s r@rzLinearClassifierMixin.predicthswa A''* v||  !ii N2,>?GiiQi/Gwwt}}gAw66rBc|j|}t|||jdk(r$tjd|z |gj S||j dj|jddfz}|S)zProbability estimation for OvR logistic regression. Positive class probabilities are computed as 1. / (1. + np.exp(-self.decision_function(X))); multiclass is handled by normalizing that over all classes. outr'rrr) rr rZr*vstackr|sumrrS)rsr7probs r@_predict_proba_lrz'LinearClassifierMixin._predict_proba_lrs{%%a( d 99>99a$h-.00 0 DHH!H$,,djjmR-@A ADKrBN)rrrrrrrrrrBr@rrDs  <7.rBrceZdZdZdZdZy)SparseCoefMixinzlMixin for converting coef_ to and from CSR format. L1-regularizing estimators should inherit this. cd}t||tj|jr|jj |_|S)a Convert coefficient matrix to dense array format. Converts the ``coef_`` member (back) to a numpy.ndarray. This is the default format of ``coef_`` and is required for fitting, so calling this method is only required on models that have previously been sparsified; otherwise, it is a no-op. Returns ------- self Fitted estimator. z6Estimator, %(name)s, must be fitted before densifying.msg)r$r0r1rztoarrayrsrs r@densifyzSparseCoefMixin.densifys=G#& ;;tzz "++-DJ rBcld}t||tj|j|_|S)a Convert coefficient matrix to sparse format. Converts the ``coef_`` member to a scipy.sparse matrix, which for L1-regularized models can be much more memory- and storage-efficient than the usual numpy.ndarray representation. The ``intercept_`` member is not converted. Returns ------- self Fitted estimator. Notes ----- For non-sparse models, i.e. when there are not many zeros in ``coef_``, this may actually *increase* memory usage, so use this method with care. A rule of thumb is that the number of zero elements, which can be computed with ``(coef_ == 0).sum()``, must be more than 50% for this to provide significant benefits. After calling this method, further fitting with the partial_fit method (if any) will not work until you call densify. z7Estimator, %(name)s, must be fitted before sparsifying.r)r$r0 csr_matrixrzrs r@sparsifyzSparseCoefMixin.sparsifys-4H#&]]4::.  rBN)rrrrrrrrrBr@rrs (rBrc eZdZUdZdgdgdegdgeedddgdZee d<d d d dd d d Z e d ddZ fdZ xZS)LinearRegressiona Ordinary least squares Linear Regression. LinearRegression fits a linear model with coefficients w = (w1, ..., wp) to minimize the residual sum of squares between the observed targets in the dataset, and the targets predicted by the linear approximation. Parameters ---------- fit_intercept : bool, default=True Whether to calculate the intercept for this model. If set to False, no intercept will be used in calculations (i.e. data is expected to be centered). copy_X : bool, default=True If True, X will be copied; else, it may be overwritten. tol : float, default=1e-6 The precision of the solution (`coef_`) is determined by `tol` which specifies a different convergence criterion for the `lsqr` solver. `tol` is set as `atol` and `btol` of `scipy.sparse.linalg.lsqr` when fitting on sparse training data. This parameter has no effect when fitting on dense data. .. versionadded:: 1.7 n_jobs : int, default=None The number of jobs to use for the computation. This will only provide speedup in case of sufficiently large problems, that is if firstly `n_targets > 1` and secondly `X` is sparse or if `positive` is set to `True`. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary ` for more details. positive : bool, default=False When set to ``True``, forces the coefficients to be positive. This option is only supported for dense arrays. For a comparison between a linear regression model with positive constraints on the regression coefficients and a linear regression without such constraints, see :ref:`sphx_glr_auto_examples_linear_model_plot_nnls.py`. .. versionadded:: 0.24 Attributes ---------- coef_ : array of shape (n_features, ) or (n_targets, n_features) Estimated coefficients for the linear regression problem. If multiple targets are passed during the fit (y 2D), this is a 2D array of shape (n_targets, n_features), while if only one target is passed, this is a 1D array of length n_features. rank_ : int Rank of matrix `X`. Only available when `X` is dense. singular_ : array of shape (min(X, y),) Singular values of `X`. Only available when `X` is dense. intercept_ : float or array of shape (n_targets,) Independent term in the linear model. Set to 0.0 if `fit_intercept = False`. n_features_in_ : int Number of features seen during :term:`fit`. .. versionadded:: 0.24 feature_names_in_ : ndarray of shape (`n_features_in_`,) Names of features seen during :term:`fit`. Defined only when `X` has feature names that are all strings. .. versionadded:: 1.0 See Also -------- Ridge : Ridge regression addresses some of the problems of Ordinary Least Squares by imposing a penalty on the size of the coefficients with l2 regularization. Lasso : The Lasso is a linear model that estimates sparse coefficients with l1 regularization. ElasticNet : Elastic-Net is a linear regression model trained with both l1 and l2 -norm regularization of the coefficients. Notes ----- From the implementation point of view, this is just plain Ordinary Least Squares (scipy.linalg.lstsq) or Non Negative Least Squares (scipy.optimize.nnls) wrapped as a predictor object. Examples -------- >>> import numpy as np >>> from sklearn.linear_model import LinearRegression >>> X = np.array([[1, 1], [1, 2], [2, 2], [2, 3]]) >>> # y = 1 * x_0 + 2 * x_1 + 3 >>> y = np.dot(X, np.array([1, 2])) + 3 >>> reg = LinearRegression().fit(X, y) >>> reg.score(X, y) 1.0 >>> reg.coef_ array([1., 2.]) >>> reg.intercept_ np.float64(3.0) >>> reg.predict(np.array([[3, 5]])) array([16.]) booleanNrleft)closed)r\copy_Xn_jobspositivetol_parameter_constraintsTgư>Fr\rrrrcJ||_||_||_||_||_yNr)rsr\rrrrs r@__init__zLinearRegression.__init__?s(+    rB)prefer_skip_nested_validationc Bj}jrdngd}t|ddd\|du}|rt|jd}j xrt j }tj||\}} } |rt||\jrjd kr tjd _nt| fd t!j"d D} t%j&| D cgc]} | d  c} _nt jr|| z |rfd} fd}n fd} fd}t(j*j-j"| |jd kr,t/j0j0d _nt| fdt!j"d D} t%j&| D cgc]} | d  c} _nt3j"t%j4jj6z}t+j8|\_}__jj>_jd k(r$t%j@j_jC|| | Scc} wcc} w)ap Fit linear model. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training data. y : array-like of shape (n_samples,) or (n_samples, n_targets) Target values. Will be cast to X's dtype if necessary. sample_weight : array-like of shape (n_samples,), default=None Individual weights for each sample. .. versionadded:: 0.17 parameter *sample_weight* support to LinearRegression. Returns ------- self : object Fitted Estimator. FrvT)rI y_numeric multi_outputforce_writeableN)r.ensure_non_negative)r\rCr9)rkr r)rc3lK|]+}ttjdd|f-ywr)r!rnnls).0jr7r8s r@ z'LinearRegression.fit..s10;<*GHMM*1a1g60s14r'cPj||jzz Srdotbr7X_offset_scalerls r@matvecz$LinearRegression.fit..matvecs%558&8155;P&PPPrBcdjj||jzz Sr)r|rrs r@rmatvecz%LinearRegression.fit..rmatvecs)33771:?Q9R(RRRrBcJj||jz Srrrr7rs r@rz$LinearRegression.fit..matvecs558aeeN&;;;rBcbjj||jzz Sr)r|rrrs r@rz%LinearRegression.fit..rmatvecs%33771:(@@@rB)rSrratolbtolc3K|]F}ttdd|fjjjHyw)Nr)r!r ravelr)rr X_centeredrsr8s r@rz'LinearRegression.fit..sJ0"GDM"AadGMMO$((0sA A)cond)"rrr%r#r.rr0r1rgr\rnrZrrrzr rangerSr*rr rLinearOperatorr rr-finfoepslstsqrank_ singular_r|rr)rsr7r8r9n_jobs_rIhas_swcopy_X_in_preprocess_datarcrerfoutsrrrrr]rrrls``` @@@r@rtzLinearRegression.fitNs0++!%4I   '  1d* 0qTM%)KK$F A4F!,< ,,*' - )1h' (51m-F( $Aq$ ==vvz%]]1a03 0xw/0@Eaggaj@Q0 YY$'?3A'?@ [[^%/NQS <A 55ggfg6Jvvz!*adhhTXXNqQ 0xw/0#1771:. 0  YY$'?3A'?@ qww<"((177"3"7"77D8> QPT8U 5DJ4:t~DJ 66Q;$**-DJ Hh8 Y(@D(@s 2 L0 Lc\t|}|j |j_|Sr)super__sklearn_tags__r input_tagsr )rstags __class__s r@rz!LinearRegression.__sklearn_tags__s(w')%)]]!2 rBr)rrrrrrrrdict__annotations__rrrtr __classcell__)rs@r@rrsjZ$+"Kq$v67 $D  !5t6tlrBrc |jd}|dz}t|dz|dz }|dd|f||z ||z} |dd|f||z ||z} tj| | } |||f} |j| jg} |/| Dcgc]}|tj k(rdnd}}t |}tj| | ||std|d|d | d | d ycc}w) a^Computes a single element of the gram matrix and compares it to the corresponding element of the user supplied gram matrix. If the values do not match a ValueError will be thrown. Parameters ---------- X : ndarray of shape (n_samples, n_features) Data array. precompute : array-like of shape (n_features, n_features) User-supplied gram matrix. X_offset : ndarray of shape (n_features,) Array of feature means used to center design matrix. X_scale : ndarray of shape (n_features,) Array of feature scale factors used to normalize design matrix. rtol : float, default=None Relative tolerance; see numpy.allclose If None, it is set to 1e-4 for arrays of dtype numpy.float32 and 1e-7 otherwise. atol : float, default=1e-5 absolute tolerance; see :func`numpy.allclose`. Note that the default here is more tolerant than the default for :func:`numpy.testing.assert_allclose`, where `atol=0`. Raises ------ ValueError Raised when the provided Gram matrix is not consistent. r'r Ng-C6?gHz>)rtolrzGram matrix passed in via 'precompute' parameter did not pass validation when a single element was checked - please check that it was computed properly. For element (,z) we computed z! but the user-supplied value was .) rSminr*rr.r/r-isclose ValueError)r7 precomputercrfrrr`f1f2v1v2expectedactualdtypesr.rtolss r@_check_precomputed_gram_matrixrs!LJ qB R!VZ!^ $B ArE(Xb\ !WR[ 0B ArE(Xb\ !WR[ 0Bvvb"~H B F /F |DJK5"**,$6KK5z ::hT = &')T2$nj9ha     >Ls C)cD|j\}} tj|rd}t|||d||\}}} } } n+t||||||\}}} } } |t |||\}}} t |drZ|rHt j| t j| stjdtd}d}n|rt||| | t|tr |dk(r|| kD}|durFt j| | f|j d }t j"|j$|| t |dsd}t |dr|t j&|j |j }|j(d k(r;t j| |d }t j"|j$|| nU|jd }t j| |f|d }t j"|j$||j$ ||| | | ||fS)zFunction used at beginning of fit in linear models with L1 or L0 penalty. This function applies _preprocess_data and additionally computes the gram matrix `precompute` as needed as well as `Xy`. F)r\rCrEr9N)r9 __array__zVGram matrix was provided but X was centered to fit intercept: recomputing Gram matrix.autoTC)rSr.rMrr'F)rSr r1rgrnhasattrr*allcloserYwarningswarn UserWarningrrTstremptyr.rr| result_typerZ)r7r8Xyrr\rCrEr9r_r`rcrerfr] common_dtype n_targetss r@_pre_fitr  sGGIz q ,< '#' - )1h'-= '#' - )1h'  $#Aq FGAq!z;' Xrxx 7K!L MM:   JB  +1j(G L*c"zV';+ TXXZ$)TN)@rrUrabcrrrrnumpyr* scipy.sparser r0scipyrrscipy.sparse.linalgr scipy.specialr baser rrrrutilsrrutils._array_apirrrrrrutils._param_validationrutils._seq_datasetrrrr utils.extmathrutils.parallelr r!utils.sparsefuncsr"utils.validationr#r$r%r5rArgrnrprrrrr rrrBr@rs'"**$4/ ,.2SS  2$t  ^-L6$r4"-74"rIOIX77t~'~D7;= NZ=rB