module mlmodel.kmeans_l1
¶
Classes¶
class 
truncated documentation 

KMeans clustering with either norm L1 or L2. See notebook KMeans with norm L1 for an example. 
Functions¶
function 
truncated documentation 

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

Compute the initial centroids 

Init n_clusters seeds according to kmeans++ 

A single run of kmeans, assumes preparation completed prior. 

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

Return a tolerance which is independent of the dataset 
Properties¶
property 
truncated documentation 


HTML representation of estimator. This is redundant with the logic of _repr_mimebundle_. The latter should … 
Methods¶
method 
truncated documentation 

Computes kmeans clustering with norm ‘l1’. 

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

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

Computes kmeans clustering. 

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

Transforms X to a clusterdistance space. In the new space, each dimension is the distance to the cluster … 
Documentation¶
Implements kmeans with norms L1 and L2.

class
mlinsights.mlmodel.kmeans_l1.
KMeansL1L2
(n_clusters=8, init='kmeans++', 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
KMeans 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 –
{‘kmeans++’, ‘random’} or ndarray of shape (n_clusters, n_features), default=’kmeans++’ Method for initialization, defaults to ‘kmeans++’:
’kmeans++’ : selects initial cluster centers for kmean 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 kmeans 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 kmeans algorithm for a single run.
tol – float, default=1e4 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 precomputing 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 Ccontiguous. 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 Ccontiguous 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 ajoblib.parallel_backend
context.1
means using all processors. See Glossary for more details.algorithm – {“auto”, “full”, “elkan”}, default=”auto” Kmeans algorithm to use. The classical EMstyle 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
andmax_iter
), these will not be consistent withlabels_
.
 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.

__init__
(n_clusters=8, init='kmeans++', 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 kmeans clustering with norm ‘l1’.
 Parameters
X – arraylike 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 Ccontiguous.
y – Ignored Not used, present here for API consistency by convention.
sample_weight – arraylike, 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.

_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

fit
(X, y=None, sample_weight=None)[source]¶ Computes kmeans clustering.
 Parameters
X – arraylike 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 Ccontiguous.
y – Ignored Not used, present here for API consistency by convention.
sample_weight – arraylike, 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.

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 – {arraylike, sparse matrix} of shape (n_samples, n_features) New data to predict.
sample_weight – arraylike, 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.

transform
(X)[source]¶ Transforms X to a clusterdistance 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 – {arraylike, 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.

mlinsights.mlmodel.kmeans_l1.
_centers_dense
(X, sample_weight, labels, n_clusters, distances, X_sort_index)[source]¶ M step of the Kmeans EM algorithm. Computation of cluster centers / means.
 Parameters
X – arraylike, shape (n_samples, n_features)
sample_weight – arraylike, 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 – arraylike, shape (n_samples) Distance to closest cluster for each sample.
X_sort_index – arraylike, shape (n_samples, n_features) index of each feature in all features
 Returns
centers, array, shape (n_clusters, n_features) The resulting centers

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
{‘kmeans++’, ‘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)

mlinsights.mlmodel.kmeans_l1.
_k_init
(norm, X, n_clusters, random_state, n_local_trials=None)[source]¶ Init n_clusters seeds according to kmeans++
 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.

mlinsights.mlmodel.kmeans_l1.
_kmeans_single_lloyd
(norm, X, sample_weight, n_clusters, max_iter=300, init='kmeans++', verbose=False, random_state=None, tol=0.0001, precompute_distances=True)[source]¶ A single run of kmeans, assumes preparation completed prior.
 Parameters
norm – ‘l1’ or ‘l2’
X – arraylike 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 – arraylike, shape (n_samples,) The weights for each observation in X.
max_iter – int, optional, default 300 Maximum number of iterations of the kmeans algorithm to run.
init –
{‘kmeans++’, ‘random’, or ndarray, or a callable}, optional Method for initialization, default to ‘kmeans++’:
’kmeans++’ : selects initial cluster centers for kmean 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 kmeans.
 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.

mlinsights.mlmodel.kmeans_l1.
_labels_inertia
(norm, X, sample_weight, centers, precompute_distances=True, distances=None)[source]¶ E step of the Kmeans EM algorithm.
Computes the labels and the inertia of the given samples and centers. This will compute the distances inplace.
 Parameters
norm – ‘l1’ or ‘l2’
X – float64 arraylike or CSR sparse matrix, shape (n_samples, n_features) The input samples to assign to the labels.
sample_weight – arraylike, 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.