skmultiflow.lazy.SAMKNNClassifier

class skmultiflow.lazy.SAMKNNClassifier(n_neighbors=5, weighting='distance', max_window_size=5000, ltm_size=0.4, min_stm_size=50, stm_size_option='maxACCApprox', use_ltm=True)[source]

Self Adjusting Memory coupled with the kNN classifier.

Parameters
n_neighborsint, optional (default=5)

number of evaluated nearest neighbors.

weighting: string, optional (default=’distance’)

Type of weighting of the nearest neighbors. It must be either ‘distance’ or ‘uniform’ (majority voting).

max_window_sizeint, optional (default=5000)

Maximum number of overall stored data points.

ltm_size: float, optional (default=0.4)

Proportion of the overall instances that may be used for the LTM. This is only relevant when the maximum number(maxSize) of stored instances is reached.

stm_size_optionstring, optional (default=’maxACCApprox’)

Type of STM size adaption. ‘maxACC’ calculates the Interleaved test-train error exactly for each of the evaluated window sizes, which means it has often to be recalculated from the scratch. ‘maxACCApprox’ approximates the Interleaved test-train error and is significantly faster than the exact version. If set to None, the STM is not adapted at all. When additionally use_ltm=false, this algorithm is simply a kNN with fixed sliding window size.

min_stm_sizeint, optional (default=50)

Minimum STM size which is evaluated during the STM size adaption.

use_ltmboolean, optional (default=True)

Specifies whether the LTM should be used at all.

Notes

The Self Adjusting Memory (SAM) [1] model builds an ensemble with models targeting current or former concepts. SAM is built using two memories: STM for the current concept, and the LTM to retain information about past concepts. A cleaning process is in charge of controlling the size of the STM while keeping the information in the LTM consistent with the STM.

This modules uses the libNearestNeighbor, a C++ library used to speed up some of the algorithm’s computations. When invoking the library’s functions it’s important to pass the right argument type. Although most of this framework’s functionality will work with python standard types, the C++ library will work with 8-bit labels, which is already done by the SAMKNN class, but may be absent in custom classes that use SAMKNN static methods, or other custom functions that use the C++ library.

References

1

Losing, Viktor, Barbara Hammer, and Heiko Wersing. “Knn classifier with self adjusting memory for heterogeneous concept drift.” In Data Mining (ICDM), 2016 IEEE 16th International Conference on, pp. 291-300. IEEE, 2016.

Examples

>>> from skmultiflow.lazy import SAMKNNClassifier
>>> from skmultiflow.data import FileStream
>>> from skmultiflow.evaluation import EvaluatePrequential
>>> # Setup the File Stream
>>> stream = FileStream("https://raw.githubusercontent.com/scikit-multiflow/"
...                     "streaming-datasets/master/moving_squares.csv")
>>> # Setup the classifier
>>> classifier = SAMKNNClassifier(n_neighbors=5, weighting='distance', max_window_size=1000,
>>>                               stm_size_option='maxACCApprox', use_ltm=False)
>>> # Setup the evaluator
>>> evaluator = EvaluatePrequential(pretrain_size=0, max_samples=100000, batch_size=1,
...                                 n_wait=100, max_time=1000, output_file=None,
...                                 show_plot=True, metrics=['accuracy', 'kappa_t'])
>>> # Evaluate
>>> evaluator.evaluate(stream=stream, model=classifier)

Methods

clean_samples(self, samplesCl, labelsCl[, …])

Removes distance-based all instances from the input samples that contradict those in the STM.

cluster_down(self, samples, labels)

Performs classwise kMeans++ clustering for given samples with corresponding labels.

fit(self, X, y[, classes, sample_weight])

Fit the model.

get_complexity(self)

get_complexity_num_parameter_metric(self)

get_distance_weighted_label(distances, …)

Returns the the distance weighted label of the k nearest neighbors.

get_distances(sample, samples)

Calculate distances from sample to all samples.

get_info(self)

Collects and returns the information about the configuration of the estimator

get_maj_label(distances, labels, numNeighbours)

Returns the majority label of the k nearest neighbors.

get_params(self[, deep])

Get parameters for this estimator.

partial_fit(self, X, y[, classes, sample_weight])

Partially (incrementally) fit the model.

predict(self, X)

