
    Kid                     "   S SK r S SKJrJr  S SKrS SKJrJrJ	r	J
r
JrJr  S SKJr  S SKJr  S SKJrJrJr  S SKJr  S SKJrJrJrJrJr  S S	KJrJrJ r J!r!J"r"  S S
K#J$r$  S SK%J&r&J'r'J(r(J)r)J*r*  \RV                  " S5      r,S r- " S S\\
\	\5      r.g)    N)IntegralReal)BaseEstimatorMetaEstimatorMixinMultiOutputMixinRegressorMixin_fit_contextclone)ConvergenceWarning)LinearRegression)check_consistent_lengthcheck_random_stateget_tags)Bunch)
HasMethodsIntervalOptions
RealNotInt
StrOptions)MetadataRouterMethodMapping_raise_for_params_routing_enabledprocess_routing)sample_without_replacement)_check_method_params_check_sample_weightcheck_is_fittedhas_fit_parametervalidate_data   c           
      D   U [        U5      -  n[        [        SU-
  5      n[        [        SXB-  -
  5      nUS:X  a  gUS:X  a  [        S5      $ [        [        [        R
                  " [        R                  " U5      [        R                  " U5      -  5      5      5      $ )a  Determine number trials such that at least one outlier-free subset is
sampled for the given inlier/outlier ratio.

Parameters
----------
n_inliers : int
    Number of inliers in the data.

n_samples : int
    Total number of samples in the data.

min_samples : int
    Minimum number of samples chosen randomly from original data.

probability : float
    Probability (confidence) that one outlier-free sample is generated.

Returns
-------
trials : int
    Number of trials.

r!   r   inf)floatmax_EPSILONabsnpceillog)	n_inliers	n_samplesmin_samplesprobabilityinlier_rationomdenoms          ^/var/www/html/dynamic-report/venv/lib/python3.13/site-packages/sklearn/linear_model/_ransac.py_dynamic_max_trialsr3   /   s    0 uY//L
hK
(C!l778E
axzU|uRWWRVVC[266%=89:;;    c                     ^  \ rS rSr% Sr\" / SQ5      S/\" \SSSS9\" \SSS	S9S/\" \	SSSS9S/\
S/\
S/\" \SSSS9\" \	\R                  15      /\" \SSSS9\" \	\R                  15      /\" \SSSS9\" \	\R                  15      /\" \	SSS	S9/\" \	SSS	S9/\" S
S15      \
/S/S.r\\S'    SSSSSS\R                  \R                  \R                  SS
SS.S jjr\" SS9SS j5       rS rS rS rU 4S jrSrU =r$ )RANSACRegressorQ   a  RANSAC (RANdom SAmple Consensus) algorithm.

RANSAC is an iterative algorithm for the robust estimation of parameters
from a subset of inliers from the complete data set.

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

Parameters
----------
estimator : object, default=None
    Base estimator object which implements the following methods:

    * `fit(X, y)`: Fit model to given training data and target values.
    * `score(X, y)`: Returns the mean accuracy on the given test data,
      which is used for the stop criterion defined by `stop_score`.
      Additionally, the score is used to decide which of two equally
      large consensus sets is chosen as the better one.
    * `predict(X)`: Returns predicted values using the linear model,
      which is used to compute residual error using loss function.

    If `estimator` is None, then
    :class:`~sklearn.linear_model.LinearRegression` is used for
    target values of dtype float.

    Note that the current implementation only supports regression
    estimators.

min_samples : int (>= 1) or float ([0, 1]), default=None
    Minimum number of samples chosen randomly from original data. Treated
    as an absolute number of samples for `min_samples >= 1`, treated as a
    relative number `ceil(min_samples * X.shape[0])` for
    `min_samples < 1`. This is typically chosen as the minimal number of
    samples necessary to estimate the given `estimator`. By default a
    :class:`~sklearn.linear_model.LinearRegression` estimator is assumed and
    `min_samples` is chosen as ``X.shape[1] + 1``. This parameter is highly
    dependent upon the model, so if a `estimator` other than
    :class:`~sklearn.linear_model.LinearRegression` is used, the user must
    provide a value.

residual_threshold : float, default=None
    Maximum residual for a data sample to be classified as an inlier.
    By default the threshold is chosen as the MAD (median absolute
    deviation) of the target values `y`. Points whose residuals are
    strictly equal to the threshold are considered as inliers.

is_data_valid : callable, default=None
    This function is called with the randomly selected data before the
    model is fitted to it: `is_data_valid(X, y)`. If its return value is
    False the current randomly chosen sub-sample is skipped.

is_model_valid : callable, default=None
    This function is called with the estimated model and the randomly
    selected data: `is_model_valid(model, X, y)`. If its return value is
    False the current randomly chosen sub-sample is skipped.
    Rejecting samples with this function is computationally costlier than
    with `is_data_valid`. `is_model_valid` should therefore only be used if
    the estimated model is needed for making the rejection decision.

max_trials : int, default=100
    Maximum number of iterations for random sample selection.

max_skips : int, default=np.inf
    Maximum number of iterations that can be skipped due to finding zero
    inliers or invalid data defined by ``is_data_valid`` or invalid models
    defined by ``is_model_valid``.

    .. versionadded:: 0.19

stop_n_inliers : int, default=np.inf
    Stop iteration if at least this number of inliers are found.

stop_score : float, default=np.inf
    Stop iteration if score is greater equal than this threshold.

stop_probability : float in range [0, 1], default=0.99
    RANSAC iteration stops if at least one outlier-free set of the training
    data is sampled in RANSAC. This requires to generate at least N
    samples (iterations)::

        N >= log(1 - probability) / log(1 - e**m)

    where the probability (confidence) is typically set to high value such
    as 0.99 (the default) and e is the current fraction of inliers w.r.t.
    the total number of samples.

loss : str, callable, default='absolute_error'
    String inputs, 'absolute_error' and 'squared_error' are supported which
    find the absolute error and squared error per sample respectively.

    If ``loss`` is a callable, then it should be a function that takes
    two arrays as inputs, the true and predicted value and returns a 1-D
    array with the i-th value of the array corresponding to the loss
    on ``X[i]``.

    If the loss on a sample is greater than the ``residual_threshold``,
    then this sample is classified as an outlier.

    .. versionadded:: 0.18

random_state : int, RandomState instance, default=None
    The generator used to initialize the centers.
    Pass an int for reproducible output across multiple function calls.
    See :term:`Glossary <random_state>`.

Attributes
----------
estimator_ : object
    Final model fitted on the inliers predicted by the "best" model found
    during RANSAC sampling (copy of the `estimator` object).

n_trials_ : int
    Number of random selection trials until one of the stop criteria is
    met. It is always ``<= max_trials``.

inlier_mask_ : bool array of shape [n_samples]
    Boolean mask of inliers classified as ``True``.

n_skips_no_inliers_ : int
    Number of iterations skipped due to finding zero inliers.

    .. versionadded:: 0.19

n_skips_invalid_data_ : int
    Number of iterations skipped due to invalid data defined by
    ``is_data_valid``.

    .. versionadded:: 0.19

n_skips_invalid_model_ : int
    Number of iterations skipped due to an invalid model defined by
    ``is_model_valid``.

    .. versionadded:: 0.19

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.
TheilSenRegressor : Theil-Sen Estimator robust multivariate regression model.
SGDRegressor : Fitted by minimizing a regularized empirical loss with SGD.

References
----------
.. [1] https://en.wikipedia.org/wiki/RANSAC
.. [2] https://www.sri.com/wp-content/uploads/2021/12/ransac-publication.pdf
.. [3] https://bmva-archive.org.uk/bmvc/2009/Papers/Paper355/Paper355.pdf

Examples
--------
>>> from sklearn.linear_model import RANSACRegressor
>>> from sklearn.datasets import make_regression
>>> X, y = make_regression(
...     n_samples=200, n_features=2, noise=4.0, random_state=0)
>>> reg = RANSACRegressor(random_state=0).fit(X, y)
>>> reg.score(X, y)
0.9885
>>> reg.predict(X[:1,])
array([-31.9417])

For a more detailed example, see
:ref:`sphx_glr_auto_examples_linear_model_plot_ransac.py`
)fitscorepredictNr!   left)closedr   bothabsolute_errorsquared_errorrandom_state)	estimatorr-   residual_thresholdis_data_validis_model_valid
max_trials	max_skipsstop_n_inliers
stop_scorestop_probabilitylossr@   _parameter_constraintsd   gGz?)r-   rB   rC   rD   rE   rF   rG   rH   rI   rJ   r@   c                    Xl         X l        X0l        X@l        XPl        X`l        Xpl        Xl        Xl        Xl	        Xl
        Xl        g N)rA   r-   rB   rC   rD   rE   rF   rG   rH   rI   r@   rJ   )selfrA   r-   rB   rC   rD   rE   rF   rG   rH   rI   rJ   r@   s                r2   __init__RANSACRegressor.__init__   sG      #&"4*,$",$ 0(	r4   F)prefer_skip_nested_validationc           	      x   [        X@S5        [        SSS9n[        SS9n[        XX%U4S9u  p[        X5        U R                  b  [        U R                  5      nO
[        5       nU R                  c3  [        U[        5      (       d  [        S5      eUR                  S	   S	-   nOgS
U R                  s=:  a  S	:  a4  O  O1[        R                  " U R                  UR                  S
   -  5      nOU R                  S	:  a  U R                  nWUR                  S
   :  a  [        SUR                  S
   -  5      eU R                  cB  [        R                  " [        R                  " U[        R                  " U5      -
  5      5      n	OU R                  n	U R                   S:X  a  UR"                  S	:X  a  S n
ORS n
ONU R                   S:X  a  UR"                  S	:X  a  S n
O*S n
O&[%        U R                   5      (       a  U R                   n
['        U R(                  5      n UR+                  US9  [-        US5      n[/        U5      R0                  nUb  U(       d  [        SU-  5      eUb  X4S'   [3        5       (       a  [5        U S40 UD6nO;[7        5       n[7        0 0 0 S9Ul        Ub  [9        X15      nSU0UR                  l        S	n[        R<                  * nSnSnSnSnS
U l        S
U l         S
U l!        UR                  S
   n[        RD                  " U5      nS
U l#        U RH                  nU RF                  U:  Ga  U =RF                  S	-  sl#        U R>                  U R@                  -   U RB                  -   U RJ                  :  a  GO[M        UXS9nUU   nUU   nU RN                  b.  U RO                  UU5      (       d  U =R@                  S	-  sl         M  [Q        XR                  R:                  US9nUR:                  " UU40 UD6  U RR                  b0  U RS                  UUU5      (       d  U =RB                  S	-  sl!        GM  URU                  U5      nW
" UU5      nUU	:*  n[        RV                  " U5      nUU:  a  U =R>                  S	-  sl        GMm  UU   n UU    n!UU    n"[Q        XR                  RX                  U S9n#URX                  " U!U"40 U#D6n$UU:X  a	  U$U:  a  GM  UnU$nUnU!nU"nU n[[        U[]        UUXR^                  5      5      nXR`                  :  d  UU Rb                  :  a  OU RF                  U:  a  GM  UcJ  U R>                  U R@                  -   U RB                  -   U RJ                  :  a  [        S5      e[        S5      eU R>                  U R@                  -   U RB                  -   U RJ                  :  a  [d        Rf                  " S[h        5        [Q        XR                  R:                  US9n%UR:                  " UU40 U%D6  Xpl5        UU l6        U $ ! [         a     GNf = f)a  Fit estimator using RANSAC algorithm.

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.

sample_weight : array-like of shape (n_samples,), default=None
    Individual weights for each sample
    raises error if sample_weight is passed and estimator
    fit method does not support it.

    .. versionadded:: 0.18

**fit_params : dict
    Parameters routed to the `fit` method of the sub-estimator via the
    metadata routing API.

    .. versionadded:: 1.5

        Only available if
        `sklearn.set_config(enable_metadata_routing=True)` is set. See
        :ref:`Metadata Routing User Guide <metadata_routing>` for more
        details.

Returns
-------
self : object
    Fitted `RANSACRegressor` estimator.

Raises
------
ValueError
    If no valid consensus set could be found. This occurs if
    `is_data_valid` and `is_model_valid` return False for all
    `max_trials` randomly chosen sub-samples.
r8   csrF)accept_sparseensure_all_finite)	ensure_2d)validate_separatelyNzR`min_samples` needs to be explicitly set when estimator is not a LinearRegression.r!   r   zG`min_samples` may not be larger than number of samples: n_samples = %d.r>   c                 2    [         R                  " X-
  5      $ rN   )r(   r'   y_truey_preds     r2   <lambda>%RANSACRegressor.fit.<locals>.<lambda>  s    rvvfo7Nr4   c                 X    [         R                  " [         R                  " X-
  5      SS9$ )Nr!   axis)r(   sumr'   rZ   s     r2   r]   r^     s    rvvFF6?+!8r4   r?   c                     X-
  S-  $ )N    rZ   s     r2   r]   r^     s    A7Mr4   c                 6    [         R                  " X-
  S-  SS9$ )Nrd   r!   r`   )r(   rb   rZ   s     r2   r]   r^     s    rvv_*8r4   )r@   sample_weightz[%s does not support sample_weight. Sample weights are only used for the calibration itself.)r8   r:   r9   )paramsindiceszRANSAC skipped more iterations than `max_skips` without finding a valid consensus set. Iterations were skipped because each randomly chosen sub-sample failed the passing criteria. See estimator attributes for diagnostics (n_skips*).zRANSAC could not find a valid consensus set. All `max_trials` iterations were skipped because each randomly chosen sub-sample failed the passing criteria. See estimator attributes for diagnostics (n_skips*).zRANSAC found a valid consensus set but exited early due to skipping more iterations than `max_skips`. See estimator attributes for diagnostics (n_skips*).)7r   dictr    r   rA   r
   r   r-   
isinstance
ValueErrorshaper(   r)   rB   medianr'   rJ   ndimcallabler   r@   
set_paramsr   type__name__r   r   r   r   r8   r#   n_skips_no_inliers_n_skips_invalid_data_n_skips_invalid_model_arange	n_trials_rE   rF   r   rC   r   rD   r:   rb   r9   minr3   rI   rG   rH   warningswarnr   
estimator_inlier_mask_)&rO   Xyrg   
fit_paramscheck_X_paramscheck_y_paramsrA   r-   rB   loss_functionr@   estimator_fit_has_sample_weightestimator_namerouted_paramsn_inliers_best
score_bestinlier_mask_bestX_inlier_besty_inlier_bestinlier_best_idxs_subsetr,   sample_idxsrE   subset_idxsX_subsety_subsetfit_params_subsetr\   residuals_subsetinlier_mask_subsetn_inliers_subsetinlier_idxs_subsetX_inlier_subsety_inlier_subsetscore_params_inlier_subsetscore_subsetfit_params_best_idxs_subsets&                                         r2   r8   RANSACRegressor.fit=  sp   ` 	*E2EUK.Q^,L
 	 %>>%dnn-I(*I#i)9:: 1  ''!*q.K!!%A%''$"2"2QWWQZ"?@K"**K#.12= 
 ""*!#266!biil2B+C!D!%!8!899((vv{ N! YY/)vv{ M! dii   IIM)$*;*;<	  l ; +<I*W'i11$-L+,  $*7'+D%F:FM!GM&+Bb&IM#( 4] F/>.N''+ffW
"&#$ %&"&'# GGAJ	ii	*__
nnz)NNaN ((,,---. 	
  5;K ~H~H !!-d6H6H(7 7 **a/* !51155{!
 MM(HB0AB "".t7J7J8X8 8 ++q0+ &&q)F,Q7 "25G!G!vv&89  .0((A-( "--?!@ 23O 23O *>1177AS*&
 %?? -L  >1lZ6O .N%J1+M+M&8##"I{<Q<QJ !4!44
doo8Uw nnz)| #((,,---. 	
 !/  !L  ((,,---. 	
 3
 ' ';--11;R'
# 	m]R6QR#,g  		s   "X+ +
X98X9c                     [        U 5        [        U USSSS9n[        X S5        [        5       (       a  [	        U S40 UD6R
                  S   nO0 nU R                  R                  " U40 UD6$ )ap  Predict using the estimated model.

This is a wrapper for `estimator_.predict(X)`.

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

**params : dict
    Parameters routed to the `predict` method of the sub-estimator via
    the metadata routing API.

    .. versionadded:: 1.5

        Only available if
        `sklearn.set_config(enable_metadata_routing=True)` is set. See
        :ref:`Metadata Routing User Guide <metadata_routing>` for more
        details.

Returns
-------
y : array, shape = [n_samples] or [n_samples, n_targets]
    Returns predicted values.
FTrV   rU   resetr:   )r   r    r   r   r   rA   r|   r:   )rO   r~   rh   predict_paramss       r2   r:   RANSACRegressor.predict\  sz    4 	#
 	&	2,T9GGQQN  N&&q;N;;r4   c                     [        U 5        [        U USSSS9n[        X0S5        [        5       (       a  [	        U S40 UD6R
                  S   nO0 nU R                  R                  " X40 UD6$ )a  Return the score of the prediction.

This is a wrapper for `estimator_.score(X, y)`.

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

y : array-like of shape (n_samples,) or (n_samples, n_targets)
    Target values.

**params : dict
    Parameters routed to the `score` method of the sub-estimator via
    the metadata routing API.

    .. versionadded:: 1.5

        Only available if
        `sklearn.set_config(enable_metadata_routing=True)` is set. See
        :ref:`Metadata Routing User Guide <metadata_routing>` for more
        details.

Returns
-------
z : float
    Score of the prediction.
FTr   r9   )r   r    r   r   r   rA   r|   r9   )rO   r~   r   rh   score_paramss        r2   r9   RANSACRegressor.score  su    : 	#
 	&0*4CFCMMgVLL$$Q:\::r4   c                     [        U S9R                  U R                  [        5       R                  SSS9R                  SSS9R                  SSS9R                  SSS9S9nU$ )a"  Get metadata routing of this object.

Please check :ref:`User Guide <metadata_routing>` on how the routing
mechanism works.

.. versionadded:: 1.5

Returns
-------
routing : MetadataRouter
    A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating
    routing information.
)ownerr8   )callercalleer9   r:   )rA   method_mapping)r   addrA   r   )rO   routers     r2   get_metadata_routing$RANSACRegressor.get_metadata_routing  si      d+//nn(?SeS,SgS.SS0S	)S4 0 
 r4   c                    > [         TU ]  5       nU R                  c  SUR                  l        U$ [        U R                  5      R                  R                  UR                  l        U$ )NT)super__sklearn_tags__rA   
input_tagssparser   )rO   tags	__class__s     r2   r    RANSACRegressor.__sklearn_tags__  sU    w')>>!%)DOO"  &.dnn%=%H%H%O%ODOO"r4   )rA   r|   r}   rC   rD   rJ   rF   rE   r-   ru   rv   rt   rx   r@   rB   rG   rI   rH   rN   )rs   
__module____qualname____firstlineno____doc__r   r   r   r   r   rp   r   r(   r#   r   rK   rj   __annotations__rP   r	   r8   r:   r9   r   r   __static_attributes____classcell__)r   s   @r2   r6   r6   Q   s   k\ !!<=tDXq$v6ZAf5

  (afEtL"D)#T*Xq$v6D266(#

 Xq$v6D266(#

 Xq$v6D266(#
  dD@A%dAq@A-?@(K'(3$D <  &&vv66: &+Y	Yv,<\,;\0 r4   r6   )/rz   numbersr   r   numpyr(   sklearn.baser   r   r   r   r	   r
   sklearn.exceptionsr   sklearn.linear_model._baser   sklearn.utilsr   r   r   sklearn.utils._bunchr   sklearn.utils._param_validationr   r   r   r   r   sklearn.utils.metadata_routingr   r   r   r   r   sklearn.utils.randomr   sklearn.utils.validationr   r   r   r   r    spacingr&   r3   r6   re   r4   r2   <module>r      s{     "   2 7 O O &   <  ::a=<DE
	E
r4   