RANSACRegressor#

classsklearn.linear_model.RANSACRegressor(estimator=None,*,min_samples=None,residual_threshold=None,is_data_valid=None,is_model_valid=None,max_trials=100,max_skips=inf,stop_n_inliers=inf,stop_score=inf,stop_probability=0.99,loss='absolute_error',random_state=None)[source]#

RANSAC (RANdom SAmple Consensus) algorithm.

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

Read more in theUser Guide.

Parameters:
estimatorobject, 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 bystop_score.Additionally, the score is used to decide which of two equallylarge 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.

Ifestimator is None, thenLinearRegression is used fortarget values of dtype float.

Note that the current implementation only supports regressionestimators.

min_samplesint (>= 1) or float ([0, 1]), default=None

Minimum number of samples chosen randomly from original data. Treatedas an absolute number of samples formin_samples>=1, treated as arelative numberceil(min_samples*X.shape[0]) formin_samples<1. This is typically chosen as the minimal number ofsamples necessary to estimate the givenestimator. By default aLinearRegression estimator is assumed andmin_samples is chosen asX.shape[1]+1. This parameter is highlydependent upon the model, so if aestimator other thanLinearRegression is used, the user mustprovide a value.

residual_thresholdfloat, default=None

Maximum residual for a data sample to be classified as an inlier.By default the threshold is chosen as the MAD (median absolutedeviation) of the target valuesy. Points whose residuals arestrictly equal to the threshold are considered as inliers.

is_data_validcallable, default=None

This function is called with the randomly selected data before themodel is fitted to it:is_data_valid(X,y). If its return value isFalse the current randomly chosen sub-sample is skipped.

is_model_validcallable, default=None

This function is called with the estimated model and the randomlyselected data:is_model_valid(model,X,y). If its return value isFalse the current randomly chosen sub-sample is skipped.Rejecting samples with this function is computationally costlier thanwithis_data_valid.is_model_valid should therefore only be used ifthe estimated model is needed for making the rejection decision.

max_trialsint, default=100

Maximum number of iterations for random sample selection.

max_skipsint, default=np.inf

Maximum number of iterations that can be skipped due to finding zeroinliers or invalid data defined byis_data_valid or invalid modelsdefined byis_model_valid.

Added in version 0.19.

stop_n_inliersint, default=np.inf

Stop iteration if at least this number of inliers are found.

stop_scorefloat, default=np.inf

Stop iteration if score is greater equal than this threshold.

stop_probabilityfloat in range [0, 1], default=0.99

RANSAC iteration stops if at least one outlier-free set of the trainingdata is sampled in RANSAC. This requires to generate at least Nsamples (iterations):

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

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

lossstr, callable, default=’absolute_error’

String inputs, ‘absolute_error’ and ‘squared_error’ are supported whichfind the absolute error and squared error per sample respectively.

Ifloss is a callable, then it should be a function that takestwo arrays as inputs, the true and predicted value and returns a 1-Darray with the i-th value of the array corresponding to the lossonX[i].

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

Added in version 0.18.

random_stateint, RandomState instance, default=None

The generator used to initialize the centers.Pass an int for reproducible output across multiple function calls.SeeGlossary.

Attributes:
estimator_object

Final model fitted on the inliers predicted by the “best” model foundduring RANSAC sampling (copy of theestimator object).

n_trials_int

Number of random selection trials until one of the stop criteria ismet. It is always<=max_trials.

inlier_mask_bool array of shape [n_samples]

Boolean mask of inliers classified asTrue.

n_skips_no_inliers_int

Number of iterations skipped due to finding zero inliers.

Added in version 0.19.

n_skips_invalid_data_int

Number of iterations skipped due to invalid data defined byis_data_valid.

Added in version 0.19.

n_skips_invalid_model_int

Number of iterations skipped due to an invalid model defined byis_model_valid.

Added in version 0.19.

n_features_in_int

Number of features seen duringfit.

Added in version 0.24.

feature_names_in_ndarray of shape (n_features_in_,)

Names of features seen duringfit. Defined only whenXhas feature names that are all strings.

Added in version 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

Examples

>>>fromsklearn.linear_modelimportRANSACRegressor>>>fromsklearn.datasetsimportmake_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, seeRobust linear model estimation using RANSAC

fit(X,y,sample_weight=None,**fit_params)[source]#

Fit estimator using RANSAC algorithm.

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

Training data.

yarray-like of shape (n_samples,) or (n_samples, n_targets)

Target values.

sample_weightarray-like of shape (n_samples,), default=None

Individual weights for each sampleraises error if sample_weight is passed and estimatorfit method does not support it.

Added in version 0.18.

**fit_paramsdict

Parameters routed to thefit method of the sub-estimator via themetadata routing API.

Added in version 1.5:Only available ifsklearn.set_config(enable_metadata_routing=True) is set. SeeMetadata Routing User Guide for moredetails.

Returns:
selfobject

FittedRANSACRegressor estimator.

Raises:
ValueError

If no valid consensus set could be found. This occurs ifis_data_valid andis_model_valid return False for allmax_trials randomly chosen sub-samples.

get_metadata_routing()[source]#

Get metadata routing of this object.

Please checkUser Guide on how the routingmechanism works.

Added in version 1.5.

Returns:
routingMetadataRouter

AMetadataRouter encapsulatingrouting information.

get_params(deep=True)[source]#

Get parameters for this estimator.

Parameters:
deepbool, default=True

If True, will return the parameters for this estimator andcontained subobjects that are estimators.

Returns:
paramsdict

Parameter names mapped to their values.

predict(X,**params)[source]#

Predict using the estimated model.

This is a wrapper forestimator_.predict(X).

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

Input data.

**paramsdict

Parameters routed to thepredict method of the sub-estimator viathe metadata routing API.

Added in version 1.5:Only available ifsklearn.set_config(enable_metadata_routing=True) is set. SeeMetadata Routing User Guide for moredetails.

Returns:
yarray, shape = [n_samples] or [n_samples, n_targets]

Returns predicted values.

score(X,y,**params)[source]#

Return the score of the prediction.

This is a wrapper forestimator_.score(X,y).

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

Training data.

yarray-like of shape (n_samples,) or (n_samples, n_targets)

Target values.

**paramsdict

Parameters routed to thescore method of the sub-estimator viathe metadata routing API.

Added in version 1.5:Only available ifsklearn.set_config(enable_metadata_routing=True) is set. SeeMetadata Routing User Guide for moredetails.

Returns:
zfloat

Score of the prediction.

set_fit_request(*,sample_weight:bool|None|str='$UNCHANGED$')RANSACRegressor[source]#

Configure whether metadata should be requested to be passed to thefit method.

Note that this method is only relevant when this estimator is used as asub-estimator within ameta-estimator and metadata routing is enabledwithenable_metadata_routing=True (seesklearn.set_config).Please check theUser Guide on how the routingmechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed tofit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it tofit.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains theexisting request. This allows you to change the request for someparameters and not others.

Added in version 1.3.

Parameters:
sample_weightstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing forsample_weight parameter infit.

Returns:
selfobject

The updated object.

set_params(**params)[source]#

Set the parameters of this estimator.

The method works on simple estimators as well as on nested objects(such asPipeline). The latter haveparameters of the form<component>__<parameter> so that it’spossible to update each component of a nested object.

Parameters:
**paramsdict

Estimator parameters.

Returns:
selfestimator instance

Estimator instance.

Gallery examples#

Robust linear model estimation using RANSAC

Robust linear model estimation using RANSAC

Robust linear estimator fitting

Robust linear estimator fitting

Theil-Sen Regression

Theil-Sen Regression