clusterkw
Version:
A package for clustering keywords using OpenAI embeddings
45 lines (44 loc) • 1.42 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.simpleClustering = simpleClustering;
/**
* Simple clustering algorithm based on distance threshold
* @param keywords Array of keywords to cluster
* @param distances Matrix of distances between keywords
* @param options Configuration options
* @returns Array of clusters
*/
function simpleClustering(keywords, distances, options) {
const { minClusterSize, distanceThreshold } = options;
const n = keywords.length;
const visited = new Set();
const clusters = [];
for (let i = 0; i < n; i++) {
if (visited.has(i))
continue;
const cluster = [keywords[i]];
visited.add(i);
for (let j = 0; j < n; j++) {
if (i === j || visited.has(j))
continue;
if (distances[i][j] <= distanceThreshold) {
cluster.push(keywords[j]);
visited.add(j);
}
}
if (cluster.length >= minClusterSize) {
clusters.push({ items: cluster });
}
}
// Handle unclustered items
const unclustered = [];
for (let i = 0; i < n; i++) {
if (!visited.has(i)) {
unclustered.push(keywords[i]);
}
}
if (unclustered.length > 0 && unclustered.length >= minClusterSize) {
clusters.push({ items: unclustered });
}
return clusters;
}