U
    _»{jªU  ã                   @   sÐ   d dl Z d dlmZmZ d dl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mZmZmZ ddlmZ dd	lmZmZmZ d
dlmZ e  d
¡Z!dd„ Z"G dd„ dee
e	eƒZ#dS )é    N)ÚIntegralÚRealé   )ÚBaseEstimatorÚMetaEstimatorMixinÚMultiOutputMixinÚRegressorMixinÚ_fit_contextÚclone)ÚConvergenceWarning)Úcheck_consistent_lengthÚcheck_random_state)Ú
HasMethodsÚIntervalÚOptionsÚ
RealNotIntÚ
StrOptions)Úsample_without_replacement)Ú_check_sample_weightÚcheck_is_fittedÚhas_fit_parameteré   )ÚLinearRegressionc                 C   sj   | t |ƒ }ttd| ƒ}ttd||  ƒ}|dkr8dS |dkrHt dƒS tt t t |¡t |¡ ¡ƒƒS )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)Z	n_inliersÚ	n_samplesÚmin_samplesZprobabilityZinlier_ratioZnomÚdenom© r$   ú[/var/www/html/bwave/python/venv/lib/python3.8/site-packages/sklearn/linear_model/_ransac.pyÚ_dynamic_max_trials"   s    r&   c                   @   sJ  e Zd ZU dZedddgƒdgeedddd�eed	dd
d�dgeed	ddd�dge	dge	dgeed	ddd�e
eejhƒgeed	ddd�e
eejhƒgeed	ddd�e
eejhƒgeeddd
d�geed	dd
d�geddhƒe	gdgdœZeed< ddddddejejejddddœdd„Zedd�d dd„ƒZdd„ Zdd„ Zdd„ ZdS )!ÚRANSACRegressora  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
        Best fitted model (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] http://www.bmva.org/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...])
    ÚfitÚscoreÚpredictNr   Úleft)Úclosedr   Z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_constraintséd   g®Gáz®ï?)r"   r1   r2   r3   r4   r5   r6   r7   r8   r9   r/   c                C   sL   || _ || _|| _|| _|| _|| _|| _|| _|	| _|
| _	|| _
|| _d S ©N)r0   r"   r1   r2   r3   r4   r5   r6   r7   r8   r/   r9   )Úselfr0   r"   r1   r2   r3   r4   r5   r6   r7   r8   r9   r/   r$   r$   r%   Ú__init__  s    zRANSACRegressor.__init__F)Zprefer_skip_nested_validationc           !      C   s€  t ddd�}t dd�}| j||||fd�\}}t||ƒ | jdk	rNt| jƒ}ntƒ }| jdkr€t|tƒsptdƒ‚|j	d d }nBd	| j  k r–dk r²n nt
 | j|j	d	  ¡}n| jdkrÂ| j}||j	d	 krâtd
|j	d	  ƒ‚| jdk�r
t
 t
 |t
 |¡ ¡¡}n| j}| jdk�r<|jdk�r2dd„ }	ndd„ }	n>| jdk�rh|jdk�r^dd„ }	ndd„ }	nt| jƒ�rz| j}	t| jƒ}
z|j|
d� W n tk
�rª   Y nX t|dƒ}t|ƒj}|dk	�rÜ|�sÜtd| ƒ‚|dk	�rðt||ƒ}d}t
j }d}d}d}d}d	| _d	| _d	| _|j	d	 }t
 |¡}d	| _| j}| j|k �ræ|  jd7  _| j| j | j | j k�rv�qæt!|||