Predict classes for the passed data.

predict_proba(self, X)

Estimates the probability of each sample in X belonging to each of the class-labels.

reset(self)

Resets the estimator to its initial state.

score(self, X, y[, sample_weight])

Returns the mean accuracy on the given test data and labels.

set_params(self, **params)

Set the parameters of this estimator.

size_check_STMLTM(self)

Makes sure that the STM and LTM combined doe not surpass the maximum size, only used when use_ltm=True.

size_check_fade_out(self)

Makes sure that the STM does not surpass the maximum size, only used when use_ltm=False.

Attributes

LTMLabels

LTMSamples

STMLabels

STMSamples

clean_samples(self, samplesCl, labelsCl, onlyLast=False)[source]

Removes distance-based all instances from the input samples that contradict those in the STM.

cluster_down(self, samples, labels)[source]

Performs classwise kMeans++ clustering for given samples with corresponding labels. The number of samples is halved per class.

fit(self, X, y, classes=None, sample_weight=None)[source]

Fit the model.

Parameters
Xnumpy.ndarray of shape (n_samples, n_features)

The features to train the model.

y: numpy.ndarray of shape (n_samples, n_targets)

An array-like with the class labels of all samples in X.

classes: numpy.ndarray, optional (default=None)

Contains all possible/known class labels. Usage varies depending on the learning method.

sample_weight: numpy.ndarray, optional (default=None)

Samples weight. If not provided, uniform weights are assumed. Usage varies depending on the learning method.

Returns
self
static get_distance_weighted_label(distances, labels, numNeighbours)[source]

Returns the the distance weighted label of the k nearest neighbors.

static get_distances(sample, samples)[source]

Calculate distances from sample to all samples.

get_info(self)[source]

Collects and returns the information about the configuration of the estimator

Returns
string

Configuration of the estimator.

static get_maj_label(distances, labels, numNeighbours)[source]

Returns the majority label of the k nearest neighbors.

get_params(self, deep=True)[source]

Get parameters for this estimator.

Parameters
deepboolean, optional

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

Returns
paramsmapping of string to any

Parameter names mapped to their values.

partial_fit(self, X, y, classes=None, sample_weight=None)[source]

Partially (incrementally) fit the model.

Parameters
Xnumpy.ndarray of shape (n_samples, n_features)

The features to train the model.

y: numpy.ndarray of shape (n_samples)

An array-like with the labels of all samples in X.

classes: numpy.ndarray, optional (default=None)

Array with all possible/known classes. Usage varies depending on the learning method.

sample_weight: numpy.ndarray of shape (n_samples), optional (default=None)

Samples weight. If not provided, uniform weights are assumed. Usage varies depending on the learning method.

Returns
self
predict(self, X)[source]

Predict classes for the passed data.

Parameters
Xnumpy.ndarray of shape (n_samples, n_features)

The set of data samples to predict the class labels for.

Returns
A numpy.ndarray with all the predictions for the samples in X.
predict_proba(self, X)[source]

Estimates the probability of each sample in X belonging to each of the class-labels.

Parameters
Xnumpy.ndarray of shape (n_samples, n_features)

The matrix of samples one wants to predict the class probabilities for.

Returns
A numpy.ndarray of shape (n_samples, n_labels), in which each outer entry is associated
with the X entry of the same index. And where the list in index [i] contains
len(self.target_values) elements, each of which represents the probability that
the i-th sample of X belongs to a certain class-label.
reset(self)[source]

Resets the estimator to its initial state.

Returns
self
score(self, X, y, sample_weight=None)[source]

Returns the mean accuracy on the given test data and labels.

In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted.

Parameters
Xarray-like, shape = (n_samples, n_features)

Test samples.

yarray-like, shape = (n_samples) or (n_samples, n_outputs)

True labels for X.

sample_weightarray-like, shape = [n_samples], optional

Sample weights.

Returns
scorefloat

Mean accuracy of self.predict(X) wrt. y.

set_params(self, **params)[source]

Set the parameters of this estimator.

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

Returns
self
size_check_STMLTM(self)[source]

Makes sure that the STM and LTM combined doe not surpass the maximum size, only used when use_ltm=True.

size_check_fade_out(self)[source]

Makes sure that the STM does not surpass the maximum size, only used when use_ltm=False.