The k-nearest neighbors for classification.

The k-nearest neighbor classification algorithm is an approach to predict the output class of a new input point by selecting the majority class among the k nearest neighbors in a training set through voting. The algorithm may also predict the probabilities of belonging to each class by counting the number of occurrences of the class withing the k nearest neighbors.

Let $$(x_i)_{i=1,\cdots,n_{\text{samples}}}\in \mathbb{R}^{n_{\text{samples}}\times n_{\text{inputs}}}$$ and $$(y_i)_{i=1,\cdots,n_{\text{samples}}}\in \{1,\cdots,n_{\text{classes}}\}^{n_{\text{samples}}}$$ denote the input and output training data respectively.

The procedure for predicting the class of a new input point $$x\in \mathbb{R}^{n_{\text{inputs}}}$$ is the following:

Let $$i_1(x), \cdots, i_{n_{\text{samples}}}(x)$$ be the indices of the input training points sorted by distance to the prediction point $$x$$, i.e.

$\|x-x_{i_1(x)}\| \leq \cdots \leq \|x-x_{i_{n_{\text{samples}}}(x)}\|.$

The ordered indices may be formally determined through the inductive formula

$i_p(x) = \underset{i\in I_p(x)}{\operatorname{argmin}}\|x-x_i\|,\quad p=1,\cdots,n_{\text{samples}}$

where

$\begin{split}I_1(x) = \{1,\cdots,n_{\text{samples}}\}\\ I_{p+1} = I_p(x)\setminus \{i_p(x)\},\quad p=1,\cdots,n_{\text{samples}}-1,\end{split}$

that is

$I_p(x) = \{1,\cdots,n_{\text{samples}}\}\setminus \{i_1(x),\cdots,i_{p-1}(x)\}.$

Then, by denoting $$\operatorname{mode}(\cdot)$$ the mode operator, i.e. the operator that extracts the element with the highest occurrence, we may define the prediction operator as the mode of the set of output classes associated to the $$k$$ first indices (classes of the $$k$$-nearest neighbors of $$x$$):

$f(x) = \operatorname{mode}(y_{i_1(x)}, \cdots, y_{i_k(x)})$

This concept is implemented through the KNNClassifier class which inherits from the MLClassificationAlgo class.

# Dependence¶

The classifier relies on the KNeighborsClassifier class of the scikit-learn library.

Classes:

 KNNClassifier(data[, transformer, ...]) The k-nearest neighbors classification algorithm.
class gemseo.mlearning.classification.knn.KNNClassifier(data, transformer=None, input_names=None, output_names=None, n_neighbors=5, **parameters)[source]

The k-nearest neighbors classification algorithm.

learning_set

The learning dataset.

Type

Dataset

parameters

The parameters of the machine learning algorithm.

Type

Dict[str,MLAlgoParameterType]

transformer

The strategies to transform the variables. The values are instances of Transformer while the keys are the names of either the variables or the groups of variables, e.g. “inputs” or “outputs” in the case of the regression algorithms. If a group is specified, the Transformer will be applied to all the variables of this group. If None, do not transform the variables.

Type

Dict[str,Transformer]

algo

The interfaced machine learning algorithm.

Type

Any

input_names

The names of the input variables.

Type

List[str]

output_names

The names of the output variables.

Type

List[str]

input_space_center

The center of the input space.

Type

Dict[str,ndarray]

n_classes

The number of classes.

Type

int

Initialize self. See help(type(self)) for accurate signature.

Parameters
• data (Dataset) – The learning dataset.

• transformer (Optional[TransformerType]) –

The strategies to transform the variables. The values are instances of Transformer while the keys are the names of either the variables or the groups of variables, e.g. “inputs” or “outputs” in the case of the regression algorithms. If a group is specified, the Transformer will be applied to all the variables of this group. If None, do not transform the variables.

By default it is set to None.

• input_names (Optional[Iterable[str]]) –

The names of the input variables. If None, consider all input variables mentioned in the learning dataset.

By default it is set to None.

• output_names (Optional[Iterable[str]]) –

The names of the output variables. If None, consider all input variables mentioned in the learning dataset.

By default it is set to None.

• n_neighbors (int) –

The number of neighbors.

By default it is set to 5.

• **parameters (Union[int,str]) – The parameters of the machine learning algorithm.

Return type

None

Classes:

 Decorators for supervised algorithms.

Attributes:

 input_data The input data matrix. input_shape The dimension of the input variables before applying the transformers. is_trained Return whether the algorithm is trained. learning_samples_indices The indices of the learning samples used for the training. output_data The output data matrix. output_shape The dimension of the output variables before applying the transformers.

Methods:

 learn([samples]) Train the machine learning algorithm from the learning dataset. load_algo(directory) Load a machine learning algorithm from a directory. predict(input_data, *args, **kwargs) Evaluate 'predict' with either array or dictionary-based input data. predict_proba(input_data, *args, **kwargs) Evaluate 'predict' with either array or dictionary-based input data. save([directory, path, save_learning_set]) Save the machine learning algorithm.
class DataFormatters

Decorators for supervised algorithms.