d�}|| }|| }| j"dk	�rÀ|  "||¡�sÀ|  jd7  _�q>|dk�rØ| #||¡ n|j#|||| d� | j$dk	�r|  $|||¡�s|  jd7  _�q>| %|¡}|	||ƒ}||k}t
 &|¡}||k �r\|  jd7  _�q>|| }|| }|| }| '||¡} ||k�r˜| |k �r˜�q>|}| }|}|}|}|}t(|t)|||| j*ƒƒ}|| j+k�sæ|| j,k�r>�qæ�q>|dk�r| j| j | j | j k�rtdƒ‚ntdƒ‚n&| j| j | j | j k�rDt- .dt/¡ |dk�r\| #||¡ n|j#|||| d� || _0|| _1| S )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

        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.
        ZcsrF)Úaccept_sparseÚforce_all_finite)Z	ensure_2d)Z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                 S   s   t  | | ¡S r<   )r   r   ©Zy_trueÚy_predr$   r$   r%   Ú<lambda>s  ó    z%RANSACRegressor.fit.<locals>.<lambda>c                 S   s   t jt  | | ¡dd�S )Nr   ©Zaxis)r   Úsumr   rA   r$   r$   r%   rC   u  s    ÿr.   c                 S   s   | | d S )Nr   r$   rA   r$   r$   r%   rC   z  rD   c                 S   s   t j| | d dd�S )Nr   r   rE   )r   rF   rA   r$   r$   r%   rC   |  s   
 ÿ)r/   Úsample_weightz\%s does not support sample_weight. Samples weights are only used for the calibration itself.)rG   zèRANSAC 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*).zÏRANSAC 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*).zšRANSAC found a valid consensus set but exited early due to skipping more iterations than `max_skips`. See estimator attributes for diagnostics (n_skips*).)2ÚdictÚ_validate_datar   r0   r
   r   r"   Ú
isinstanceÚ
ValueErrorÚshaper   r   r1   Zmedianr   r9   ÚndimÚcallabler   r/   Z
set_paramsr   ÚtypeÚ__name__r   r   Zn_skips_no_inliers_Zn_skips_invalid_data_Zn_skips_invalid_model_ZarangeZ	n_trials_r4   r5   r   r2   r(   r3   r*   rF   r)   Úminr&   r8   r6   r7   ÚwarningsÚwarnr   Ú
estimator_Zinlier_mask_)!r=   ÚXÚyrG   Zcheck_X_paramsZcheck_y_paramsr0   r"   r1   Zloss_functionr/   Zestimator_fit_has_sample_weightZestimator_nameZn_inliers_bestZ
score_bestZinlier_mask_bestZX_inlier_bestZy_inlier_bestZinlier_best_idxs_subsetr!   Zsample_idxsr4   Zsubset_idxsZX_subsetZy_subsetrB   Zresiduals_subsetZinlier_mask_subsetZn_inliers_subsetZinlier_idxs_subsetZX_inlier_subsetZy_inlier_subsetZscore_subsetr$   r$   r%   r(   )  sT   %
  ÿ




ÿ
ÿÿ






þÿ



ÿþü  ÿ ÿ
  ÿ  ÿ



   ÿþ
ÿþüÿÿÿþüù
ýzRANSACRegressor.fitc                 C   s&   t | ƒ | j|dddd�}| j |¡S )au  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.

        Returns
        -------
        y : array, shape = [n_samples] or [n_samples, n_targets]
            Returns predicted values.
        FT©r@   r?   Úreset)r   rI   rT   r*   )r=   rU   r$   r$   r%   r*   ,  s    üzRANSACRegressor.predictc                 C   s(   t | ƒ | j|dddd�}| j ||¡S )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.

        Returns
        -------
        z : float
            Score of the prediction.
        FTrW   )r   rI   rT   r)   )r=   rU   rV   r$   r$   r%   r)   D  s    üzRANSACRegressor.scorec                 C   s   dddiiS )NZ_xfail_checksZcheck_sample_weights_invariancez8zero sample_weight is not equivalent to removing samplesr$   )r=   r$   r$   r%   Ú
_more_tags_  s
    þÿzRANSACRegressor._more_tags)N)N)rP   Ú
__module__Ú__qualname__Ú__doc__r   r   r   r   r   rN   r   r   r   r   r:   rH   Ú__annotations__r>   r	   r(   r*   r)   rY   r$   r$   r$   r%   r'   D   s^   
 +ýþþþç þòþ  r'   )$rR   Únumbersr   r   Únumpyr   Úbaser   r   r   r   r	   r
   Ú
exceptionsr   Úutilsr   r   Zutils._param_validationr   r   r   r   r   Zutils.randomr   Zutils.validationr   r   r   Z_baser   Úspacingr   r&   r'   r$   r$   r$   r%   Ú<module>   s"    
"
   ÿ