`L iXqdZddlmZddlmZmZddlZddlm Z ddl m Z ddl m Z mZdd lmZdd lmZdd lmZdd lmZmZd dlmZmZmZGdde eZGdde eZy)z Various bayesian regression )log)IntegralRealN)linalg)pinvh)RegressorMixin _fit_context)_safe_indexing)Interval) fast_logdet)_check_sample_weight validate_data) LinearModel_preprocess_data _rescale_datacLeZdZUdZeedddgeedddgeedddgeedddgeedddgeedddgdeedddgdeedddgdgdgdgd gd Zee d <d d ddddddddddd dZ e dddZ ddZ dZdZy) BayesianRidgea Bayesian ridge regression. Fit a Bayesian ridge model. See the Notes section for details on this implementation and the optimization of the regularization parameters lambda (precision of the weights) and alpha (precision of the noise). Read more in the :ref:`User Guide `. For an intuitive visualization of how the sinusoid is approximated by a polynomial using different pairs of initial values, see :ref:`sphx_glr_auto_examples_linear_model_plot_bayesian_ridge_curvefit.py`. Parameters ---------- max_iter : int, default=300 Maximum number of iterations over the complete dataset before stopping independently of any early stopping criterion. .. versionchanged:: 1.3 tol : float, default=1e-3 Stop the algorithm if w has converged. alpha_1 : float, default=1e-6 Hyper-parameter : shape parameter for the Gamma distribution prior over the alpha parameter. alpha_2 : float, default=1e-6 Hyper-parameter : inverse scale parameter (rate parameter) for the Gamma distribution prior over the alpha parameter. lambda_1 : float, default=1e-6 Hyper-parameter : shape parameter for the Gamma distribution prior over the lambda parameter. lambda_2 : float, default=1e-6 Hyper-parameter : inverse scale parameter (rate parameter) for the Gamma distribution prior over the lambda parameter. alpha_init : float, default=None Initial value for alpha (precision of the noise). If not set, alpha_init is 1/Var(y). .. versionadded:: 0.22 lambda_init : float, default=None Initial value for lambda (precision of the weights). If not set, lambda_init is 1. .. versionadded:: 0.22 compute_score : bool, default=False If True, compute the log marginal likelihood at each iteration of the optimization. fit_intercept : bool, default=True Whether to calculate the intercept for this model. The intercept is not treated as a probabilistic parameter and thus has no associated variance. 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. verbose : bool, default=False Verbose mode when fitting the model. Attributes ---------- coef_ : array-like of shape (n_features,) Coefficients of the regression model (mean of distribution) intercept_ : float Independent term in decision function. Set to 0.0 if `fit_intercept = False`. alpha_ : float Estimated precision of the noise. lambda_ : float Estimated precision of the weights. sigma_ : array-like of shape (n_features, n_features) Estimated variance-covariance matrix of the weights scores_ : array-like of shape (n_iter_+1,) If computed_score is True, value of the log marginal likelihood (to be maximized) at each iteration of the optimization. The array starts with the value of the log marginal likelihood obtained for the initial values of alpha and lambda and ends with the value obtained for the estimated alpha and lambda. n_iter_ : int The actual number of iterations to reach the stopping criterion. X_offset_ : ndarray of shape (n_features,) If `fit_intercept=True`, offset subtracted for centering data to a zero mean. Set to np.zeros(n_features) otherwise. X_scale_ : ndarray of shape (n_features,) Set to np.ones(n_features). 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 -------- ARDRegression : Bayesian ARD regression. Notes ----- There exist several strategies to perform Bayesian ridge regression. This implementation is based on the algorithm described in Appendix A of (Tipping, 2001) where updates of the regularization parameters are done as suggested in (MacKay, 1992). Note that according to A New View of Automatic Relevance Determination (Wipf and Nagarajan, 2008) these update rules do not guarantee that the marginal likelihood is increasing between two consecutive iterations of the optimization. References ---------- D. J. C. MacKay, Bayesian Interpolation, Computation and Neural Systems, Vol. 4, No. 3, 1992. M. E. Tipping, Sparse Bayesian Learning and the Relevance Vector Machine, Journal of Machine Learning Research, Vol. 1, 2001. Examples -------- >>> from sklearn import linear_model >>> clf = linear_model.BayesianRidge() >>> clf.fit([[0,0], [1, 1], [2, 2]], [0, 1, 2]) BayesianRidge() >>> clf.predict([[1, 1]]) array([1.]) rNleftclosedrneitherbooleanverbose max_itertolalpha_1alpha_2lambda_1lambda_2 alpha_init lambda_init compute_score fit_interceptcopy_Xr_parameter_constraints,MbP?ư>FTc ||_||_||_||_||_||_||_||_| |_| |_ | |_ | |_ yNr) selfrrrr r!r"r#r$r%r&r'rs a/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sklearn/linear_model/_bayes.py__init__zBayesianRidge.__init__s[ !       $&**  prefer_skip_nested_validationc t|||tjtjgdd\}}|j}|j \}}|}|j }|Rt|||}|j}tj||} tj|| z dz|}t|||j|j|\}}} } } |t|||\}}} | |_| |_tj tjj"}|j$}|j&}|d||zz }|d}tj(||}tj(||}|j*}|j,}|j.}|j0}|j2}t5|_d}tj8|j:|}t=j>|||k \}}}tA|}|dz}tjB||}||d ||d |ddf}tE|jFD]'}|jI|||||||||| \} }!|jJr3|jM||||||| |!}"|j6jO|"tj||z|||zzz }#|#d|zztj| dzd|zzz }||#z d|zz|!d|zzz }|d k7rRtjtjP|| z |jRkr|rtUd tW|d ntjX| }*d z|_-||_.||_/|jI|||||||||| \|_0}!|jJrW|jM|||||| |!}"|j6jO|"tjb|j6|_tj8|j:|||z|zddtjdfz |_3|ji| | | |S)a7Fit the model. Parameters ---------- X : ndarray of shape (n_samples, n_features) Training data. y : ndarray of shape (n_samples,) Target values. Will be cast to X's dtype if necessary. sample_weight : ndarray of shape (n_samples,), default=None Individual weights for each sample. .. versionadded:: 0.20 parameter *sample_weight* support to BayesianRidge. Returns ------- self : object Returns the instance itself. T)dtypeforce_writeable y_numericNr5)weightsr)r&copy sample_weight?) full_matricesrzConvergence after z iterationsr)5rnpfloat64float32r5shapevarrsumaveragerr&r'r X_offset_X_scale_finfoepsr#r$asarrayrr!r"rr listscores_dotTrsvdlenzerosranger _update_coef_r%_log_marginal_likelihoodappendabsrprintstrr:n_iter_alpha_lambda_coef_arraynewaxissigma__set_intercept)$r.Xyr;r5 n_samples n_featuressw_sumy_vary_meanrE y_offset_rF_rHrYrZrr!r"rr coef_old_XT_yUSVh_fullK eigen_vals_eigen_vals_fullVhiter_r[sse_sgamma_s$ r/fitzBayesianRidge.fitsQ,  ::rzz*   1 ! :  $0OM"&&(FZZ=9FJJF q0-HE/? ,,' 0 ,1iH  $#Aq-8GAq!"  hhrzz"&&"" >ECK(F ?GF%0**WE2,,====,,,,v  vvacc1~ 1Y5KM 1g Fd ((:U;*! QqS!V_4==) 'E,,1iT1b+vwKE4!!11  ##A&VVVk1g@T6TUVFH ,q1AAL1PQGvoG 3q7{8JKFzbffRVVI,=%>?$((J.E MJI= '@qy   -- q)Zq"k67  D   -- A LL   "88DLL1DLff IIw&?":W"Dam!TT   Iy(; r1c|j|}|s|Stj||j|zj d}tj |d|j z z}||fS)Predict using the linear model. In addition to the mean of the predictive distribution, also its standard deviation can be returned. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Samples. return_std : bool, default=False Whether to return the standard deviation of posterior prediction. Returns ------- y_mean : array-like of shape (n_samples,) Mean of predictive distribution of query points. y_std : array-like of shape (n_samples,) Standard deviation of predictive distribution of query points. raxisr<)_decision_functionr>rLr^rCsqrtrY)r.r` return_stdrfsigmas_squared_datay_stds r/predictzBayesianRidge.predictxsk,((+M#%66!T[[#9A#="B"B"B"J GG/33DEFE5= r1c ||kDrKtjj|j||| | z zddtjfz |g} nGtjj|j||| | z zdddfz |j|g} tj |tj || z dz} | | fS)a Update posterior mean and compute corresponding sse (sum of squared errors). Posterior mean is given by coef_ = scaled_sigma_ * X.T * y where scaled_sigma_ = (lambda_/alpha_ * np.eye(n_features) + np.dot(X.T, X))^-1 Nr)r>r multi_dotrMr]rCrL) r.r`rarbrcrjrkrqrorYrZr[rss r/rRzBayesianRidge._update_coef_s z !II''r[7V+;;Q ]KKTREII''a;6)9947CCQSS!LE vvq266!U++12d{r1c |j} |j} |j} |j} ||kDr0t j t j |||zz } not j||t j|j} | d|xxx||zz ccct j t j |  } | t |z| |zz }|| t |z| |zz z }|d|t |z|t |zz||zz |t j |dzzz | z|t dtjzzz zz }|S)zLog marginal likelihood.r8N?r) rr r!r"r>rCrfullr\r5pi)r.rbrcrd eigen_valsrYrZcoefsserr r!r" logdet_sigmascores r/rSz&BayesianRidge._log_marginal_likelihoods^,,,,==== z !FF266'FZ4G*G#HIIL77:wbhhw>O>U>UVL ) $(; ; $FF266,#788L3w<'(W*<< 3v;&6)999  W %s6{" #sl tQw' (   s1ruu9~%  &   r1r-F)__name__ __module__ __qualname____doc__r rrr(dict__annotations__r0r rvrrRrSr1r/rrsOdh4?@q$y9:T1d6:;T1d6:;dAtF;<dAtF;<XdAtFCDhtQVDE##+; $D $ :5]6]~!<2r1rc ,eZdZUdZeedddgeedddgeedddgeedddgeedddgeedddgdgeedddgdgdgdgd Zee d <d d d d d d dddddd dZ e ddZ dZ dZddZy) ARDRegressiona5Bayesian ARD regression. Fit the weights of a regression model, using an ARD prior. The weights of the regression model are assumed to be in Gaussian distributions. Also estimate the parameters lambda (precisions of the distributions of the weights) and alpha (precision of the distribution of the noise). The estimation is done by an iterative procedures (Evidence Maximization) Read more in the :ref:`User Guide `. Parameters ---------- max_iter : int, default=300 Maximum number of iterations. .. versionchanged:: 1.3 tol : float, default=1e-3 Stop the algorithm if w has converged. alpha_1 : float, default=1e-6 Hyper-parameter : shape parameter for the Gamma distribution prior over the alpha parameter. alpha_2 : float, default=1e-6 Hyper-parameter : inverse scale parameter (rate parameter) for the Gamma distribution prior over the alpha parameter. lambda_1 : float, default=1e-6 Hyper-parameter : shape parameter for the Gamma distribution prior over the lambda parameter. lambda_2 : float, default=1e-6 Hyper-parameter : inverse scale parameter (rate parameter) for the Gamma distribution prior over the lambda parameter. compute_score : bool, default=False If True, compute the objective function at each step of the model. threshold_lambda : float, default=10 000 Threshold for removing (pruning) weights with high precision from the computation. 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. verbose : bool, default=False Verbose mode when fitting the model. Attributes ---------- coef_ : array-like of shape (n_features,) Coefficients of the regression model (mean of distribution) alpha_ : float estimated precision of the noise. lambda_ : array-like of shape (n_features,) estimated precisions of the weights. sigma_ : array-like of shape (n_features, n_features) estimated variance-covariance matrix of the weights scores_ : float if computed, value of the objective function (to be maximized) n_iter_ : int The actual number of iterations to reach the stopping criterion. .. versionadded:: 1.3 intercept_ : float Independent term in decision function. Set to 0.0 if ``fit_intercept = False``. X_offset_ : float If `fit_intercept=True`, offset subtracted for centering data to a zero mean. Set to np.zeros(n_features) otherwise. X_scale_ : float Set to np.ones(n_features). 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 -------- BayesianRidge : Bayesian ridge regression. References ---------- D. J. C. MacKay, Bayesian nonlinear modeling for the prediction competition, ASHRAE Transactions, 1994. R. Salakhutdinov, Lecture notes on Statistical Machine Learning, http://www.utstat.toronto.edu/~rsalakhu/sta4273/notes/Lecture2.pdf#page=15 Their beta is our ``self.alpha_`` Their alpha is our ``self.lambda_`` ARD is a little different than the slide: only dimensions/features for which ``self.lambda_ < self.threshold_lambda`` are kept and the rest are discarded. Examples -------- >>> from sklearn import linear_model >>> clf = linear_model.ARDRegression() >>> clf.fit([[0,0], [1, 1], [2, 2]], [0, 1, 2]) ARDRegression() >>> clf.predict([[1, 1]]) array([1.]) - :ref:`sphx_glr_auto_examples_linear_model_plot_ard.py` demonstrates ARD Regression. - :ref:`sphx_glr_auto_examples_linear_model_plot_lasso_and_elasticnet.py` showcases ARD Regression alongside Lasso and Elastic-Net for sparse, correlated signals, in the presence of noise. rNrrrrr) rrrr r!r"r%threshold_lambdar&r'rr(r)r*r+Fg@Tc ||_||_| |_||_||_||_||_||_||_| |_ | |_ yr-) rrr&rr r!r"r%rr'r) r.rrrr r!r"r%rr&r'rs r/r0zARDRegression.__init__fsT! *      * 0  r1r2c ~t|||tjtjgddd\}}|j}|j \}}tj ||}t|||j|j\}}}}} ||_ | |_ tj|t} |j} |j} |j } |j"}|j$}tj&tjj(}tj*dtj,||zz |}tj||}t/|_d}d}||k\r |j2n |j4}t7|j8D]}||||| }|||||| |}tj:|tj<||z dz}d|| tj>|zz }|d | zz|| dzd | zzz || <||j;z d | zz|d |zzz }||j@k} d || <|jBr| tjD|z| |zz j;}|| tE|z||zz z }|d tG||tE|zztj:tjD|zzz }|d ||z||dzzj;zzz}|j0jI||d kDrJtj:tjJ||z |jLkr|rtOd |zn*tjP|}| jSrnd z|_*| jSr||||| }|||||| |}n%tjVgjYd d }||_-||_.||_/||_0|jc||| |S)a0Fit the model according to the given training data and parameters. Iterative procedure to maximize the evidence Parameters ---------- X : array-like 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 values (integers). Will be cast to X's dtype if necessary. Returns ------- self : object Fitted estimator. Tr)r5r6r7ensure_min_samplesr8)r&r:r<Ncx|tjj||dd|fj|gz||<|Sr-)r>rrrM)r`rar[rY keep_lambdar^s r/ update_coeffz'ARDRegression.fit..update_coeffsB!'"))*=*=1k>*,,a0+"E+ Lr1g@rrzConverged after %s iterationsr)2rr>r?r@r5rArPrr&r'rErFonesboolr!r"rr rrGrHrIrBrJrK _update_sigma_update_sigma_woodburyrQrrCrLdiagrr%rr rTrUrrVr:anyrXr\reshaper[rYr^rZr_)r.r`rar5rbrcr[rErgrFrr!r"rr rrHrYrZrir update_sigmarrr^rsrurts r/rvzARDRegression.fits&  ::rzz*   1 ! :51/? q 2 20 ,1iH#  ggj5 ====,,,,,,hhrzz"&&C266!9s?35A''*E2v   J&   ,,  4==)$ E!!VWkBF Aufk6JE661rvva//A56D7;/"''&/AAF$*S8^$;{#)C(N:$GK  &**,.w>4#PW-CWXF"D$9$99K"#E;, !!w/(W2DDIIKWs6{*Wv-===S'#f+-.ffRVVG_-. SFTMWuax-?,D,D,FFGG ##A&qyRVVBFF9u+<$=>I9EABI??$I$ Lqy ?? !!VWkBF Aufk6JEXXb\))!Q/F     Iy(; r1c|jd}|dd|f}d||jddz }ttj||j |z tj ||z|jz}tj |||z}tj |jdd|jz| }|tj|jdxxd||z z cc<|S)Nrrr8r<) rArrr>eyer5rLrM diag_indices) r.r`rYrZrrbX_keep inv_lambdar^s r/rz$ARDRegression._update_sigma_woodburys GGAJ 1k>"-55a<<  FF9AGG ,v 5ffVj(&((3 4  34&&++B2VXX=vFFrv||A/0C'+:N4NN0 r1c|dd|f}tj|j|}tj|jd|j }|||z||zz}t |} | S)Nrr8)r>rLrMrrAr5r) r.r`rYrZrrgramr sigma_invr^s r/rzARDRegression._update_sigmasi1k>"vvfhh'ffTZZ]!''2K(3.$> y! r1c6|j|}|dur|S|j|jk}t||d}t j ||j |zjd}t j|d|jz z}||fS)rxFr)indicesrzryr<) r{rZrr r>rLr^rCr|rY)r.r`r}rf col_indexr~rs r/rzARDRegression.predicts,((+  M t'<'<scipyr scipy.linalgrbaser r utilsr utils._param_validationr utils.extmathr utils.validationrr_baserrrrrrr1r/rsQ"/".'B?? sNKst f!NKf!r1