module mlmodel.kmeans_l1

Inheritance diagram of mlinsights.mlmodel.kmeans_l1

Short summary

module mlinsights.mlmodel.kmeans_l1

Implements k-means with norms L1 and L2.

source on GitHub

Classes

class

truncated documentation

KMeansL1L2

K-Means clustering with either norm L1 or L2. See notebook KMeans with norm L1 for an example.

Functions

function

truncated documentation

_centers_dense

M step of the K-means EM algorithm. Computation of cluster centers / means.

_init_centroids

Compute the initial centroids

_k_init

Init n_clusters seeds according to k-means++

_kmeans_single_lloyd

A single run of k-means, assumes preparation completed prior.

_labels_inertia

E step of the K-means EM algorithm. Computes the labels and the inertia of the given samples and centers. This …

_tolerance

Return a tolerance which is independent of the dataset

Properties

property

truncated documentation

_repr_html_

HTML representation of estimator. This is redundant with the logic of _repr_mimebundle_. The latter should …

Methods

method

truncated documentation

__init__

_fit_l1

Computes k-means clustering with norm ‘l1’.

_predict_l1

Returns the distance of each point in X to every fit clusters.

_transform_l1

Returns the distance of each point in X to every fit clusters.

fit

Computes k-means clustering.

predict

Predicts the closest cluster each sample in X belongs to. In the vector quantization literature, cluster_centers_

transform

Transforms X to a cluster-distance space. In the new space, each dimension is the distance to the cluster …

Documentation

Implements k-means with norms L1 and L2.

source on GitHub

class mlinsights.mlmodel.kmeans_l1.KMeansL1L2(n_clusters=8, init='k-means++', n_init=10, max_iter=300, tol=0.0001, precompute_distances='auto', verbose=0, random_state=None, copy_x=True, n_jobs=None, algorithm='full', norm='L2')[source]

Bases: sklearn.cluster._kmeans.KMeans

K-Means clustering with either norm L1 or L2. See notebook KMeans with norm L1 for an example.

Parameters
  • n_clusters – int, default=8 The number of clusters to form as well as the number of centroids to generate.

  • init

    {‘k-means++’, ‘random’} or ndarray of shape (n_clusters, n_features), default=’k-means++’ Method for initialization, defaults to ‘k-means++’:

    ’k-means++’ : selects initial cluster centers for k-mean clustering in a smart way to speed up convergence. See section Notes in k_init for more details.

    ’random’: choose k observations (rows) at random from data for the initial centroids.

    If an ndarray is passed, it should be of shape (n_clusters, n_features) and gives the initial centers.

  • n_init – int, default=10 Number of time the k-means algorithm will be run with different centroid seeds. The final results will be the best output of n_init consecutive runs in terms of inertia.

  • max_iter – int, default=300 Maximum number of iterations of the k-means algorithm for a single run.

  • tol – float, default=1e-4 Relative tolerance with regards to inertia to declare convergence.

  • precompute_distances

    ‘auto’ or bool, default=’auto’ Precompute distances (faster but takes more memory).

    ’auto’ : do not precompute distances if n_samples * n_clusters > 12 million. This corresponds to about 100MB overhead per job using double precision.

    True : always precompute distances.

    False : never precompute distances.

  • verbose – int, default=0 Verbosity mode.

  • random_state – int, RandomState instance, default=None Determines random number generation for centroid initialization. Use an int to make the randomness deterministic. See Glossary.

  • copy_x – bool, default=True When pre-computing distances it is more numerically accurate to center the data first. If copy_x is True (default), then the original data is not modified, ensuring X is C-contiguous. If False, the original data is modified, and put back before the function returns, but small numerical differences may be introduced by subtracting and then adding the data mean, in this case it will also not ensure that data is C-contiguous which may cause a significant slowdown.

  • n_jobs

    int, default=None The number of jobs to use for the computation. This works by computing each of the n_init runs in parallel.

    None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.

  • algorithm – {“auto”, “full”, “elkan”}, default=”auto” K-means algorithm to use. The classical EM-style algorithm is “full”. The “elkan” variation is more efficient by using the triangle inequality, but currently doesn’t support sparse data. “auto” chooses “elkan” for dense data and “full” for sparse data.

  • norm – {“L1”, “L2”} The norm L2 is identical to KMeans. Norm L1 uses a complete different path.

