clustering-tfjs
Version:
High-performance TypeScript clustering algorithms (K-Means, Spectral, Agglomerative) with TensorFlow.js acceleration and scikit-learn compatibility
139 lines (138 loc) • 6.63 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpectralClusteringConsensus = void 0;
const tf = __importStar(require("../tf-adapter"));
const spectral_1 = require("./spectral");
const tensor_utils_1 = require("../utils/tensor-utils");
/**
* SpectralClustering with consensus clustering to improve robustness.
* Runs k-means multiple times and takes majority vote for each point.
*/
class SpectralClusteringConsensus extends spectral_1.SpectralClustering {
constructor(params) {
super(params);
this.consensusRuns = params.consensusRuns ?? 50;
}
async fit(X) {
// We need a custom implementation that recomputes the embedding
// because the parent class doesn't store it
const Xtensor = (0, tensor_utils_1.isTensor)(X)
? tf.cast(X, 'float32')
: tf.tensor2d(X, undefined, 'float32');
// Build affinity matrix (reuse parent logic)
const computeAffinityMatrix = spectral_1.SpectralClustering.computeAffinityMatrix;
this.affinityMatrix_ = computeAffinityMatrix(Xtensor, this.params);
const affinitySum = (await this.affinityMatrix_.sum().data())[0];
if (affinitySum === 0) {
throw new Error('Affinity matrix contains only zeros – cannot perform spectral clustering.');
}
// Detect connected components
const { detectConnectedComponents } = await Promise.resolve().then(() => __importStar(require('../utils/connected_components')));
const { numComponents, isFullyConnected, componentLabels } = detectConnectedComponents(this.affinityMatrix_);
if (!isFullyConnected) {
console.warn('Graph is not fully connected, spectral embedding may not work as expected.');
}
let U;
// If graph is disconnected and has enough components, use component indicators
if (!isFullyConnected && numComponents >= this.params.nClusters) {
const { createComponentIndicators } = await Promise.resolve().then(() => __importStar(require('../utils/component_indicators')));
U = createComponentIndicators(componentLabels, numComponents, numComponents);
}
else {
// Standard approach: compute Laplacian and eigenvectors
const { normalised_laplacian } = await Promise.resolve().then(() => __importStar(require('../utils/laplacian')));
const laplacian = tf.tidy(() => normalised_laplacian(this.affinityMatrix_));
const { smallest_eigenvectors_with_values } = await Promise.resolve().then(() => __importStar(require('../utils/smallest_eigenvectors_with_values')));
const numEigenvectors = Math.max(this.params.nClusters, numComponents);
const { eigenvectors: U_full, eigenvalues } = smallest_eigenvectors_with_values(laplacian, numEigenvectors);
// Apply diffusion map scaling
const U_scaled = tf.tidy(() => {
const numToUse = this.params.nClusters;
const eigenvals = tf.slice(eigenvalues, [0], [numToUse]);
const scalingFactors = tf.sqrt(tf.maximum(tf.scalar(0), tf.sub(tf.scalar(1), eigenvals)));
const scalingFactors2D = scalingFactors.reshape([1, -1]);
const U_selected = tf.slice(U_full, [0, 0], [-1, numToUse]);
return U_selected.mul(scalingFactors2D);
});
U = U_scaled;
laplacian.dispose();
eigenvalues.dispose();
U_full.dispose();
}
// Run k-means multiple times with different random seeds
const { KMeans } = await Promise.resolve().then(() => __importStar(require('./kmeans')));
const allLabels = [];
for (let run = 0; run < this.consensusRuns; run++) {
const km = new KMeans({
nClusters: this.params.nClusters,
randomState: (this.params.randomState ?? 42) + run,
nInit: 1, // Single init per run, we handle multiple runs here
});
await km.fit(U);
allLabels.push(km.labels_);
}
// Consensus: for each point, take the most common label
const n = allLabels[0].length;
const consensusLabels = [];
for (let i = 0; i < n; i++) {
// Get all labels for point i
const labelsForPoint = allLabels.map((labels) => labels[i]);
// Count occurrences
const counts = new Map();
for (const label of labelsForPoint) {
counts.set(label, (counts.get(label) || 0) + 1);
}
// Find most common label
let maxCount = 0;
let consensusLabel = 0;
for (const [label, count] of counts) {
if (count > maxCount) {
maxCount = count;
consensusLabel = label;
}
}
consensusLabels.push(consensusLabel);
}
// Update labels
this.labels_ = consensusLabels;
// Cleanup
U.dispose();
if (!(0, tensor_utils_1.isTensor)(X)) {
Xtensor.dispose();
}
}
}
exports.SpectralClusteringConsensus = SpectralClusteringConsensus;