UNPKG

clustering-tfjs

Version:

High-performance TypeScript clustering algorithms (K-Means, Spectral, Agglomerative) with TensorFlow.js acceleration and scikit-learn compatibility

62 lines (61 loc) 2.6 kB
"use strict"; 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.createConstantEigenvector = createConstantEigenvector; const tf = __importStar(require("../tf-adapter")); /** * Creates the constant eigenvector for connected graphs in spectral clustering. * * For a connected graph, the smallest eigenvalue of the normalized Laplacian is 0, * and its corresponding eigenvector should be constant. However, numerical computation * can introduce small variations. sklearn replaces this with the theoretical constant * eigenvector to improve clustering stability. * * sklearn uses a simple constant vector 1/sqrt(n) for all entries, not the * degree-weighted version. This is then scaled by the spectral embedding normalization. * * @param affinity The affinity matrix * @returns The constant eigenvector as a column vector (n x 1) */ function createConstantEigenvector(affinity) { return tf.tidy(() => { const n = affinity.shape[0]; // Create simple constant vector: all entries are 1/sqrt(n) // This gives a unit-norm vector with all equal entries const value = 1.0 / Math.sqrt(n); const constantVec = tf.fill([n, 1], value); return constantVec; }); }