Fitted attributes:

  • cluster_centers_: ndarray of shape (n_clusters, n_features)

    Coordinates of cluster centers. If the algorithm stops before fully converging (see tol and max_iter), these will not be consistent with labels_.

  • labels_: ndarray of shape (n_samples,)

    Labels of each point

  • inertia_: float

    Sum of squared distances of samples to their closest cluster center.

  • n_iter_: int

    Number of iterations run.

source on GitHub

__init__(n_clusters=8, init='k-means++', n_init=10, max_iter=300, tol=0.0001, precompute_distances='auto', verbose=0, random_state=None, copy_x=True, n_jobs=None, algorithm='full', norm='L2')[source]

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

_fit_l1(X, y=None, sample_weight=None)[source]

Computes k-means clustering with norm ‘l1’.

Parameters
  • X – array-like or sparse matrix, shape=(n_samples, n_features) Training instances to cluster. It must be noted that the data will be converted to C ordering, which will cause a memory copy if the given data is not C-contiguous.

  • y – Ignored Not used, present here for API consistency by convention.

  • sample_weight – array-like, shape (n_samples,), optional The weights for each observation in X. If None, all observations are assigned equal weight (default: None).

Returns

self Fitted estimator.

source on GitHub

_predict_l1(X, sample_weight=None, return_distances=False)[source]

Returns the distance of each point in X to every fit clusters.

Parameters
  • X – features

  • sample_weight – (unused)

  • return_distances – returns distances as well

Returns

labels or labels, distances

source on GitHub

_transform_l1(X)[source]

Returns the distance of each point in X to every fit clusters.

source on GitHub

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

Computes k-means clustering.

Parameters
  • X – array-like or sparse matrix, shape=(n_samples, n_features) Training instances to cluster. It must be noted that the data will be converted to C ordering, which will cause a memory copy if the given data is not C-contiguous.

  • y – Ignored Not used, present here for API consistency by convention.

  • sample_weight – array-like, shape (n_samples,), optional The weights for each observation in X. If None, all observations are assigned equal weight (default: None).

Returns

self Fitted estimator.

source on GitHub

predict(X, sample_weight=None)[source]

Predicts the closest cluster each sample in X belongs to.

In the vector quantization literature, cluster_centers_ is called the code book and each value returned by predict is the index of the closest code in the code book.

Parameters
  • X – {array-like, sparse matrix} of shape (n_samples, n_features) New data to predict.

  • sample_weight – array-like, shape (n_samples,), optional The weights for each observation in X. If None, all observations are assigned equal weight (default: None), unused here

Returns

labels : array, shape [n_samples,] Index of the cluster each sample belongs to.

source on GitHub

transform(X)[source]

Transforms X to a cluster-distance space.

In the new space, each dimension is the distance to the cluster centers. Note that even if X is sparse, the array returned by transform will typically be dense.

Parameters

X – {array-like, sparse matrix} of shape (n_samples, n_features) New data to transform.

Returns

X_new : array, shape [n_samples, k] X transformed in the new space.

source on GitHub

mlinsights.mlmodel.kmeans_l1._centers_dense(X, sample_weight, labels, n_clusters, distances, X_sort_index)[source]

M step of the K-means EM algorithm. Computation of cluster centers / means.

Parameters
  • X – array-like, shape (n_samples, n_features)

  • sample_weight – array-like, shape (n_samples,) The weights for each observation in X.

  • labels – array of integers, shape (n_samples) Current label assignment

  • n_clusters – int Number of desired clusters

  • distances – array-like, shape (n_samples) Distance to closest cluster for each sample.

  • X_sort_index – array-like, shape (n_samples, n_features) index of each feature in all features

Returns

centers, array, shape (n_clusters, n_features) The resulting centers

source on GitHub

mlinsights.mlmodel.kmeans_l1._init_centroids(norm, X, k, init, random_state=None, init_size=None)[source]

Compute the initial centroids

param norm

‘l1’ or ‘l2’

param X

array, shape (n_samples, n_features)

param k

int number of centroids

param init

