Skip to main content
Version Conda forge page Build status Test coverage Codacy Monthly downloads Supported Python versions License

kmodes

Description

Python implementations of the k-modes and k-prototypes clustering algorithms. Relies on numpy for a lot of the heavy lifting.

k-modes is used for clustering categorical variables. It defines clusters based on the number of matching categories between data points. (This is in contrast to the more well-known k-means algorithm, which clusters numerical data based on Euclidean distance.) The k-prototypes algorithm combines k-modes and k-means and is able to cluster mixed numerical / categorical data.

Implemented are:

The code is modeled after the clustering algorithms in scikit-learn and has the same familiar interface.

I would love to have more people play around with this and give me feedback on my implementation. If you come across any issues in running or installing kmodes, please submit a bug report.

Enjoy!

Installation

kmodes can be installed using pip:

pip install kmodes

To upgrade to the latest version (recommended), run it like this:

pip install --upgrade kmodes

kmodes can also conveniently be installed with conda from the conda-forge channel:

conda install -c conda-forge kmodes

Alternatively, you can build the latest development version from source:

git clone https://github.com/nicodv/kmodes.git
cd kmodes
python setup.py install

Usage

import numpy as np
from kmodes.kmodes import KModes

# random categorical data
data = np.random.choice(20, (100, 10))

km = KModes(n_clusters=4, init='Huang', n_init=5, verbose=1)

clusters = km.fit_predict(data)

# Print the cluster centroids
print(km.cluster_centroids_)

The examples directory showcases simple use cases of both k-modes (‘soybean.py’) and k-prototypes (‘stocks.py’).

Parallel execution

The k-modes and k-prototypes implementations both offer support for multiprocessing via the joblib library, similar to e.g. scikit-learn’s implementation of k-means, using the n_jobs parameter. It generally does not make sense to set more jobs than there are processor cores available on your system.

This potentially speeds up any execution with more than one initialization try, n_init > 1, which may be helpful to reduce the execution time for larger problems. Note that it depends on your problem whether multiprocessing actually helps, so be sure to try that out first. You can check out the examples for some benchmarks.

FAQ

Q: I’m seeing errors such as “TypeError: ‘<’ not supported between instances of ‘str’ and ‘float’” when using the kprototypes algorithm.

A: One or more of your numerical feature columns have string values in them. Make sure that all columns have consistent data types.


Q: How does k-protypes know which of my features are numerical and which are categorical?

A: You tell it which column indices are categorical using the categorical argument. All others are assumed numerical. E.g., clusters = KPrototypes().fit_predict(X, categorical=[1, 2])


Q: I’m getting the following error, what gives? “ModuleNotFoundError: No module named ‘kmodes.kmodes’; ‘kmodes’ is not a package”.

A: Make sure your working file is not called ‘kmodes.py’, because it might overrule the kmodes package.


Q: I’m getting the following error: “ValueError: Clustering algorithm could not initialize. Consider assigning the initial clusters manually.”

A: This is a feature, not a bug. kmodes is telling you that it can’t make sense of the data you are presenting it. At least, not with the parameters you are setting the algorithm with. It is up to you, the data scientist, to figure out why. Some hints to possible solutions:

  • Run with fewer clusters as the data might not support a large number of clusters

  • Explore and visualize your data, checking for weird distributions, outliers, etc.

  • Clean and normalize the data

  • Increase the ratio of rows to columns


Q: I’m getting the following error: “ValueError: Input contains NaN, infinity, or a value too large for dtype(‘float64’).”

A: Following scikit-learn, the k-modes algorithm does not accept np.NaN values in the X matrix. Users are suggested to fill in the missing data in a way that makes sense for the problem at hand.


Q: How would like your library to be cited?

A: Something along these lines would do nicely:

@Misc{devos2015,
  author = {Nelis J. de Vos},
  title = {kmodes categorical clustering library},
  howpublished = {\url{https://github.com/nicodv/kmodes}},
  year = {2015--2021}
}

References

[HUANG97] (1,2)

Huang, Z.: Clustering large data sets with mixed numeric and categorical values, Proceedings of the First Pacific Asia Knowledge Discovery and Data Mining Conference, Singapore, pp. 21-34, 1997.

[HUANG98]

Huang, Z.: Extensions to the k-modes algorithm for clustering large data sets with categorical values, Data Mining and Knowledge Discovery 2(3), pp. 283-304, 1998.

[CAO09]

Cao, F., Liang, J, Bai, L.: A new initialization method for categorical data clustering, Expert Systems with Applications 36(7), pp. 10223-10228., 2009.

Release files for kmodes 0.12.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for kmodes 0.12.2
File Size Uploaded
kmodes-0.12.2.tar.gz 18.9 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for kmodes 0.12.2
File Interpreter ABI Platform
kmodes-0.12.2-py2.py3-none-any.whl Python 2, Python 3 none any Details

Total release size: 39.3 kB

Release files / kmodes-0.12.2.tar.gz

Download URL kmodes-0.12.2.tar.gz
Size 18.9 kB
Tags Source
SHA-256 checksum
How to use checksums
d840ac9f4616a668ebacba24a12ec1def87da24a9fd0a0dc2f7499a9b9a6f45b
BLAKE2b-256 checksum
How to use checksums
5c16e2b5222bb5efabc56259215bbc9e94df9ee08a43b5a9ed33aae28ce2dade
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.0 CPython/3.10.4

Release files / kmodes-0.12.2-py2.py3-none-any.whl

Download URL kmodes-0.12.2-py2.py3-none-any.whl
Size 20.4 kB
Tags Python 2 Python 3
SHA-256 checksum
How to use checksums
b764f7166dd5fe63826135ed74df796693dc7c25fc2cb8a106e14f3bfb371004
BLAKE2b-256 checksum
How to use checksums
1aa80d3bf6f3340cbcb8cf4ad02c306d157af8f09ce86aadf5346e00605870dd
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.0 CPython/3.10.4

Release history Release notifications | RSS feed

This release

0.12.2 This release

2 release files

0.12.1

2 release files

0.12.0

2 release files

0.11.0

2 release files

0.10.2

2 release files

0.10.1

2 release files

0.9

2 release files

0.8

2 release files

0.7

2 release files

0.6

2 release files

0.5

2 release files

0.4

2 release files

0.2

2 release files

0.1

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page