Table of Contents

Class KNNImputer<T>

Namespace
AiDotNet.Preprocessing.Imputers
Assembly
AiDotNet.dll

Imputes missing values using K-Nearest Neighbors.

public class KNNImputer<T> : TransformerBase<T, Matrix<T>, Matrix<T>>, IDataTransformer<T, Matrix<T>, Matrix<T>>

Type Parameters

T

The numeric type for calculations (e.g., float, double).

Inheritance
TransformerBase<T, Matrix<T>, Matrix<T>>
KNNImputer<T>
Implements
IDataTransformer<T, Matrix<T>, Matrix<T>>
Inherited Members

Remarks

KNNImputer replaces missing values with the mean (or weighted mean) of the K nearest neighbors found in the training set. Each sample's missing values are imputed using the values from the K most similar samples that have non-missing values for that feature.

For Beginners: This imputer fills in missing values by looking at similar data points: - Finds the K most similar rows that have the value you need - Uses their average to fill in the missing value - "Similar" is measured using Euclidean distance on non-missing features

Example: If you're missing someone's income, KNN finds K similar people (same age, education, etc.) and uses their average income.

Constructors

KNNImputer(int, KNNWeights, double, int[]?)

Creates a new instance of KNNImputer<T>.

public KNNImputer(int nNeighbors = 5, KNNWeights weights = KNNWeights.Uniform, double missingValue = NaN, int[]? columnIndices = null)

Parameters

nNeighbors int

Number of neighbors to use. Defaults to 5.

weights KNNWeights

Weight function used in prediction. Defaults to Uniform.

missingValue double

The value to treat as missing. Defaults to NaN.

columnIndices int[]

The column indices to impute, or null for all columns.

Properties

NNeighbors

Gets the number of neighbors to use for imputation.

public int NNeighbors { get; }

Property Value

int

SupportsInverseTransform

Gets whether this transformer supports inverse transformation.

public override bool SupportsInverseTransform { get; }

Property Value

bool

Weights

Gets the weighting scheme used for neighbors.

public KNNWeights Weights { get; }

Property Value

KNNWeights

Methods

FitCore(Matrix<T>)

Stores the training data for neighbor lookup.

protected override void FitCore(Matrix<T> data)

Parameters

data Matrix<T>

The training data matrix.

GetFeatureNamesOut(string[]?)

Gets the output feature names after transformation.

public override string[] GetFeatureNamesOut(string[]? inputFeatureNames = null)

Parameters

inputFeatureNames string[]

Returns

string[]

InverseTransformCore(Matrix<T>)

Inverse transformation is not supported for KNN imputation.

protected override Matrix<T> InverseTransformCore(Matrix<T> data)

Parameters

data Matrix<T>

Returns

Matrix<T>

TransformCore(Matrix<T>)

Imputes missing values using K-nearest neighbors.

protected override Matrix<T> TransformCore(Matrix<T> data)

Parameters

data Matrix<T>

The data to impute.

Returns

Matrix<T>

The data with missing values imputed.