Methods:

 format_dict(predict) Make an array-based function be called with a dictionary of NumPy arrays. format_input_output(predict) Make a function robust to type, array shape and data transformation. format_samples(predict) Make a 2D NumPy array-based function work with 1D NumPy array. format_transform([transform_inputs, ...]) Force a function to transform its input and/or output variables.
classmethod format_dict(predict)

Make an array-based function be called with a dictionary of NumPy arrays.

Parameters

predict (Callable[[numpy.ndarray], numpy.ndarray]) – The function to be called; it takes a NumPy array in input and returns a NumPy array.

Returns

A function making the function ‘predict’ work with either a NumPy data array or a dictionary of NumPy data arrays indexed by variables names. The evaluation will have the same type as the input data.

Return type

Callable[[Union[numpy.ndarray, Mapping[str, numpy.ndarray]]], Union[numpy.ndarray, Mapping[str, numpy.ndarray]]]

classmethod format_input_output(predict)

Make a function robust to type, array shape and data transformation.

Parameters

predict (Callable[[numpy.ndarray], numpy.ndarray]) – The function of interest to be called.

Returns

A function calling the function of interest ‘predict’, while guaranteeing consistency in terms of data type and array shape, and applying input and/or output data transformation if required.

Return type

Callable[[Union[numpy.ndarray, Mapping[str, numpy.ndarray]]], Union[numpy.ndarray, Mapping[str, numpy.ndarray]]]

classmethod format_samples(predict)

Make a 2D NumPy array-based function work with 1D NumPy array.

Parameters

predict (Callable[[numpy.ndarray], numpy.ndarray]) – The function to be called; it takes a 2D NumPy array in input and returns a 2D NumPy array. The first dimension represents the samples while the second one represents the components of the variables.

Returns

A function making the function ‘predict’ work with either a 1D NumPy array or a 2D NumPy array. The evaluation will have the same dimension as the input data.

Return type

Callable[[numpy.ndarray], numpy.ndarray]

classmethod format_transform(transform_inputs=True, transform_outputs=True)

Force a function to transform its input and/or output variables.

Parameters
• transform_inputs (bool) –

Whether to transform the input variables.

By default it is set to True.

• transform_outputs (bool) –

Whether to transform the output variables.

By default it is set to True.

Returns

A function evaluating a function of interest, after transforming its input data and/or before transforming its output data.

Return type

Callable[[numpy.ndarray], numpy.ndarray]

property input_data

The input data matrix.

property input_shape

The dimension of the input variables before applying the transformers.

property is_trained

Return whether the algorithm is trained.

learn(samples=None)

Train the machine learning algorithm from the learning dataset.

Parameters

samples (Optional[Sequence[int]]) –

The indices of the learning samples. If None, use the whole learning dataset.

By default it is set to None.

Return type

None

property learning_samples_indices

The indices of the learning samples used for the training.

Load a machine learning algorithm from a directory.

Parameters

directory (Union[str, pathlib.Path]) – The path to the directory where the machine learning algorithm is saved.

Return type

None

property output_data

The output data matrix.

property output_shape

The dimension of the output variables before applying the transformers.

predict(input_data, *args, **kwargs)

Evaluate ‘predict’ with either array or dictionary-based input data.

Firstly, the pre-processing stage converts the input data to a NumPy data array, if these data are expressed as a dictionary of NumPy data arrays.

Then, the processing evaluates the function ‘predict’ from this NumPy input data array.

Lastly, the post-processing transforms the output data to a dictionary of output NumPy data array if the input data were passed as a dictionary of NumPy data arrays.

Parameters
• input_data (Union[numpy.ndarray, Mapping[str, numpy.ndarray]]) – The input data.

• *args – The positional arguments of the function ‘predict’.

• **kwargs – The keyword arguments of the function ‘predict’.

Returns

The output data with the same type as the input one.

Return type

Union[numpy.ndarray, Mapping[str, numpy.ndarray]]

predict_proba(input_data, *args, **kwargs)

Evaluate ‘predict’ with either array or dictionary-based input data.

Firstly, the pre-processing stage converts the input data to a NumPy data array, if these data are expressed as a dictionary of NumPy data arrays.

Then, the processing evaluates the function ‘predict’ from this NumPy input data array.

Lastly, the post-processing transforms the output data to a dictionary of output NumPy data array if the input data were passed as a dictionary of NumPy data arrays.

Parameters
• input_data (Union[numpy.ndarray, Mapping[str, numpy.ndarray]]) – The input data.

• *args – The positional arguments of the function ‘predict’.

• **kwargs – The keyword arguments of the function ‘predict’.

Returns

The output data with the same type as the input one.

Return type

Union[numpy.ndarray, Mapping[str, numpy.ndarray]]

save(directory=None, path='.', save_learning_set=False)

Save the machine learning algorithm.

Parameters
• directory (Optional[str]) –

The name of the directory to save the algorithm.

By default it is set to None.

• path (Union[str, pathlib.Path]) –

The path to parent directory where to create the directory.

By default it is set to ..

• save_learning_set (bool) –

Whether to save the learning set or get rid of it to lighten the saved files.

By default it is set to False.

Returns

The path to the directory where the algorithm is saved.

Return type

str