KNNImputer#

classsklearn.impute.KNNImputer(*,missing_values=nan,n_neighbors=5,weights='uniform',metric='nan_euclidean',copy=True,add_indicator=False,keep_empty_features=False)[source]#

Imputation for completing missing values using k-Nearest Neighbors.

Each sample’s missing values are imputed using the mean value fromn_neighbors nearest neighbors found in the training set. Two samples areclose if the features that neither is missing are close.

Read more in theUser Guide.

Added in version 0.22.

Parameters:
missing_valuesint, float, str, np.nan or None, default=np.nan

The placeholder for the missing values. All occurrences ofmissing_values will be imputed. For pandas’ dataframes withnullable integer dtypes with missing values,missing_valuesshould be set to np.nan, sincepd.NA will be converted to np.nan.

n_neighborsint, default=5

Number of neighboring samples to use for imputation.

weights{‘uniform’, ‘distance’} or callable, default=’uniform’

Weight function used in prediction. Possible values:

  • ‘uniform’ : uniform weights. All points in each neighborhood areweighted equally.

  • ‘distance’ : weight points by the inverse of their distance.in this case, closer neighbors of a query point will have agreater influence than neighbors which are further away.

  • callable : a user-defined function which accepts anarray of distances, and returns an array of the same shapecontaining the weights.

metric{‘nan_euclidean’} or callable, default=’nan_euclidean’

Distance metric for searching neighbors. Possible values:

  • ‘nan_euclidean’

  • callable : a user-defined function which conforms to the definitionoffunc_metric(x,y,*,missing_values=np.nan).x andycorresponds to a row (i.e. 1-D arrays) ofX andY, respectively.The callable should returns a scalar distance value.

copybool, default=True

If True, a copy of X will be created. If False, imputation willbe done in-place whenever possible.

add_indicatorbool, default=False

If True, aMissingIndicator transform will stack onto theoutput of the imputer’s transform. This allows a predictive estimatorto account for missingness despite imputation. If a feature has nomissing values at fit/train time, the feature won’t appear on themissing indicator even if there are missing values at transform/testtime.

keep_empty_featuresbool, default=False

If True, features that consist exclusively of missing values whenfit is called are returned in results whentransform is called.The imputed value is always0.

Added in version 1.2.

Attributes:
indicator_MissingIndicator

Indicator used to add binary indicators for missing values.None if add_indicator is False.

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

SimpleImputer

Univariate imputer for completing missing values with simple strategies.

IterativeImputer

Multivariate imputer that estimates values to impute for each feature with missing values from all the others.

References

Examples

>>>importnumpyasnp>>>fromsklearn.imputeimportKNNImputer>>>X=[[1,2,np.nan],[3,4,3],[np.nan,6,5],[8,8,7]]>>>imputer=KNNImputer(n_neighbors=2)>>>imputer.fit_transform(X)array([[1. , 2. , 4. ],       [3. , 4. , 3. ],       [5.5, 6. , 5. ],       [8. , 8. , 7. ]])

For a more detailed example seeImputing missing values before building an estimator.

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

Fit the imputer on X.

Parameters:
Xarray-like shape of (n_samples, n_features)

Input data, wheren_samples is the number of samples andn_features is the number of features.

yIgnored

Not used, present here for API consistency by convention.

Returns:
selfobject

The fittedKNNImputer class instance.

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

Fit to data, then transform it.

Fits transformer toX andy with optional parametersfit_paramsand returns a transformed version ofX.

Parameters:
Xarray-like of shape (n_samples, n_features)

Input samples.

yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None

Target values (None for unsupervised transformations).

**fit_paramsdict

Additional fit parameters.

Returns:
X_newndarray array of shape (n_samples, n_features_new)

Transformed array.

get_feature_names_out(input_features=None)[source]#

Get output feature names for transformation.

Parameters:
input_featuresarray-like of str or None, default=None

Input features.

  • Ifinput_features isNone, thenfeature_names_in_ isused as feature names in. Iffeature_names_in_ is not defined,then the following input feature names are generated:["x0","x1",...,"x(n_features_in_-1)"].

  • Ifinput_features is an array-like, theninput_features mustmatchfeature_names_in_ iffeature_names_in_ is defined.

Returns:
feature_names_outndarray of str objects

Transformed feature names.

get_metadata_routing()[source]#

Get metadata routing of this object.

Please checkUser Guide on how the routingmechanism works.

Returns:
routingMetadataRequest

AMetadataRequest 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.

set_output(*,transform=None)[source]#

Set output container.

SeeIntroducing the set_output APIfor an example on how to use the API.

Parameters:
transform{“default”, “pandas”, “polars”}, default=None

Configure output oftransform andfit_transform.

  • "default": Default output format of a transformer

  • "pandas": DataFrame output

  • "polars": Polars output

  • None: Transform configuration is unchanged

Added in version 1.4:"polars" option was added.

Returns:
selfestimator instance

Estimator instance.

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.

transform(X)[source]#

Impute all missing values in X.

Parameters:
Xarray-like of shape (n_samples, n_features)

The input data to complete.

Returns:
Xarray-like of shape (n_samples, n_output_features)

The imputed dataset.n_output_features is the number of featuresthat is not always missing duringfit.

Gallery examples#

Imputing missing values before building an estimator

Imputing missing values before building an estimator

Release Highlights for scikit-learn 0.22

Release Highlights for scikit-learn 0.22