{‘k-means++’, ‘random’ or ndarray or callable} optional Method for initialization

param random_state

int, RandomState instance or None (default) Determines random number generation for centroid initialization. Use an int to make the randomness deterministic. See Glossary.

param init_size

int, optional Number of samples to randomly sample for speeding up the initialization (sometimes at the expense of accuracy): the only algorithm is initialized by running a batch KMeans on a random subset of the data. This needs to be larger than k.

return

centers, array, shape(k, n_features)

source on GitHub

mlinsights.mlmodel.kmeans_l1._k_init(norm, X, n_clusters, random_state, n_local_trials=None)[source]

Init n_clusters seeds according to k-means++

param norm

l1 or l2 manhattan or euclidean distance

param X

array or sparse matrix, shape (n_samples, n_features) The data to pick seeds for. To avoid memory copy, the input data should be double precision (dtype=numpy.float64).

param n_clusters

integer The number of seeds to choose

param random_state

int, RandomState instance The generator used to initialize the centers. Use an int to make the randomness deterministic. See Glossary.

param n_local_trials

integer, optional The number of seeding trials for each center (except the first), of which the one reducing inertia the most is greedily chosen. Set to None to make the number of trials depend logarithmically on the number of seeds (2+log(k)); this is the default.

source on GitHub

mlinsights.mlmodel.kmeans_l1._kmeans_single_lloyd(norm, X, sample_weight, n_clusters, max_iter=300, init='k-means++', verbose=False, random_state=None, tol=0.0001, precompute_distances=True)[source]

A single run of k-means, assumes preparation completed prior.

Parameters
  • norm – ‘l1’ or ‘l2’

  • X – array-like of floats, shape (n_samples, n_features) The observations to cluster.

  • n_clusters – int The number of clusters to form as well as the number of centroids to generate.

  • sample_weight – array-like, shape (n_samples,) The weights for each observation in X.

  • max_iter – int, optional, default 300 Maximum number of iterations of the k-means algorithm to run.

  • init

    {‘k-means++’, ‘random’, or ndarray, or a callable}, optional Method for initialization, default to ‘k-means++’:

    ’k-means++’ : selects initial cluster centers for k-mean clustering in a smart way to speed up convergence. See section Notes in k_init for more details.

    ’random’: choose k observations (rows) at random from data for the initial centroids.

    If an ndarray is passed, it should be of shape (k, p) and gives the initial centers.

    If a callable is passed, it should take arguments X, k and and a random state and return an initialization.

  • tol – float, optional The relative increment in the results before declaring convergence.

  • verbose – boolean, optional Verbosity mode

  • precompute_distances – boolean, default: True Precompute distances (faster but takes more memory).

  • random_state – int, RandomState instance or None (default) Determines random number generation for centroid initialization. Use an int to make the randomness deterministic. See Glossary.

Returns

centroid : float ndarray with shape (k, n_features) Centroids found at the last iteration of k-means.

Returns

label : integer ndarray with shape (n_samples,) label[i] is the code or index of the centroid the i’th observation is closest to.

Returns

inertia : float The final value of the inertia criterion (sum of squared distances to the closest centroid for all observations in the training set).

Returns

n_iter : int Number of iterations run.

source on GitHub

mlinsights.mlmodel.kmeans_l1._labels_inertia(norm, X, sample_weight, centers, precompute_distances=True, distances=None)[source]

E step of the K-means EM algorithm.

Computes the labels and the inertia of the given samples and centers. This will compute the distances in-place.

Parameters
  • norm – ‘l1’ or ‘l2’

  • X – float64 array-like or CSR sparse matrix, shape (n_samples, n_features) The input samples to assign to the labels.

  • sample_weight – array-like, shape (n_samples,) The weights for each observation in X.

  • centers – float array, shape (k, n_features) The cluster centers.

  • precompute_distances – boolean, default: True Precompute distances (faster but takes more memory).

  • distances – existing distances

Returns

labels : int array of shape(n) The resulting assignment

Returns

inertia : float Sum of squared distances of samples to their closest cluster center.

source on GitHub

mlinsights.mlmodel.kmeans_l1._tolerance(norm, X, tol)[source]

Return a tolerance which is independent of the dataset

source on GitHub