A library for calculating the gap statistics for clustering algorithms
Project description
GapStatistics Package
The GapStatistics package provides a Python implementation of the Gap Statistics method for determining the optimal number of clusters in a dataset using K-means clustering derived from Tibshirani et al.. The package is designed to choose the distance metrics agnostically as well as the clustering algorithm. However, the primary usage is the KMeans algorithm.
Features
- Calculate the Gap Statistics for determining the optimal number of clusters in a dataset.
- Supports various distance metrics for clustering.
- Provides options for applying Principal Component Analysis (PCA) during bootstrapping.
- Allows to choose whether to return additional statistics for analysis.
Installation
To install the GapStatistics package, you can use pip:
pip install gapstatistics
Example - Training / Prediction
This is the basic use case. If you don't define the parameter algorithm parameter, the default clustering technique is KMeans. The returned object optimum is an integer showing the optimal number of clusters for the data.
from gapstatistics import GapStatistics
centers = [[0,0], [0,6], [3,2], [5,0]]
X = make_blobs(n_samples=200, centers=centers, n_features=2, cluster_std=1)
n_iterations = 30
gs = GapStatistics(distance_metric='minkowski')
optimum = Gs.fit_predict(K=10, X=X[0])
print(f'Optimum: {optimum}')
Example - Visualization
Here is some code that you can use for showing different plots how the gap statistics derives the optimal number of clusters. For this, you must set the return_params to True, so that you can plot them.
from gapstatistics import GapStatistics
from sklearn.datasets import make_blobs
centers = [[0,0], [0,6], [3,2], [5,0]]
X = make_blobs(n_samples=200, centers=centers, n_features=2, cluster_std=1)
n_iterations = 30
gs = GapStatistics(distance_metric='minkowski', return_params=True)
optimum, params = gs.fit_predict(K=10, X=X[0])
gs.plot()
Example - Provide custom distance metrics
Here is some code that you can use for creating a custom distance metric to provide to the class. The distance metric must have two parameters:
- X: (list)
- Centroid: (list)
def euclidian_distance(X: np.array, Centroid: np.array) -> np.array:
return np.linalg.norm(X - Centroid, axis=1)
def manhattan_distance(X: np.array, Centroid: np.array) -> np.array:
return np.sum(np.abs(X - Centroid), axis=1)
GapStatistics(distance_metric=manhattan_distance)
Parameters
GapStatistics Class
__init__(self, algorithm, distance_metric, pca_sampling, return_params)
-
algorithm(Callable): The clustering algorithm to use (default: KMeans). It should be a callable that creates a clustering model. If you want to use your own clustering algorithm, you must provide a callable object that has the following attributes / functions:- init(n_clusters)
- fit
- predict
- self.cluster_centers_
-
distance_metric(str or callable): The distance metric used for clustering. If a string, it should be a valid metric name recognized bysklearn.metrics.DistanceMetric. If a callable, it should accept two arrays and return the distance between them. Examples for strings are:- manhattan
- euclidean
- l1, l2
- minkowski
-
pca_sampling(bool): Whether to apply Principal Component Analysis (PCA) during bootstrapping (default: True). -
return_params(bool): Whether to return additional statistics in thefit_predictfunction (default: False).
Methods
fit_predict(self, K, X, n_iterations)
Perform gap statistics to find the optimal number of clusters (K) for a given dataset.
K(int): The maximum number of clusters (K) to consider for finding the optimal K value.X(list): A list of data points (samples) to be used for clustering. Must have a 2D shape -> (?, 2)n_iterations(int): The number of iterations to perform for simulating Wk's statistics.
Returns either the optimal number of clusters (K) or a tuple with the optimal K and additional statistics used in gap analysis.
plot(self, original_labels, colors)
Visualize the output of the gap statistics based on the returned parameters.
original_labels(list): The list of the original groundtruth labels to compare against (if accessible).colors(dict): If the optimal value is greater than 10, you must provide an additional color dictionary.
Returns a plot consisting of four subplots for showing why the gap statistics decided the optimal number of clusters.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file gapstatistics-0.1.5.tar.gz.
File metadata
- Download URL: gapstatistics-0.1.5.tar.gz
- Upload date:
- Size: 5.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.8.1 CPython/3.12.3 Darwin/24.0.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
a8d49d67f9362b0943aa0d60839470a64693692019cb2cd8ca5f5b53321e93c8
|
|
| MD5 |
d6670c4267be04937f391dc0933452aa
|
|
| BLAKE2b-256 |
0df7938c125f57f5d00a65ed31682a3b6a459c9b9a51807741f3dccbda470304
|
File details
Details for the file gapstatistics-0.1.5-py2.py3-none-any.whl.
File metadata
- Download URL: gapstatistics-0.1.5-py2.py3-none-any.whl
- Upload date:
- Size: 8.7 kB
- Tags: Python 2, Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.8.1 CPython/3.12.3 Darwin/24.0.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
842a828d5dec5d15f2b0cfbd7acdd2d414b8634c1e4004199eda98fd6a5642d4
|
|
| MD5 |
2bac755845b00accf96115abc3715e58
|
|
| BLAKE2b-256 |
2ba69f99b9d9426ee4eb4ee53f1f76c3e66ae04bb08b1fcd18d3abbb4e196875
|