cerceis-lib
Version:
Contains list of quality of life functions that is written in TypeScript and es6
72 lines (70 loc) • 2.49 kB
text/typescript
interface Cluster {
id: number;
position: number;
childs: number[];
}
/**
* Simple 1D K-means clustering.
* Runs multiple attempts and returns the best result (most balanced cluster sizes).
* @param k Number of clusters (default 2).
* @param arr Input data points.
* @param attempts Number of attempts to run (default 1).
*/
declare const KMeans: (k: number | undefined, arr: number[], attempts?: number) => Cluster[];
interface NDCluster<T> {
/** 1-based cluster id */
id: number;
/** Mean position in feature space */
centroid: number[];
/** Original data items assigned to this cluster */
members: T[];
/** Number of members */
size: number;
/**
* Within-cluster sum of squares — sum of squared Euclidean distances
* from each member to the centroid. Lower means a tighter, more
* cohesive cluster.
*/
wcss: number;
}
type FeatureExtractor<T> = (item: T) => number[];
interface KMeansNDOptions {
/**
* Number of independent runs. The run with the lowest total WCSS wins.
* More attempts → more reliable result at the cost of compute.
* Default: 5.
*/
attempts?: number;
/**
* Centroid initialisation strategy.
* - `'kmeans++'` (default) spreads initial centroids far apart,
* which dramatically reduces the chance of a poor local minimum.
* - `'random'` picks k random data points as starting centroids.
*/
init?: 'random' | 'kmeans++';
/**
* Hard cap on iteration count per attempt.
* Default: 300.
*/
maxIter?: number;
}
/**
* N-dimensional K-means clustering suitable for production analytics
* (customer segmentation, product segmentation, etc.).
*
* @param k Number of clusters.
* @param data Array of items to cluster.
* @param features Function that extracts a numeric feature vector from each item.
* All vectors must have the same length.
* @param options Optional tuning parameters.
*
* @example
* // Customer segmentation by recency, frequency, monetary value (RFM)
* const segments = KMeansND(3, customers, (c) => [c.recency, c.frequency, c.spend]);
*
* @example
* // Works with plain number arrays too
* const result = KMeansND(2, [[1,2],[3,4],[100,200]], (x) => x);
*/
declare const KMeansND: <T>(k: number, data: T[], features: FeatureExtractor<T>, options?: KMeansNDOptions) => NDCluster<T>[];
export { type FeatureExtractor, KMeans, KMeansND, type KMeansNDOptions, type NDCluster };