Registry / ai-ml / kmodes

kmodes

JSON →
library0.12.2pypypi✓ verified 22d ago

Python implementations of the k-modes and k-prototypes clustering algorithms for clustering categorical data. It is currently at version 0.12.2 and sees active development with several releases per year.

pip install kmodes
INSTALL
IMPORT
SIG · KMODES
K
kmodes
ai-mlpythonv0.12.2
Install
9.7s avg
Import
3190ms
Disk
280MB
Pass rate
5/ 10
Env Coverage5 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.12.2 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
build_error
glibc
py 3.103.95 runs
installs and imports cleanly · install 9.7s · import 3.190s · 270MB
280MB installed
● package 280MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

KModes
from kmodes.kmodes import KModes
KPrototypes
from kmodes.kprototypes import KPrototypes

Demonstrates basic usage of the KModes algorithm for clustering purely categorical data. Initialize the KModes estimator, fit it to your data, and retrieve the cluster assignments and centroids.

import numpy as np from kmodes.kmodes import KModes # Generate random categorical data (e.g., 100 samples, 10 features, 20 unique categories per feature) data = np.random.choice(20, (100, 10)) # Initialize KModes with 4 clusters, Huang initialization, 5 initialization runs km = KModes(n_clusters=4, init='Huang', n_init=5, verbose=1) # Fit the model and predict clusters clusters = km.fit_predict(data) # Print the cluster centroids print("Cluster Centroids:\n", km.cluster_centroids_) print("Assigned Clusters:\n", clusters[:10]) # Display first 10 assigned clusters
Debug
Known issues
breakingDropped support for missing values (np.NaN) in the input matrix (X) starting from version 0.11.1, following scikit-learn's approach. Users must now handle missing data manually by imputation or removal.
fix
Pre-process your data to handle `np.NaN` values (e.g., fill with a specific category for categorical features, or remove rows) before passing to `kmodes`.
affects: >=0.11.1
breakingPython 3.4 support was dropped in version 0.10.2. Official support for Python 3.10 was added in 0.12.0. Ensure your Python environment is compatible (Python 3.6+ is generally safe).
fix
Upgrade your Python environment to at least 3.6. For full compatibility with the latest features, Python 3.10 or newer is recommended.
affects: >=0.10.2
breakingThe minimum `scikit-learn` version was upgraded to 0.22 in kmodes version 0.11.0. Older `scikit-learn` versions may cause compatibility issues or `AttributeError`.
fix
Upgrade your `scikit-learn` library to version 0.22 or newer: `pip install --upgrade scikit-learn`.
affects: >=0.11.0
gotchaWhen using `KPrototypes`, one or more of your numerical feature columns may contain string values, leading to `TypeError: '<' not supported between instances of 'str' and 'float'`.
fix
Ensure that all numerical columns are consistently typed as numeric (e.g., `float` or `int`) before passing them to `KPrototypes`. Convert string representations of numbers to their proper numeric types.
affects: All
gotchaFor `KPrototypes`, you must explicitly specify which column indices are categorical using the `categorical` argument. If not provided, it assumes all are numerical, or can raise an error if mixed data types are present without specification.
fix
Pass a list of categorical column indices to the `categorical` parameter during `KPrototypes` initialization, e.g., `KPrototypes(..., categorical=[0, 2, 5])`.
affects: All
gotchaA `ModuleNotFoundError` (e.g., `No module named 'kmodes.kmodes'`) can occur if your working Python file is named `kmodes.py`, as it might shadow the installed `kmodes` package.
fix
Rename your local Python script to something other than `kmodes.py` (e.g., `my_script.py`) to avoid module name conflicts.
affects: All
gotchaEncountering `ValueError: Clustering algorithm could not initialize` is often an indication that the data and chosen parameters (e.g., `n_clusters`, `init` method) are not suitable. It's not necessarily a bug.
fix
Consider reducing the number of clusters, cleaning or normalizing your data, exploring different initialization methods, or ensuring sufficient data density for the chosen cluster count.
affects: All
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'kmodes'
The Python interpreter cannot find the 'kmodes' package, often because a local script is named 'kmodes.py' (shadowing the installed package) or the package is not installed in the active environment.
fix
Rename your Python script to something other than 'kmodes.py'. Ensure 'kmodes' is installed in your current environment using `pip install kmodes` or `conda install -c conda-forge kmodes`.
ValueError: Clustering algorithm could not initialize. Consider assigning the initial clusters manually.
The k-modes or k-prototypes algorithm failed to find suitable initial clusters or converge, often due to unsuitable data characteristics (e.g., very sparse data), a high number of clusters for the given data, or an ineffective initialization method.
fix
Try reducing the number of clusters (`n_clusters`), pre-processing your data, exploring different initialization methods (`init='Huang'` or `init='Cao'`), or increasing `n_init` (number of initialization runs) to find a better starting point.
TypeError: '<' not supported between instances of 'str' and 'float'
This error typically occurs when using `KPrototypes` and a column intended to be numerical contains string values, or when using `KModes` on data with mixed numerical/categorical types that it is not designed to handle without explicit type definition.
fix
Ensure all numerical columns are consistently typed as numeric (e.g., `float` or `int`) before passing them to `KPrototypes`. If using `KPrototypes`, explicitly specify categorical column indices using the `categorical` parameter; if your data is purely categorical, use `KModes`.
ValueError: Input contains NaN, infinity, or a value too large for dtype('float64').
The `kmodes` library (from version 0.11.1 onwards) does not support `np.NaN` (missing values) directly in the input data matrix `X`.
fix
Pre-process your data to handle `np.NaN` values by imputation (e.g., filling with a specific category for categorical features, or mean/median for numerical features) or by removing rows/columns with missing data before passing it to `kmodes`.
Upgrade
Version history
0.12.2latest on PyPI · released Sep 6, 2022
Audit
Dependencies
numpyrequiredRelies on numpy for core array operations and computations.
scikit-learnrequiredThe code is modeled after scikit-learn's interface and has a minimum version requirement of 0.22 since kmodes 0.11.0.
joblibrequiredUsed for parallel execution support via the `n_jobs` parameter for multiple initialization runs.
Agent activity
7 hits · last 30 days
node
6
Resources
kmodes — pip install kmodes · libregistry