@memberjunction/ai-vectors-memory 3.3.0 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +5 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -5
- package/dist/index.js.map +1 -1
- package/dist/models/SimpleVectorService.d.ts +945 -0
- package/dist/models/SimpleVectorService.d.ts.map +1 -1
- package/dist/models/SimpleVectorService.js +1028 -13
- package/dist/models/SimpleVectorService.js.map +1 -1
- package/package.json +7 -6
|
@@ -1,12 +1,57 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
1
|
+
import { LogError } from '@memberjunction/core';
|
|
2
|
+
/**
|
|
3
|
+
* SimpleVectorService provides in-memory vector similarity search capabilities.
|
|
4
|
+
* This service is storage-agnostic and allows developers to manage their own vector persistence.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* ```typescript
|
|
8
|
+
* // Create service instance
|
|
9
|
+
* const vectorService = new SimpleVectorService();
|
|
10
|
+
*
|
|
11
|
+
* // Load vectors from your data source
|
|
12
|
+
* const vectors = new Map<string, number[]>();
|
|
13
|
+
* vectors.set('item1', [0.1, 0.2, 0.3]);
|
|
14
|
+
* vectors.set('item2', [0.4, 0.5, 0.6]);
|
|
15
|
+
* vectorService.LoadVectors(vectors);
|
|
16
|
+
*
|
|
17
|
+
* // Find similar items
|
|
18
|
+
* const queryVector = [0.15, 0.25, 0.35];
|
|
19
|
+
* const results = vectorService.FindNearest(queryVector, 5);
|
|
20
|
+
* ```
|
|
21
|
+
*
|
|
22
|
+
* @class
|
|
23
|
+
* @public
|
|
24
|
+
*/
|
|
25
|
+
export class SimpleVectorService {
|
|
6
26
|
constructor() {
|
|
7
27
|
this.vectors = new Map();
|
|
8
28
|
this.expectedDimensions = null;
|
|
9
29
|
}
|
|
30
|
+
/**
|
|
31
|
+
* Loads vectors into memory. Can accept either an array of VectorEntry objects
|
|
32
|
+
* or a Map where keys are identifiers and values are vector arrays.
|
|
33
|
+
*
|
|
34
|
+
* @param {VectorEntry<TMetadata>[] | Map<string, number[]>} entries - The vectors to load
|
|
35
|
+
* @throws {Error} If entries is null or undefined
|
|
36
|
+
*
|
|
37
|
+
* @example
|
|
38
|
+
* ```typescript
|
|
39
|
+
* // Load from array
|
|
40
|
+
* service.LoadVectors([
|
|
41
|
+
* { key: 'doc1', vector: [0.1, 0.2], metadata: { title: 'Document 1' } },
|
|
42
|
+
* { key: 'doc2', vector: [0.3, 0.4], metadata: { title: 'Document 2' } }
|
|
43
|
+
* ]);
|
|
44
|
+
*
|
|
45
|
+
* // Load from Map
|
|
46
|
+
* const vectorMap = new Map();
|
|
47
|
+
* vectorMap.set('doc1', [0.1, 0.2]);
|
|
48
|
+
* vectorMap.set('doc2', [0.3, 0.4]);
|
|
49
|
+
* service.LoadVectors(vectorMap);
|
|
50
|
+
* ```
|
|
51
|
+
*
|
|
52
|
+
* @public
|
|
53
|
+
* @method
|
|
54
|
+
*/
|
|
10
55
|
LoadVectors(entries) {
|
|
11
56
|
if (!entries) {
|
|
12
57
|
throw new Error('Entries cannot be null or undefined');
|
|
@@ -24,6 +69,25 @@ class SimpleVectorService {
|
|
|
24
69
|
});
|
|
25
70
|
}
|
|
26
71
|
}
|
|
72
|
+
/**
|
|
73
|
+
* Adds or updates a single vector in the service
|
|
74
|
+
*
|
|
75
|
+
* @param {string} key - The unique identifier for the vector
|
|
76
|
+
* @param {number[]} vector - The vector/embedding array
|
|
77
|
+
* @param {TMetadata} metadata - Optional metadata to associate with the vector
|
|
78
|
+
* @throws {Error} If key is null/undefined, or if vector is invalid
|
|
79
|
+
*
|
|
80
|
+
* @example
|
|
81
|
+
* ```typescript
|
|
82
|
+
* service.AddVector('product123', [0.1, 0.2, 0.3], {
|
|
83
|
+
* name: 'Product Name',
|
|
84
|
+
* category: 'Electronics'
|
|
85
|
+
* });
|
|
86
|
+
* ```
|
|
87
|
+
*
|
|
88
|
+
* @public
|
|
89
|
+
* @method
|
|
90
|
+
*/
|
|
27
91
|
AddVector(key, vector, metadata) {
|
|
28
92
|
if (!key) {
|
|
29
93
|
throw new Error('Key cannot be null or undefined');
|
|
@@ -34,13 +98,53 @@ class SimpleVectorService {
|
|
|
34
98
|
this.validateAndSetDimensions(vector);
|
|
35
99
|
this.vectors.set(key, { key, vector, metadata });
|
|
36
100
|
}
|
|
101
|
+
/**
|
|
102
|
+
* Finds the K nearest neighbors to a query vector using the specified similarity metric
|
|
103
|
+
*
|
|
104
|
+
* @param {number[]} queryVector - The vector to search for similar items
|
|
105
|
+
* @param {number} [topK=10] - Number of nearest neighbors to return
|
|
106
|
+
* @param {number} [threshold] - Optional minimum similarity threshold (0-1)
|
|
107
|
+
* @param {DistanceMetric} [metric='cosine'] - The distance metric to use
|
|
108
|
+
* @param {(metadata: TMetadata) => boolean} [filter] - Optional filter to pre-filter vectors by metadata before similarity calculation
|
|
109
|
+
* @returns {VectorSearchResult<TMetadata>[]} Array of search results sorted by similarity (highest first)
|
|
110
|
+
* @throws {Error} If queryVector is null/undefined or empty
|
|
111
|
+
*
|
|
112
|
+
* @example
|
|
113
|
+
* ```typescript
|
|
114
|
+
* // Default cosine similarity
|
|
115
|
+
* const nearestItems = service.FindNearest(queryEmbedding, 5);
|
|
116
|
+
*
|
|
117
|
+
* // Using Euclidean distance for numeric features
|
|
118
|
+
* const similarProducts = service.FindNearest(productFeatures, 10, undefined, 'euclidean');
|
|
119
|
+
*
|
|
120
|
+
* // With threshold - only return items with similarity > 0.7
|
|
121
|
+
* const highSimilarity = service.FindNearest(queryVector, 10, 0.7, 'cosine');
|
|
122
|
+
*
|
|
123
|
+
* // Using Jaccard for categorical data
|
|
124
|
+
* const similarUsers = service.FindNearest(userPreferences, 5, undefined, 'jaccard');
|
|
125
|
+
*
|
|
126
|
+
* // Filter by metadata before searching (efficient pre-filtering)
|
|
127
|
+
* const agentNotes = service.FindNearest(
|
|
128
|
+
* queryVector,
|
|
129
|
+
* 5,
|
|
130
|
+
* 0.5,
|
|
131
|
+
* 'cosine',
|
|
132
|
+
* (metadata) => metadata.agentId === 'agent-123'
|
|
133
|
+
* );
|
|
134
|
+
* ```
|
|
135
|
+
*
|
|
136
|
+
* @public
|
|
137
|
+
* @method
|
|
138
|
+
*/
|
|
37
139
|
FindNearest(queryVector, topK = 10, threshold, metric = 'cosine', filter) {
|
|
38
140
|
if (!queryVector || queryVector.length === 0) {
|
|
39
141
|
throw new Error('Query vector cannot be null, undefined, or empty');
|
|
40
142
|
}
|
|
143
|
+
// Pre-filter vectors by metadata BEFORE similarity calculation
|
|
41
144
|
const candidateVectors = filter
|
|
42
145
|
? Array.from(this.vectors.values()).filter(entry => entry.metadata && filter(entry.metadata))
|
|
43
146
|
: Array.from(this.vectors.values());
|
|
147
|
+
// Calculate similarity ONLY for filtered candidates
|
|
44
148
|
const results = candidateVectors
|
|
45
149
|
.map(entry => {
|
|
46
150
|
try {
|
|
@@ -51,7 +155,8 @@ class SimpleVectorService {
|
|
|
51
155
|
};
|
|
52
156
|
}
|
|
53
157
|
catch (error) {
|
|
54
|
-
|
|
158
|
+
// Log error and skip this entry
|
|
159
|
+
LogError(`Error calculating ${metric} similarity for key ${entry.key}: ${error}`);
|
|
55
160
|
return null;
|
|
56
161
|
}
|
|
57
162
|
})
|
|
@@ -61,15 +166,69 @@ class SimpleVectorService {
|
|
|
61
166
|
.slice(0, topK);
|
|
62
167
|
return results;
|
|
63
168
|
}
|
|
169
|
+
/**
|
|
170
|
+
* Finds vectors similar to an existing vector identified by its key.
|
|
171
|
+
* The source vector itself is excluded from the results.
|
|
172
|
+
*
|
|
173
|
+
* @param {string} key - The key of the source vector
|
|
174
|
+
* @param {number} [topK=10] - Number of similar vectors to return
|
|
175
|
+
* @param {number} [threshold] - Optional minimum similarity threshold (0-1)
|
|
176
|
+
* @param {DistanceMetric} [metric='cosine'] - The distance metric to use
|
|
177
|
+
* @param {(metadata: TMetadata) => boolean} [filter] - Optional filter to pre-filter vectors by metadata before similarity calculation
|
|
178
|
+
* @returns {VectorSearchResult<TMetadata>[]} Array of similar vectors sorted by similarity
|
|
179
|
+
* @throws {Error} If the key doesn't exist in the service
|
|
180
|
+
*
|
|
181
|
+
* @example
|
|
182
|
+
* ```typescript
|
|
183
|
+
* // Find items similar to 'product123'
|
|
184
|
+
* const similarProducts = service.FindSimilar('product123', 5);
|
|
185
|
+
*
|
|
186
|
+
* // Find highly similar items (similarity > 0.8)
|
|
187
|
+
* const verySimilar = service.FindSimilar('product123', 10, 0.8);
|
|
188
|
+
*
|
|
189
|
+
* // Find similar items using Euclidean distance
|
|
190
|
+
* const similar = service.FindSimilar('product123', 5, undefined, 'euclidean');
|
|
191
|
+
*
|
|
192
|
+
* // Find similar items filtered by category
|
|
193
|
+
* const similarInCategory = service.FindSimilar(
|
|
194
|
+
* 'product123',
|
|
195
|
+
* 5,
|
|
196
|
+
* 0.7,
|
|
197
|
+
* 'cosine',
|
|
198
|
+
* (metadata) => metadata.category === 'Electronics'
|
|
199
|
+
* );
|
|
200
|
+
* ```
|
|
201
|
+
*
|
|
202
|
+
* @public
|
|
203
|
+
* @method
|
|
204
|
+
*/
|
|
64
205
|
FindSimilar(key, topK = 10, threshold, metric = 'cosine', filter) {
|
|
65
206
|
const sourceVector = this.vectors.get(key);
|
|
66
207
|
if (!sourceVector) {
|
|
67
208
|
throw new Error(`Vector with key "${key}" not found`);
|
|
68
209
|
}
|
|
210
|
+
// Get topK + 1 to account for excluding self
|
|
69
211
|
return this.FindNearest(sourceVector.vector, topK + 1, threshold, metric, filter)
|
|
70
|
-
.filter(result => result.key !== key)
|
|
212
|
+
.filter(result => result.key !== key) // Exclude self
|
|
71
213
|
.slice(0, topK);
|
|
72
214
|
}
|
|
215
|
+
/**
|
|
216
|
+
* Calculates the cosine similarity between two vectors identified by their keys
|
|
217
|
+
*
|
|
218
|
+
* @param {string} key1 - Key of the first vector
|
|
219
|
+
* @param {string} key2 - Key of the second vector
|
|
220
|
+
* @returns {number} Cosine similarity score between 0 and 1
|
|
221
|
+
* @throws {Error} If either key doesn't exist in the service
|
|
222
|
+
*
|
|
223
|
+
* @example
|
|
224
|
+
* ```typescript
|
|
225
|
+
* const similarity = service.Similarity('item1', 'item2');
|
|
226
|
+
* console.log(`Similarity: ${similarity}`);
|
|
227
|
+
* ```
|
|
228
|
+
*
|
|
229
|
+
* @public
|
|
230
|
+
* @method
|
|
231
|
+
*/
|
|
73
232
|
Similarity(key1, key2) {
|
|
74
233
|
const v1 = this.vectors.get(key1);
|
|
75
234
|
const v2 = this.vectors.get(key2);
|
|
@@ -81,23 +240,133 @@ class SimpleVectorService {
|
|
|
81
240
|
}
|
|
82
241
|
return this.CosineSimilarity(v1.vector, v2.vector);
|
|
83
242
|
}
|
|
243
|
+
/**
|
|
244
|
+
* Calculates cosine similarity between two vectors using the formula:
|
|
245
|
+
* similarity = (A · B) / (||A|| × ||B||)
|
|
246
|
+
*
|
|
247
|
+
* ## What is Cosine Similarity?
|
|
248
|
+
* Cosine similarity measures the cosine of the angle between two vectors in multi-dimensional space.
|
|
249
|
+
* It tells us how similar two vectors are regardless of their magnitude (length).
|
|
250
|
+
*
|
|
251
|
+
* ## Return Values:
|
|
252
|
+
* - **1.0**: Vectors point in exactly the same direction (identical)
|
|
253
|
+
* - **0.0**: Vectors are perpendicular (orthogonal/unrelated)
|
|
254
|
+
* - **-1.0**: Vectors point in opposite directions (completely different)
|
|
255
|
+
* - **0.7-1.0**: High similarity (vectors are closely related)
|
|
256
|
+
* - **0.3-0.7**: Moderate similarity
|
|
257
|
+
* - **< 0.3**: Low similarity
|
|
258
|
+
*
|
|
259
|
+
* ## Why Use Cosine Similarity for Embeddings?
|
|
260
|
+
* Text embeddings encode semantic meaning as vectors. Cosine similarity is ideal because:
|
|
261
|
+
* - It focuses on direction (meaning) rather than magnitude (importance)
|
|
262
|
+
* - It's normalized between -1 and 1, making scores comparable
|
|
263
|
+
* - It works well in high-dimensional spaces (384-1536 dimensions)
|
|
264
|
+
*
|
|
265
|
+
* ## Mathematical Formula:
|
|
266
|
+
* ```
|
|
267
|
+
* cosine_similarity = dot_product(A, B) / (magnitude(A) * magnitude(B))
|
|
268
|
+
*
|
|
269
|
+
* Where:
|
|
270
|
+
* - dot_product(A, B) = Σ(a[i] * b[i]) for all i
|
|
271
|
+
* - magnitude(A) = √(Σ(a[i]²)) for all i
|
|
272
|
+
* ```
|
|
273
|
+
*
|
|
274
|
+
* @param {number[]} a - First vector (e.g., embedding of document A)
|
|
275
|
+
* @param {number[]} b - Second vector (e.g., embedding of document B)
|
|
276
|
+
* @returns {number} Cosine similarity score between -1 and 1
|
|
277
|
+
* @throws {Error} If vectors have different dimensions (must be same length)
|
|
278
|
+
*
|
|
279
|
+
* @example
|
|
280
|
+
* ```typescript
|
|
281
|
+
* // Two identical vectors have similarity of 1
|
|
282
|
+
* const similarity1 = CosineSimilarity([1, 2, 3], [1, 2, 3]); // ≈ 1.0
|
|
283
|
+
*
|
|
284
|
+
* // Perpendicular vectors have similarity of 0
|
|
285
|
+
* const similarity2 = CosineSimilarity([1, 0], [0, 1]); // = 0.0
|
|
286
|
+
*
|
|
287
|
+
* // Opposite vectors have similarity of -1
|
|
288
|
+
* const similarity3 = CosineSimilarity([1, 2], [-1, -2]); // = -1.0
|
|
289
|
+
* ```
|
|
290
|
+
*
|
|
291
|
+
* @protected
|
|
292
|
+
* @method
|
|
293
|
+
*/
|
|
84
294
|
CosineSimilarity(a, b) {
|
|
295
|
+
// Vectors must have the same number of dimensions to be compared
|
|
296
|
+
// For embeddings, this means both texts were processed by the same model
|
|
85
297
|
if (a.length !== b.length) {
|
|
86
298
|
throw new Error(`Vectors must have same dimensions. Got ${a.length} and ${b.length}`);
|
|
87
299
|
}
|
|
300
|
+
// Initialize our three accumulator variables:
|
|
301
|
+
// - dotProduct: Sum of element-wise products (measures alignment)
|
|
302
|
+
// - normA: Sum of squares for vector A (used to calculate magnitude)
|
|
303
|
+
// - normB: Sum of squares for vector B (used to calculate magnitude)
|
|
88
304
|
let dotProduct = 0;
|
|
89
305
|
let normA = 0;
|
|
90
306
|
let normB = 0;
|
|
307
|
+
// Single pass through both vectors to calculate all needed values
|
|
308
|
+
// This is more efficient than multiple loops
|
|
91
309
|
for (let i = 0; i < a.length; i++) {
|
|
310
|
+
// Dot product: Multiply corresponding elements and sum them
|
|
311
|
+
// This measures how much the vectors "agree" at each dimension
|
|
92
312
|
dotProduct += a[i] * b[i];
|
|
93
|
-
|
|
94
|
-
|
|
313
|
+
// Calculate sum of squares for each vector
|
|
314
|
+
// These will be used to normalize the dot product
|
|
315
|
+
normA += a[i] * a[i]; // Same as Math.pow(a[i], 2) but faster
|
|
316
|
+
normB += b[i] * b[i]; // Same as Math.pow(b[i], 2) but faster
|
|
95
317
|
}
|
|
318
|
+
// Handle edge case: Zero vectors (all elements are 0)
|
|
319
|
+
// A zero vector has no direction, so similarity is undefined
|
|
320
|
+
// We return 0 by convention (neither similar nor dissimilar)
|
|
96
321
|
if (normA === 0 || normB === 0) {
|
|
97
322
|
return 0;
|
|
98
323
|
}
|
|
324
|
+
// Final calculation: Normalize the dot product by the magnitudes
|
|
325
|
+
// Math.sqrt(normA) = magnitude of vector A (||A||)
|
|
326
|
+
// Math.sqrt(normB) = magnitude of vector B (||B||)
|
|
327
|
+
// This gives us the cosine of the angle between the vectors
|
|
99
328
|
return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
|
|
100
329
|
}
|
|
330
|
+
/**
|
|
331
|
+
* Calculates Euclidean distance between two vectors, normalized to 0-1 range.
|
|
332
|
+
*
|
|
333
|
+
* ## What is Euclidean Distance?
|
|
334
|
+
* Euclidean distance is the "straight-line" distance between two points in space.
|
|
335
|
+
* It's what you'd measure with a ruler in the physical world.
|
|
336
|
+
*
|
|
337
|
+
* ## Mathematical Formula:
|
|
338
|
+
* ```
|
|
339
|
+
* distance = √(Σ(a[i] - b[i])²)
|
|
340
|
+
* normalized_similarity = 1 / (1 + distance)
|
|
341
|
+
* ```
|
|
342
|
+
*
|
|
343
|
+
* ## Return Values (Normalized):
|
|
344
|
+
* - **1.0**: Identical vectors (distance = 0)
|
|
345
|
+
* - **0.5**: Moderate distance (distance = 1)
|
|
346
|
+
* - **→0**: Very different vectors (large distance)
|
|
347
|
+
*
|
|
348
|
+
* ## Business Use Cases:
|
|
349
|
+
* - **Product specifications**: Compare products by numeric features (size, weight, price)
|
|
350
|
+
* - **Quality control**: Measure deviation from target specifications
|
|
351
|
+
* - **Geographic analysis**: Distance between store locations (lat/long)
|
|
352
|
+
* - **Customer segmentation**: Group customers by purchase behavior metrics
|
|
353
|
+
* - **Inventory management**: Find similar SKUs by dimensions
|
|
354
|
+
*
|
|
355
|
+
* ## When to Use:
|
|
356
|
+
* ✅ Continuous numeric features where magnitude matters
|
|
357
|
+
* ✅ Physical measurements and specifications
|
|
358
|
+
* ✅ When you need true geometric distance
|
|
359
|
+
* ❌ High-dimensional sparse data (use cosine instead)
|
|
360
|
+
* ❌ Text embeddings (use cosine for better results)
|
|
361
|
+
*
|
|
362
|
+
* @param {number[]} a - First vector
|
|
363
|
+
* @param {number[]} b - Second vector
|
|
364
|
+
* @returns {number} Normalized similarity score (0-1, where 1 = identical)
|
|
365
|
+
* @throws {Error} If vectors have different dimensions
|
|
366
|
+
*
|
|
367
|
+
* @protected
|
|
368
|
+
* @method
|
|
369
|
+
*/
|
|
101
370
|
EuclideanDistance(a, b) {
|
|
102
371
|
if (a.length !== b.length) {
|
|
103
372
|
throw new Error(`Vectors must have same dimensions. Got ${a.length} and ${b.length}`);
|
|
@@ -108,8 +377,51 @@ class SimpleVectorService {
|
|
|
108
377
|
sumSquaredDiff += diff * diff;
|
|
109
378
|
}
|
|
110
379
|
const distance = Math.sqrt(sumSquaredDiff);
|
|
380
|
+
// Normalize to 0-1 range: closer = higher score
|
|
111
381
|
return 1 / (1 + distance);
|
|
112
382
|
}
|
|
383
|
+
/**
|
|
384
|
+
* Calculates Manhattan distance between two vectors, normalized to 0-1 range.
|
|
385
|
+
*
|
|
386
|
+
* ## What is Manhattan Distance?
|
|
387
|
+
* Manhattan distance (also called L1 distance, city block distance, or taxicab distance)
|
|
388
|
+
* measures the distance between two points by summing the absolute differences of their coordinates.
|
|
389
|
+
* Like navigating a city grid where you can only move along streets.
|
|
390
|
+
*
|
|
391
|
+
* ## Mathematical Formula:
|
|
392
|
+
* ```
|
|
393
|
+
* distance = Σ|a[i] - b[i]|
|
|
394
|
+
* normalized_similarity = 1 / (1 + distance)
|
|
395
|
+
* ```
|
|
396
|
+
*
|
|
397
|
+
* ## Return Values (Normalized):
|
|
398
|
+
* - **1.0**: Identical vectors (distance = 0)
|
|
399
|
+
* - **0.5**: Moderate distance (sum of differences = 1)
|
|
400
|
+
* - **→0**: Very different vectors (large total difference)
|
|
401
|
+
*
|
|
402
|
+
* ## Business Use Cases:
|
|
403
|
+
* - **Supply chain**: Warehouse grid navigation, pick-path optimization
|
|
404
|
+
* - **Time series**: Comparing trends (robust to outliers)
|
|
405
|
+
* - **Resource allocation**: Movement costs in grid systems
|
|
406
|
+
* - **Urban planning**: Actual travel distance in city blocks
|
|
407
|
+
* - **Inventory differences**: Total units different across SKUs
|
|
408
|
+
*
|
|
409
|
+
* ## When to Use:
|
|
410
|
+
* ✅ Grid-based movement systems
|
|
411
|
+
* ✅ When outliers should have linear (not squared) impact
|
|
412
|
+
* ✅ Discrete movements or changes
|
|
413
|
+
* ✅ Each dimension represents independent cost/distance
|
|
414
|
+
* ❌ Smooth gradients needed
|
|
415
|
+
* ❌ True geometric distance required
|
|
416
|
+
*
|
|
417
|
+
* @param {number[]} a - First vector
|
|
418
|
+
* @param {number[]} b - Second vector
|
|
419
|
+
* @returns {number} Normalized similarity score (0-1, where 1 = identical)
|
|
420
|
+
* @throws {Error} If vectors have different dimensions
|
|
421
|
+
*
|
|
422
|
+
* @protected
|
|
423
|
+
* @method
|
|
424
|
+
*/
|
|
113
425
|
ManhattanDistance(a, b) {
|
|
114
426
|
if (a.length !== b.length) {
|
|
115
427
|
throw new Error(`Vectors must have same dimensions. Got ${a.length} and ${b.length}`);
|
|
@@ -118,8 +430,50 @@ class SimpleVectorService {
|
|
|
118
430
|
for (let i = 0; i < a.length; i++) {
|
|
119
431
|
sumAbsDiff += Math.abs(a[i] - b[i]);
|
|
120
432
|
}
|
|
433
|
+
// Normalize to 0-1 range
|
|
121
434
|
return 1 / (1 + sumAbsDiff);
|
|
122
435
|
}
|
|
436
|
+
/**
|
|
437
|
+
* Calculates dot product similarity between two vectors, normalized to 0-1 range.
|
|
438
|
+
*
|
|
439
|
+
* ## What is Dot Product?
|
|
440
|
+
* Dot product (inner product) measures both direction AND magnitude alignment.
|
|
441
|
+
* Unlike cosine similarity, it rewards vectors that point the same way AND have similar magnitudes.
|
|
442
|
+
*
|
|
443
|
+
* ## Mathematical Formula:
|
|
444
|
+
* ```
|
|
445
|
+
* dot_product = Σ(a[i] × b[i])
|
|
446
|
+
* normalized = (tanh(dot_product / scale) + 1) / 2
|
|
447
|
+
* ```
|
|
448
|
+
*
|
|
449
|
+
* ## Return Values (Normalized):
|
|
450
|
+
* - **1.0**: Perfect alignment with similar magnitude
|
|
451
|
+
* - **0.5**: Orthogonal or neutral relationship
|
|
452
|
+
* - **0.0**: Opposite direction or very different magnitudes
|
|
453
|
+
*
|
|
454
|
+
* ## Business Use Cases:
|
|
455
|
+
* - **Recommendation systems**: When popularity (magnitude) matters
|
|
456
|
+
* - **Revenue analysis**: Quantity × Price calculations
|
|
457
|
+
* - **Weighted scoring**: Features × Importance weights
|
|
458
|
+
* - **Portfolio analysis**: Holdings × Performance
|
|
459
|
+
* - **Marketing effectiveness**: Reach × Engagement metrics
|
|
460
|
+
*
|
|
461
|
+
* ## When to Use:
|
|
462
|
+
* ✅ Magnitude is meaningful (popularity, importance, quantity)
|
|
463
|
+
* ✅ Pre-normalized vectors with semantic magnitude
|
|
464
|
+
* ✅ Weighted feature comparisons
|
|
465
|
+
* ✅ Collaborative filtering with implicit feedback
|
|
466
|
+
* ❌ Vectors with different scales
|
|
467
|
+
* ❌ When only direction matters (use cosine)
|
|
468
|
+
*
|
|
469
|
+
* @param {number[]} a - First vector
|
|
470
|
+
* @param {number[]} b - Second vector
|
|
471
|
+
* @returns {number} Normalized similarity score (0-1, where 1 = high similarity)
|
|
472
|
+
* @throws {Error} If vectors have different dimensions
|
|
473
|
+
*
|
|
474
|
+
* @protected
|
|
475
|
+
* @method
|
|
476
|
+
*/
|
|
123
477
|
DotProduct(a, b) {
|
|
124
478
|
if (a.length !== b.length) {
|
|
125
479
|
throw new Error(`Vectors must have same dimensions. Got ${a.length} and ${b.length}`);
|
|
@@ -128,10 +482,59 @@ class SimpleVectorService {
|
|
|
128
482
|
for (let i = 0; i < a.length; i++) {
|
|
129
483
|
dotProduct += a[i] * b[i];
|
|
130
484
|
}
|
|
485
|
+
// Normalize using tanh for bounded output
|
|
486
|
+
// Scale factor based on expected vector dimensions
|
|
131
487
|
const scale = Math.sqrt(a.length);
|
|
132
488
|
const normalized = Math.tanh(dotProduct / scale);
|
|
489
|
+
// Convert from [-1, 1] to [0, 1]
|
|
133
490
|
return (normalized + 1) / 2;
|
|
134
491
|
}
|
|
492
|
+
/**
|
|
493
|
+
* Calculates Jaccard similarity between two vectors treated as sets.
|
|
494
|
+
*
|
|
495
|
+
* ## What is Jaccard Similarity?
|
|
496
|
+
* Jaccard similarity (Jaccard index) measures the similarity between two sets
|
|
497
|
+
* as the size of their intersection divided by the size of their union.
|
|
498
|
+
* For vectors, non-zero elements are treated as "present" in the set.
|
|
499
|
+
*
|
|
500
|
+
* ## Mathematical Formula:
|
|
501
|
+
* ```
|
|
502
|
+
* jaccard = |A ∩ B| / |A ∪ B|
|
|
503
|
+
* where A and B are sets of non-zero indices
|
|
504
|
+
* ```
|
|
505
|
+
*
|
|
506
|
+
* ## Return Values:
|
|
507
|
+
* - **1.0**: Identical sets (same non-zero positions)
|
|
508
|
+
* - **0.5**: Half of combined elements are shared
|
|
509
|
+
* - **0.0**: No overlap (completely different sets)
|
|
510
|
+
*
|
|
511
|
+
* ## Business Use Cases:
|
|
512
|
+
* - **Customer behavior**: Products purchased, features used
|
|
513
|
+
* - **Document similarity**: Presence/absence of keywords
|
|
514
|
+
* - **Market basket**: Product co-occurrence analysis
|
|
515
|
+
* - **User permissions**: Comparing access control sets
|
|
516
|
+
* - **Tag similarity**: Comparing item categorizations
|
|
517
|
+
*
|
|
518
|
+
* ## When to Use:
|
|
519
|
+
* ✅ Binary or categorical data (presence/absence)
|
|
520
|
+
* ✅ Sparse vectors where zeros mean "not present"
|
|
521
|
+
* ✅ Set membership comparisons
|
|
522
|
+
* ✅ When magnitude doesn't matter, only presence
|
|
523
|
+
* ❌ Continuous numeric features
|
|
524
|
+
* ❌ Dense embeddings
|
|
525
|
+
*
|
|
526
|
+
* ## Note on Sparse Vectors:
|
|
527
|
+
* This implementation treats 0 as absence and any non-zero as presence.
|
|
528
|
+
* This is suitable for sparse representations where 0 explicitly means "not in set".
|
|
529
|
+
*
|
|
530
|
+
* @param {number[]} a - First vector (treated as set)
|
|
531
|
+
* @param {number[]} b - Second vector (treated as set)
|
|
532
|
+
* @returns {number} Jaccard similarity (0-1, where 1 = identical sets)
|
|
533
|
+
* @throws {Error} If vectors have different dimensions
|
|
534
|
+
*
|
|
535
|
+
* @protected
|
|
536
|
+
* @method
|
|
537
|
+
*/
|
|
135
538
|
JaccardSimilarity(a, b) {
|
|
136
539
|
if (a.length !== b.length) {
|
|
137
540
|
throw new Error(`Vectors must have same dimensions. Got ${a.length} and ${b.length}`);
|
|
@@ -148,11 +551,58 @@ class SimpleVectorService {
|
|
|
148
551
|
union++;
|
|
149
552
|
}
|
|
150
553
|
}
|
|
554
|
+
// Handle edge case: both vectors are all zeros
|
|
151
555
|
if (union === 0) {
|
|
152
|
-
return 1;
|
|
556
|
+
return 1; // Consider empty sets as identical
|
|
153
557
|
}
|
|
154
558
|
return intersection / union;
|
|
155
559
|
}
|
|
560
|
+
/**
|
|
561
|
+
* Calculates Hamming distance between two vectors, normalized to similarity score.
|
|
562
|
+
*
|
|
563
|
+
* ## What is Hamming Distance?
|
|
564
|
+
* Hamming distance counts the number of positions where two vectors differ.
|
|
565
|
+
* Originally designed for error detection in telecommunications, it's useful
|
|
566
|
+
* for comparing categorical data or binary strings.
|
|
567
|
+
*
|
|
568
|
+
* ## Mathematical Formula:
|
|
569
|
+
* ```
|
|
570
|
+
* hamming_distance = count(a[i] ≠ b[i])
|
|
571
|
+
* similarity = 1 - (hamming_distance / vector_length)
|
|
572
|
+
* ```
|
|
573
|
+
*
|
|
574
|
+
* ## Return Values (Normalized):
|
|
575
|
+
* - **1.0**: Identical vectors (no differences)
|
|
576
|
+
* - **0.5**: Half of positions differ
|
|
577
|
+
* - **0.0**: All positions differ
|
|
578
|
+
*
|
|
579
|
+
* ## Business Use Cases:
|
|
580
|
+
* - **Data quality**: Detecting errors in data entry
|
|
581
|
+
* - **A/B testing**: Comparing feature flags or configurations
|
|
582
|
+
* - **Fraud detection**: Unusual patterns in categorical attributes
|
|
583
|
+
* - **Product variants**: Comparing product configurations
|
|
584
|
+
* - **System monitoring**: Configuration drift detection
|
|
585
|
+
*
|
|
586
|
+
* ## When to Use:
|
|
587
|
+
* ✅ Categorical data comparison
|
|
588
|
+
* ✅ Binary feature vectors
|
|
589
|
+
* ✅ Error detection and correction
|
|
590
|
+
* ✅ Fixed-length codes or identifiers
|
|
591
|
+
* ❌ Continuous numeric features
|
|
592
|
+
* ❌ When magnitude of difference matters
|
|
593
|
+
*
|
|
594
|
+
* ## Note on Continuous Values:
|
|
595
|
+
* For continuous values, this uses exact equality. Consider binning
|
|
596
|
+
* continuous values first if approximate matching is needed.
|
|
597
|
+
*
|
|
598
|
+
* @param {number[]} a - First vector
|
|
599
|
+
* @param {number[]} b - Second vector
|
|
600
|
+
* @returns {number} Normalized similarity (0-1, where 1 = identical)
|
|
601
|
+
* @throws {Error} If vectors have different dimensions
|
|
602
|
+
*
|
|
603
|
+
* @protected
|
|
604
|
+
* @method
|
|
605
|
+
*/
|
|
156
606
|
HammingDistance(a, b) {
|
|
157
607
|
if (a.length !== b.length) {
|
|
158
608
|
throw new Error(`Vectors must have same dimensions. Got ${a.length} and ${b.length}`);
|
|
@@ -163,11 +613,31 @@ class SimpleVectorService {
|
|
|
163
613
|
differences++;
|
|
164
614
|
}
|
|
165
615
|
}
|
|
616
|
+
// Normalize to similarity score (1 = identical, 0 = all different)
|
|
166
617
|
return 1 - (differences / a.length);
|
|
167
618
|
}
|
|
619
|
+
/**
|
|
620
|
+
* Calculates distance/similarity between two vectors using the specified metric.
|
|
621
|
+
* All metrics are normalized to 0-1 range where 1 indicates highest similarity.
|
|
622
|
+
*
|
|
623
|
+
* @param {number[]} a - First vector
|
|
624
|
+
* @param {number[]} b - Second vector
|
|
625
|
+
* @param {DistanceMetric} [metric='cosine'] - The metric to use
|
|
626
|
+
* @returns {number} Normalized similarity score (0-1)
|
|
627
|
+
* @throws {Error} If vectors have different dimensions or invalid metric
|
|
628
|
+
*
|
|
629
|
+
* @example
|
|
630
|
+
* ```typescript
|
|
631
|
+
* const similarity = service.CalculateDistance(vec1, vec2, 'euclidean');
|
|
632
|
+
* ```
|
|
633
|
+
*
|
|
634
|
+
* @public
|
|
635
|
+
* @method
|
|
636
|
+
*/
|
|
168
637
|
CalculateDistance(a, b, metric = 'cosine') {
|
|
169
638
|
switch (metric) {
|
|
170
639
|
case 'cosine':
|
|
640
|
+
// Convert from [-1, 1] to [0, 1]
|
|
171
641
|
return (this.CosineSimilarity(a, b) + 1) / 2;
|
|
172
642
|
case 'euclidean':
|
|
173
643
|
return this.EuclideanDistance(a, b);
|
|
@@ -183,32 +653,258 @@ class SimpleVectorService {
|
|
|
183
653
|
throw new Error(`Unknown distance metric: ${metric}`);
|
|
184
654
|
}
|
|
185
655
|
}
|
|
656
|
+
/**
|
|
657
|
+
* Gets the current number of vectors in the service
|
|
658
|
+
*
|
|
659
|
+
* @returns {number} The number of vectors currently loaded
|
|
660
|
+
*
|
|
661
|
+
* @public
|
|
662
|
+
* @readonly
|
|
663
|
+
*/
|
|
186
664
|
get Size() {
|
|
187
665
|
return this.vectors.size;
|
|
188
666
|
}
|
|
667
|
+
/**
|
|
668
|
+
* Clears all vectors from memory
|
|
669
|
+
*
|
|
670
|
+
* @example
|
|
671
|
+
* ```typescript
|
|
672
|
+
* service.Clear();
|
|
673
|
+
* console.log(service.Size); // 0
|
|
674
|
+
* ```
|
|
675
|
+
*
|
|
676
|
+
* @public
|
|
677
|
+
* @method
|
|
678
|
+
*/
|
|
189
679
|
Clear() {
|
|
190
680
|
this.vectors.clear();
|
|
191
681
|
}
|
|
682
|
+
/**
|
|
683
|
+
* Checks if a vector with the given key exists
|
|
684
|
+
*
|
|
685
|
+
* @param {string} key - The key to check
|
|
686
|
+
* @returns {boolean} True if the key exists, false otherwise
|
|
687
|
+
*
|
|
688
|
+
* @example
|
|
689
|
+
* ```typescript
|
|
690
|
+
* if (service.Has('product123')) {
|
|
691
|
+
* console.log('Product vector exists');
|
|
692
|
+
* }
|
|
693
|
+
* ```
|
|
694
|
+
*
|
|
695
|
+
* @public
|
|
696
|
+
* @method
|
|
697
|
+
*/
|
|
192
698
|
Has(key) {
|
|
193
699
|
return this.vectors.has(key);
|
|
194
700
|
}
|
|
701
|
+
/**
|
|
702
|
+
* Retrieves a specific vector by its key
|
|
703
|
+
*
|
|
704
|
+
* @param {string} key - The key of the vector to retrieve
|
|
705
|
+
* @returns {number[] | undefined} The vector array, or undefined if not found
|
|
706
|
+
*
|
|
707
|
+
* @example
|
|
708
|
+
* ```typescript
|
|
709
|
+
* const vector = service.GetVector('product123');
|
|
710
|
+
* if (vector) {
|
|
711
|
+
* console.log(`Vector dimensions: ${vector.length}`);
|
|
712
|
+
* }
|
|
713
|
+
* ```
|
|
714
|
+
*
|
|
715
|
+
* @public
|
|
716
|
+
* @method
|
|
717
|
+
*/
|
|
195
718
|
GetVector(key) {
|
|
196
719
|
return this.vectors.get(key)?.vector;
|
|
197
720
|
}
|
|
721
|
+
/**
|
|
722
|
+
* Retrieves the metadata associated with a specific vector
|
|
723
|
+
*
|
|
724
|
+
* @param {string} key - The key of the vector
|
|
725
|
+
* @returns {TMetadata | undefined} The metadata, or undefined if not found
|
|
726
|
+
*
|
|
727
|
+
* @example
|
|
728
|
+
* ```typescript
|
|
729
|
+
* const metadata = service.GetMetadata('product123');
|
|
730
|
+
* if (metadata) {
|
|
731
|
+
* console.log(`Product name: ${metadata.name}`);
|
|
732
|
+
* }
|
|
733
|
+
* ```
|
|
734
|
+
*
|
|
735
|
+
* @public
|
|
736
|
+
* @method
|
|
737
|
+
*/
|
|
198
738
|
GetMetadata(key) {
|
|
199
739
|
return this.vectors.get(key)?.metadata;
|
|
200
740
|
}
|
|
741
|
+
/**
|
|
742
|
+
* Updates an existing vector entry in-place, allowing partial updates to the vector data,
|
|
743
|
+
* metadata, or both without removing and re-adding the entry. Unlike {@link AddVector}, this
|
|
744
|
+
* method requires the key to already exist and will throw if it does not.
|
|
745
|
+
*
|
|
746
|
+
* This is useful when you need to:
|
|
747
|
+
* - Update the embedding for an existing key after re-encoding (e.g., content changed)
|
|
748
|
+
* - Patch metadata without touching the vector data
|
|
749
|
+
* - Atomically update both vector and metadata in a single call
|
|
750
|
+
*
|
|
751
|
+
* @param {string} key - The unique identifier of the vector to update. Must already exist.
|
|
752
|
+
* @param {Object} updates - The fields to update. At least one of `vector` or `metadata` must be provided.
|
|
753
|
+
* @param {number[]} [updates.vector] - New vector/embedding to replace the existing one.
|
|
754
|
+
* Must match the expected dimensions of the service.
|
|
755
|
+
* @param {TMetadata} [updates.metadata] - New metadata to replace the existing metadata.
|
|
756
|
+
* @returns {boolean} True if the update was applied successfully
|
|
757
|
+
* @throws {Error} If the key does not exist in the service
|
|
758
|
+
* @throws {Error} If neither `vector` nor `metadata` is provided
|
|
759
|
+
* @throws {Error} If the new vector has mismatched dimensions
|
|
760
|
+
*
|
|
761
|
+
* @example
|
|
762
|
+
* ```typescript
|
|
763
|
+
* // Update only the vector (e.g., after re-embedding content)
|
|
764
|
+
* service.UpdateVector('doc123', { vector: newEmbedding });
|
|
765
|
+
*
|
|
766
|
+
* // Update only metadata (e.g., status changed)
|
|
767
|
+
* service.UpdateVector('doc123', { metadata: { title: 'Updated Title', status: 'reviewed' } });
|
|
768
|
+
*
|
|
769
|
+
* // Update both vector and metadata atomically
|
|
770
|
+
* service.UpdateVector('doc123', {
|
|
771
|
+
* vector: newEmbedding,
|
|
772
|
+
* metadata: { title: 'Updated Title', version: 2 }
|
|
773
|
+
* });
|
|
774
|
+
* ```
|
|
775
|
+
*
|
|
776
|
+
* @public
|
|
777
|
+
* @method
|
|
778
|
+
*/
|
|
779
|
+
UpdateVector(key, updates) {
|
|
780
|
+
const existing = this.vectors.get(key);
|
|
781
|
+
if (!existing) {
|
|
782
|
+
throw new Error(`Vector with key "${key}" not found. Use AddVector to create new entries.`);
|
|
783
|
+
}
|
|
784
|
+
if (updates.vector == null && updates.metadata == null) {
|
|
785
|
+
throw new Error('At least one of vector or metadata must be provided for an update');
|
|
786
|
+
}
|
|
787
|
+
if (updates.vector != null) {
|
|
788
|
+
if (updates.vector.length === 0) {
|
|
789
|
+
throw new Error('Vector cannot be empty');
|
|
790
|
+
}
|
|
791
|
+
this.validateAndSetDimensions(updates.vector);
|
|
792
|
+
existing.vector = updates.vector;
|
|
793
|
+
}
|
|
794
|
+
if (updates.metadata != null) {
|
|
795
|
+
existing.metadata = updates.metadata;
|
|
796
|
+
}
|
|
797
|
+
return true;
|
|
798
|
+
}
|
|
799
|
+
/**
|
|
800
|
+
* Adds a new vector or updates an existing one based on whether the key already exists.
|
|
801
|
+
* If the key does not exist, a new entry is created. If the key already exists, the
|
|
802
|
+
* vector and/or metadata are updated in place.
|
|
803
|
+
*
|
|
804
|
+
* @param {string} key - The unique identifier for the vector
|
|
805
|
+
* @param {number[]} vector - The vector/embedding array
|
|
806
|
+
* @param {TMetadata} [metadata] - Optional metadata to associate with the vector
|
|
807
|
+
* @returns {boolean} True if an existing vector was updated, false if a new vector was added
|
|
808
|
+
* @throws {Error} If key is null/undefined, or if vector is invalid
|
|
809
|
+
*
|
|
810
|
+
* @example
|
|
811
|
+
* ```typescript
|
|
812
|
+
* // First call creates the entry
|
|
813
|
+
* const wasUpdate = service.AddOrUpdateVector('doc1', [0.1, 0.2, 0.3], { title: 'Doc 1' });
|
|
814
|
+
* console.log(wasUpdate); // false (new entry)
|
|
815
|
+
*
|
|
816
|
+
* // Second call updates the existing entry
|
|
817
|
+
* const wasUpdate2 = service.AddOrUpdateVector('doc1', [0.4, 0.5, 0.6], { title: 'Doc 1 v2' });
|
|
818
|
+
* console.log(wasUpdate2); // true (updated)
|
|
819
|
+
* ```
|
|
820
|
+
*
|
|
821
|
+
* @public
|
|
822
|
+
* @method
|
|
823
|
+
*/
|
|
824
|
+
AddOrUpdateVector(key, vector, metadata) {
|
|
825
|
+
if (!key) {
|
|
826
|
+
throw new Error('Key cannot be null or undefined');
|
|
827
|
+
}
|
|
828
|
+
if (!vector || vector.length === 0) {
|
|
829
|
+
throw new Error('Vector cannot be null, undefined, or empty');
|
|
830
|
+
}
|
|
831
|
+
const exists = this.vectors.has(key);
|
|
832
|
+
if (exists) {
|
|
833
|
+
this.UpdateVector(key, { vector, metadata });
|
|
834
|
+
}
|
|
835
|
+
else {
|
|
836
|
+
this.AddVector(key, vector, metadata);
|
|
837
|
+
}
|
|
838
|
+
return exists;
|
|
839
|
+
}
|
|
840
|
+
/**
|
|
841
|
+
* Removes a vector from the service
|
|
842
|
+
*
|
|
843
|
+
* @param {string} key - The key of the vector to remove
|
|
844
|
+
* @returns {boolean} True if the vector was removed, false if it didn't exist
|
|
845
|
+
*
|
|
846
|
+
* @example
|
|
847
|
+
* ```typescript
|
|
848
|
+
* if (service.RemoveVector('product123')) {
|
|
849
|
+
* console.log('Vector removed successfully');
|
|
850
|
+
* }
|
|
851
|
+
* ```
|
|
852
|
+
*
|
|
853
|
+
* @public
|
|
854
|
+
* @method
|
|
855
|
+
*/
|
|
201
856
|
RemoveVector(key) {
|
|
202
857
|
return this.vectors.delete(key);
|
|
203
858
|
}
|
|
859
|
+
/**
|
|
860
|
+
* Gets all keys currently stored in the service
|
|
861
|
+
*
|
|
862
|
+
* @returns {string[]} Array of all vector keys
|
|
863
|
+
*
|
|
864
|
+
* @example
|
|
865
|
+
* ```typescript
|
|
866
|
+
* const allKeys = service.GetAllKeys();
|
|
867
|
+
* console.log(`Total vectors: ${allKeys.length}`);
|
|
868
|
+
* ```
|
|
869
|
+
*
|
|
870
|
+
* @public
|
|
871
|
+
* @method
|
|
872
|
+
*/
|
|
204
873
|
GetAllKeys() {
|
|
205
874
|
return Array.from(this.vectors.keys());
|
|
206
875
|
}
|
|
876
|
+
/**
|
|
877
|
+
* Exports all vectors as an array of VectorEntry objects.
|
|
878
|
+
* Useful for persistence or transferring data.
|
|
879
|
+
*
|
|
880
|
+
* @returns {VectorEntry<TMetadata>[]} Array of all vector entries
|
|
881
|
+
*
|
|
882
|
+
* @example
|
|
883
|
+
* ```typescript
|
|
884
|
+
* const allVectors = service.ExportVectors();
|
|
885
|
+
* // Save to database or file
|
|
886
|
+
* await saveToDatabase(allVectors);
|
|
887
|
+
* ```
|
|
888
|
+
*
|
|
889
|
+
* @public
|
|
890
|
+
* @method
|
|
891
|
+
*/
|
|
207
892
|
ExportVectors() {
|
|
208
893
|
return Array.from(this.vectors.values());
|
|
209
894
|
}
|
|
895
|
+
/**
|
|
896
|
+
* Validates vector dimensions and sets expected dimensions if not yet set.
|
|
897
|
+
* Ensures all vectors have consistent dimensions for valid similarity calculations.
|
|
898
|
+
*
|
|
899
|
+
* @param {number[]} vector - The vector to validate
|
|
900
|
+
* @throws {Error} If vector dimensions don't match expected dimensions
|
|
901
|
+
*
|
|
902
|
+
* @private
|
|
903
|
+
* @method
|
|
904
|
+
*/
|
|
210
905
|
validateAndSetDimensions(vector) {
|
|
211
906
|
if (this.expectedDimensions === null) {
|
|
907
|
+
// First vector sets the expected dimensions
|
|
212
908
|
this.expectedDimensions = vector.length;
|
|
213
909
|
}
|
|
214
910
|
else if (vector.length !== this.expectedDimensions) {
|
|
@@ -216,12 +912,93 @@ class SimpleVectorService {
|
|
|
216
912
|
`All vectors must have the same number of dimensions for similarity calculations to work.`);
|
|
217
913
|
}
|
|
218
914
|
}
|
|
915
|
+
/**
|
|
916
|
+
* Gets the expected vector dimensions for this service instance
|
|
917
|
+
*
|
|
918
|
+
* @returns {number | null} The expected dimensions, or null if no vectors loaded yet
|
|
919
|
+
*
|
|
920
|
+
* @public
|
|
921
|
+
* @readonly
|
|
922
|
+
*/
|
|
219
923
|
get ExpectedDimensions() {
|
|
220
924
|
return this.expectedDimensions;
|
|
221
925
|
}
|
|
926
|
+
/**
|
|
927
|
+
* Finds all vectors with similarity above a threshold
|
|
928
|
+
*
|
|
929
|
+
* @param {number[]} queryVector - The vector to search for similar items
|
|
930
|
+
* @param {number} threshold - Minimum similarity threshold (0-1)
|
|
931
|
+
* @param {DistanceMetric} [metric='cosine'] - The distance metric to use
|
|
932
|
+
* @param {(metadata: TMetadata) => boolean} [filter] - Optional filter to pre-filter vectors by metadata before similarity calculation
|
|
933
|
+
* @returns {VectorSearchResult<TMetadata>[]} Array of search results sorted by similarity
|
|
934
|
+
*
|
|
935
|
+
* @example
|
|
936
|
+
* ```typescript
|
|
937
|
+
* // Find all highly similar items (similarity > 0.8)
|
|
938
|
+
* const similar = service.FindAboveThreshold(queryVector, 0.8);
|
|
939
|
+
*
|
|
940
|
+
* // Find all items with Jaccard similarity > 0.5
|
|
941
|
+
* const matches = service.FindAboveThreshold(features, 0.5, 'jaccard');
|
|
942
|
+
*
|
|
943
|
+
* // Find all similar items in a specific category
|
|
944
|
+
* const categoryMatches = service.FindAboveThreshold(
|
|
945
|
+
* queryVector,
|
|
946
|
+
* 0.7,
|
|
947
|
+
* 'cosine',
|
|
948
|
+
* (metadata) => metadata.status === 'Active'
|
|
949
|
+
* );
|
|
950
|
+
* ```
|
|
951
|
+
*
|
|
952
|
+
* @public
|
|
953
|
+
* @method
|
|
954
|
+
*/
|
|
222
955
|
FindAboveThreshold(queryVector, threshold, metric = 'cosine', filter) {
|
|
223
956
|
return this.FindNearest(queryVector, this.vectors.size, threshold, metric, filter);
|
|
224
957
|
}
|
|
958
|
+
// ============================================================================
|
|
959
|
+
// PHASE 2: CLUSTERING ALGORITHMS
|
|
960
|
+
// ============================================================================
|
|
961
|
+
/**
|
|
962
|
+
* Performs K-Means clustering on the loaded vectors.
|
|
963
|
+
* Uses K-Means++ initialization for better starting centroids.
|
|
964
|
+
*
|
|
965
|
+
* ## What is K-Means Clustering?
|
|
966
|
+
* K-Means divides vectors into K clusters by minimizing within-cluster variance.
|
|
967
|
+
* Each vector is assigned to the nearest centroid, and centroids are iteratively updated.
|
|
968
|
+
*
|
|
969
|
+
* ## Business Use Cases:
|
|
970
|
+
* - **Customer Segmentation**: Group customers by behavior patterns
|
|
971
|
+
* - **Product Categorization**: Organize products into natural groups
|
|
972
|
+
* - **Market Segmentation**: Identify distinct market segments
|
|
973
|
+
* - **Anomaly Detection**: Identify unusual patterns (far from all centroids)
|
|
974
|
+
* - **Document Organization**: Group similar documents together
|
|
975
|
+
*
|
|
976
|
+
* ## When to Use:
|
|
977
|
+
* ✅ Known or estimated number of clusters
|
|
978
|
+
* ✅ Spherical, well-separated clusters
|
|
979
|
+
* ✅ Similar cluster sizes
|
|
980
|
+
* ✅ Need interpretable centroids
|
|
981
|
+
* ❌ Non-spherical clusters
|
|
982
|
+
* ❌ Varying cluster densities
|
|
983
|
+
* ❌ Unknown number of clusters
|
|
984
|
+
*
|
|
985
|
+
* @param {number} k - Number of clusters
|
|
986
|
+
* @param {number} [maxIterations=100] - Maximum iterations before stopping
|
|
987
|
+
* @param {DistanceMetric} [metric='euclidean'] - Distance metric to use
|
|
988
|
+
* @param {number} [tolerance=0.0001] - Convergence tolerance
|
|
989
|
+
* @returns {ClusterResult<TMetadata>} Clustering results with assignments and centroids
|
|
990
|
+
*
|
|
991
|
+
* @example
|
|
992
|
+
* ```typescript
|
|
993
|
+
* const result = service.KMeansCluster(3, 100, 'euclidean');
|
|
994
|
+
* result.clusters.forEach((members, clusterId) => {
|
|
995
|
+
* console.log(`Cluster ${clusterId}: ${members.length} members`);
|
|
996
|
+
* });
|
|
997
|
+
* ```
|
|
998
|
+
*
|
|
999
|
+
* @public
|
|
1000
|
+
* @method
|
|
1001
|
+
*/
|
|
225
1002
|
KMeansCluster(k, maxIterations = 100, metric = 'euclidean', tolerance = 0.0001) {
|
|
226
1003
|
if (k <= 0 || k > this.vectors.size) {
|
|
227
1004
|
throw new Error(`Invalid k: ${k}. Must be between 1 and ${this.vectors.size}`);
|
|
@@ -230,11 +1007,13 @@ class SimpleVectorService {
|
|
|
230
1007
|
if (entries.length === 0) {
|
|
231
1008
|
throw new Error('No vectors loaded for clustering');
|
|
232
1009
|
}
|
|
1010
|
+
// Initialize centroids using K-Means++
|
|
233
1011
|
const centroids = this.initializeKMeansPlusPlus(entries, k, metric);
|
|
234
1012
|
let assignments = new Map();
|
|
235
1013
|
let iterations = 0;
|
|
236
1014
|
let converged = false;
|
|
237
1015
|
while (iterations < maxIterations && !converged) {
|
|
1016
|
+
// Assignment step: assign each point to nearest centroid
|
|
238
1017
|
const newAssignments = new Map();
|
|
239
1018
|
entries.forEach(entry => {
|
|
240
1019
|
let minDistance = Infinity;
|
|
@@ -248,9 +1027,11 @@ class SimpleVectorService {
|
|
|
248
1027
|
});
|
|
249
1028
|
newAssignments.set(entry.key, assignedCluster);
|
|
250
1029
|
});
|
|
1030
|
+
// Check for convergence
|
|
251
1031
|
converged = this.checkConvergence(assignments, newAssignments);
|
|
252
1032
|
assignments = newAssignments;
|
|
253
1033
|
if (!converged) {
|
|
1034
|
+
// Update step: recalculate centroids
|
|
254
1035
|
const newCentroids = new Map();
|
|
255
1036
|
for (let clusterId = 0; clusterId < k; clusterId++) {
|
|
256
1037
|
const clusterMembers = entries.filter(e => assignments.get(e.key) === clusterId);
|
|
@@ -258,9 +1039,11 @@ class SimpleVectorService {
|
|
|
258
1039
|
newCentroids.set(clusterId, this.FindCentroid(clusterMembers.map(m => m.vector)));
|
|
259
1040
|
}
|
|
260
1041
|
else {
|
|
1042
|
+
// Empty cluster - keep old centroid
|
|
261
1043
|
newCentroids.set(clusterId, centroids.get(clusterId));
|
|
262
1044
|
}
|
|
263
1045
|
}
|
|
1046
|
+
// Check if centroids moved significantly
|
|
264
1047
|
let maxCentroidMovement = 0;
|
|
265
1048
|
newCentroids.forEach((newCentroid, clusterId) => {
|
|
266
1049
|
const oldCentroid = centroids.get(clusterId);
|
|
@@ -275,6 +1058,7 @@ class SimpleVectorService {
|
|
|
275
1058
|
}
|
|
276
1059
|
iterations++;
|
|
277
1060
|
}
|
|
1061
|
+
// Build result
|
|
278
1062
|
const clusters = new Map();
|
|
279
1063
|
for (let i = 0; i < k; i++) {
|
|
280
1064
|
clusters.set(i, []);
|
|
@@ -282,6 +1066,7 @@ class SimpleVectorService {
|
|
|
282
1066
|
assignments.forEach((clusterId, key) => {
|
|
283
1067
|
clusters.get(clusterId).push(key);
|
|
284
1068
|
});
|
|
1069
|
+
// Calculate inertia (sum of squared distances to centroids)
|
|
285
1070
|
let inertia = 0;
|
|
286
1071
|
entries.forEach(entry => {
|
|
287
1072
|
const clusterId = assignments.get(entry.key);
|
|
@@ -300,10 +1085,18 @@ class SimpleVectorService {
|
|
|
300
1085
|
}
|
|
301
1086
|
};
|
|
302
1087
|
}
|
|
1088
|
+
/**
|
|
1089
|
+
* K-Means++ initialization for better starting centroids.
|
|
1090
|
+
* Chooses initial centroids that are far apart from each other.
|
|
1091
|
+
*
|
|
1092
|
+
* @private
|
|
1093
|
+
*/
|
|
303
1094
|
initializeKMeansPlusPlus(entries, k, metric) {
|
|
304
1095
|
const centroids = new Map();
|
|
1096
|
+
// Choose first centroid randomly
|
|
305
1097
|
const firstIdx = Math.floor(Math.random() * entries.length);
|
|
306
1098
|
centroids.set(0, [...entries[firstIdx].vector]);
|
|
1099
|
+
// Choose remaining centroids
|
|
307
1100
|
for (let i = 1; i < k; i++) {
|
|
308
1101
|
const distances = entries.map(entry => {
|
|
309
1102
|
let minDist = Infinity;
|
|
@@ -313,6 +1106,7 @@ class SimpleVectorService {
|
|
|
313
1106
|
});
|
|
314
1107
|
return minDist;
|
|
315
1108
|
});
|
|
1109
|
+
// Choose next centroid with probability proportional to squared distance
|
|
316
1110
|
const sumSquaredDist = distances.reduce((sum, d) => sum + d * d, 0);
|
|
317
1111
|
let threshold = Math.random() * sumSquaredDist;
|
|
318
1112
|
let cumSum = 0;
|
|
@@ -326,6 +1120,10 @@ class SimpleVectorService {
|
|
|
326
1120
|
}
|
|
327
1121
|
return centroids;
|
|
328
1122
|
}
|
|
1123
|
+
/**
|
|
1124
|
+
* Check if cluster assignments have converged
|
|
1125
|
+
* @private
|
|
1126
|
+
*/
|
|
329
1127
|
checkConvergence(oldAssignments, newAssignments) {
|
|
330
1128
|
if (oldAssignments.size !== newAssignments.size)
|
|
331
1129
|
return false;
|
|
@@ -336,6 +1134,55 @@ class SimpleVectorService {
|
|
|
336
1134
|
}
|
|
337
1135
|
return true;
|
|
338
1136
|
}
|
|
1137
|
+
/**
|
|
1138
|
+
* Performs DBSCAN (Density-Based Spatial Clustering of Applications with Noise) clustering.
|
|
1139
|
+
*
|
|
1140
|
+
* ## What is DBSCAN?
|
|
1141
|
+
* DBSCAN groups together points that are closely packed together (high density),
|
|
1142
|
+
* marking points in low-density regions as outliers. Unlike K-Means, it doesn't require
|
|
1143
|
+
* specifying the number of clusters beforehand.
|
|
1144
|
+
*
|
|
1145
|
+
* ## Business Use Cases:
|
|
1146
|
+
* - **Fraud Detection**: Identify unusual transaction patterns
|
|
1147
|
+
* - **Anomaly Detection**: Find outliers in any dataset
|
|
1148
|
+
* - **Customer Behavior**: Find natural groupings without preconceptions
|
|
1149
|
+
* - **Geographic Clustering**: Find areas of high activity
|
|
1150
|
+
* - **Quality Control**: Identify defective products
|
|
1151
|
+
*
|
|
1152
|
+
* ## When to Use:
|
|
1153
|
+
* ✅ Unknown number of clusters
|
|
1154
|
+
* ✅ Non-spherical clusters
|
|
1155
|
+
* ✅ Varying cluster densities
|
|
1156
|
+
* ✅ Need to identify outliers
|
|
1157
|
+
* ✅ Noise in the data
|
|
1158
|
+
* ❌ High-dimensional sparse data
|
|
1159
|
+
* ❌ Clusters of vastly different densities
|
|
1160
|
+
*
|
|
1161
|
+
* @param {number} epsilon - Maximum distance between two vectors to be considered neighbors
|
|
1162
|
+
* @param {number} minPoints - Minimum number of points to form a dense region
|
|
1163
|
+
* @param {DistanceMetric} [metric='euclidean'] - Distance metric to use
|
|
1164
|
+
* @param {(metadata: TMetadata) => boolean} [filter] - Optional filter to pre-filter vectors by metadata before clustering
|
|
1165
|
+
* @returns {ClusterResult<TMetadata>} Clustering results with outliers identified
|
|
1166
|
+
*
|
|
1167
|
+
* @example
|
|
1168
|
+
* ```typescript
|
|
1169
|
+
* // epsilon=0.3 means similarity must be > 0.7
|
|
1170
|
+
* const result = service.DBSCANCluster(0.3, 3, 'cosine');
|
|
1171
|
+
* console.log(`Found ${result.clusters.size} clusters`);
|
|
1172
|
+
* console.log(`Outliers: ${result.outliers?.length || 0}`);
|
|
1173
|
+
*
|
|
1174
|
+
* // Cluster only active items
|
|
1175
|
+
* const activeResult = service.DBSCANCluster(
|
|
1176
|
+
* 0.3,
|
|
1177
|
+
* 3,
|
|
1178
|
+
* 'cosine',
|
|
1179
|
+
* (metadata) => metadata.status === 'Active'
|
|
1180
|
+
* );
|
|
1181
|
+
* ```
|
|
1182
|
+
*
|
|
1183
|
+
* @public
|
|
1184
|
+
* @method
|
|
1185
|
+
*/
|
|
339
1186
|
DBSCANCluster(epsilon, minPoints, metric = 'euclidean', filter) {
|
|
340
1187
|
if (epsilon <= 0 || epsilon >= 1) {
|
|
341
1188
|
throw new Error('Epsilon must be between 0 and 1 (exclusive)');
|
|
@@ -343,6 +1190,7 @@ class SimpleVectorService {
|
|
|
343
1190
|
if (minPoints <= 0) {
|
|
344
1191
|
throw new Error('MinPoints must be positive');
|
|
345
1192
|
}
|
|
1193
|
+
// Pre-filter vectors if filter provided
|
|
346
1194
|
const entries = filter
|
|
347
1195
|
? Array.from(this.vectors.values()).filter(entry => entry.metadata && filter(entry.metadata))
|
|
348
1196
|
: Array.from(this.vectors.values());
|
|
@@ -351,26 +1199,34 @@ class SimpleVectorService {
|
|
|
351
1199
|
const clusters = new Map();
|
|
352
1200
|
const outliers = [];
|
|
353
1201
|
let clusterId = 0;
|
|
1202
|
+
// Build neighborhood map for efficiency (using filtered entries)
|
|
354
1203
|
const neighborhoods = new Map();
|
|
355
1204
|
entries.forEach(entry => {
|
|
356
|
-
const neighbors = this.FindNearest(entry.vector, entries.length,
|
|
1205
|
+
const neighbors = this.FindNearest(entry.vector, entries.length, // Search within filtered space
|
|
1206
|
+
1 - epsilon, // Convert epsilon to similarity threshold
|
|
1207
|
+
metric, filter // Apply same filter to neighborhood search
|
|
1208
|
+
).map(r => r.key);
|
|
357
1209
|
neighborhoods.set(entry.key, neighbors);
|
|
358
1210
|
});
|
|
1211
|
+
// DBSCAN algorithm
|
|
359
1212
|
entries.forEach(entry => {
|
|
360
1213
|
if (visited.has(entry.key))
|
|
361
1214
|
return;
|
|
362
1215
|
visited.add(entry.key);
|
|
363
1216
|
const neighbors = neighborhoods.get(entry.key);
|
|
364
1217
|
if (neighbors.length < minPoints) {
|
|
1218
|
+
// Mark as noise (may later be added to a cluster)
|
|
365
1219
|
outliers.push(entry.key);
|
|
366
1220
|
}
|
|
367
1221
|
else {
|
|
1222
|
+
// Start a new cluster
|
|
368
1223
|
const cluster = [];
|
|
369
1224
|
clusters.set(clusterId, cluster);
|
|
370
1225
|
this.expandCluster(entry.key, neighbors, cluster, visited, clustered, neighborhoods, minPoints, outliers);
|
|
371
1226
|
clusterId++;
|
|
372
1227
|
}
|
|
373
1228
|
});
|
|
1229
|
+
// Remove outliers that were later added to clusters
|
|
374
1230
|
const finalOutliers = outliers.filter(key => !clustered.has(key));
|
|
375
1231
|
return {
|
|
376
1232
|
clusters,
|
|
@@ -383,6 +1239,10 @@ class SimpleVectorService {
|
|
|
383
1239
|
}
|
|
384
1240
|
};
|
|
385
1241
|
}
|
|
1242
|
+
/**
|
|
1243
|
+
* Expand a cluster in DBSCAN
|
|
1244
|
+
* @private
|
|
1245
|
+
*/
|
|
386
1246
|
expandCluster(key, neighbors, cluster, visited, clustered, neighborhoods, minPoints, outliers) {
|
|
387
1247
|
cluster.push(key);
|
|
388
1248
|
clustered.add(key);
|
|
@@ -393,6 +1253,7 @@ class SimpleVectorService {
|
|
|
393
1253
|
visited.add(neighborKey);
|
|
394
1254
|
const neighborNeighbors = neighborhoods.get(neighborKey);
|
|
395
1255
|
if (neighborNeighbors.length >= minPoints) {
|
|
1256
|
+
// Add unprocessed neighbors to queue
|
|
396
1257
|
neighborNeighbors.forEach(nn => {
|
|
397
1258
|
if (!visited.has(nn)) {
|
|
398
1259
|
queue.push(nn);
|
|
@@ -403,6 +1264,7 @@ class SimpleVectorService {
|
|
|
403
1264
|
if (!clustered.has(neighborKey)) {
|
|
404
1265
|
cluster.push(neighborKey);
|
|
405
1266
|
clustered.add(neighborKey);
|
|
1267
|
+
// Remove from outliers if it was there
|
|
406
1268
|
const outlierIdx = outliers.indexOf(neighborKey);
|
|
407
1269
|
if (outlierIdx !== -1) {
|
|
408
1270
|
outliers.splice(outlierIdx, 1);
|
|
@@ -410,6 +1272,35 @@ class SimpleVectorService {
|
|
|
410
1272
|
}
|
|
411
1273
|
}
|
|
412
1274
|
}
|
|
1275
|
+
// ============================================================================
|
|
1276
|
+
// PHASE 3: UTILITY METHODS
|
|
1277
|
+
// ============================================================================
|
|
1278
|
+
/**
|
|
1279
|
+
* Finds the centroid (mean) of a set of vectors.
|
|
1280
|
+
*
|
|
1281
|
+
* ## What is a Centroid?
|
|
1282
|
+
* A centroid is the mean position of all vectors in a group.
|
|
1283
|
+
* It represents the "center" of the cluster in vector space.
|
|
1284
|
+
*
|
|
1285
|
+
* ## Business Use Cases:
|
|
1286
|
+
* - **Representative Selection**: Find the average customer profile
|
|
1287
|
+
* - **Summarization**: Create a summary vector for a group
|
|
1288
|
+
* - **Cluster Analysis**: Understand cluster characteristics
|
|
1289
|
+
* - **Trend Analysis**: Find the average trend across time periods
|
|
1290
|
+
*
|
|
1291
|
+
* @param {number[][]} vectors - Array of vectors to find centroid of
|
|
1292
|
+
* @returns {number[]} The centroid vector
|
|
1293
|
+
*
|
|
1294
|
+
* @example
|
|
1295
|
+
* ```typescript
|
|
1296
|
+
* const vectors = [[1, 2], [3, 4], [5, 6]];
|
|
1297
|
+
* const centroid = service.FindCentroid(vectors);
|
|
1298
|
+
* // Returns [3, 4] (mean of each dimension)
|
|
1299
|
+
* ```
|
|
1300
|
+
*
|
|
1301
|
+
* @public
|
|
1302
|
+
* @method
|
|
1303
|
+
*/
|
|
413
1304
|
FindCentroid(vectors) {
|
|
414
1305
|
if (vectors.length === 0) {
|
|
415
1306
|
throw new Error('Cannot find centroid of empty vector set');
|
|
@@ -424,20 +1315,49 @@ class SimpleVectorService {
|
|
|
424
1315
|
centroid[i] += vector[i];
|
|
425
1316
|
}
|
|
426
1317
|
});
|
|
1318
|
+
// Calculate mean
|
|
427
1319
|
for (let i = 0; i < dimensions; i++) {
|
|
428
1320
|
centroid[i] /= vectors.length;
|
|
429
1321
|
}
|
|
430
1322
|
return centroid;
|
|
431
1323
|
}
|
|
1324
|
+
/**
|
|
1325
|
+
* Calculates the average within-cluster distance for a clustering result.
|
|
1326
|
+
* Lower values indicate tighter, more cohesive clusters.
|
|
1327
|
+
*
|
|
1328
|
+
* ## What is Within-Cluster Distance?
|
|
1329
|
+
* Measures how close points are to other points in the same cluster.
|
|
1330
|
+
* Also known as cluster cohesion or compactness.
|
|
1331
|
+
*
|
|
1332
|
+
* ## Business Interpretation:
|
|
1333
|
+
* - **Low value**: Tight, well-defined groups (good)
|
|
1334
|
+
* - **High value**: Loose, scattered groups (may need more clusters)
|
|
1335
|
+
*
|
|
1336
|
+
* @param {ClusterResult<TMetadata>} clusterResult - The clustering result
|
|
1337
|
+
* @param {DistanceMetric} [metric='euclidean'] - Distance metric to use
|
|
1338
|
+
* @returns {number} Average within-cluster distance (0-1, lower is better)
|
|
1339
|
+
*
|
|
1340
|
+
* @example
|
|
1341
|
+
* ```typescript
|
|
1342
|
+
* const result = service.KMeansCluster(3);
|
|
1343
|
+
* const cohesion = service.WithinClusterDistance(result);
|
|
1344
|
+
* console.log(`Cluster cohesion: ${cohesion.toFixed(3)}`);
|
|
1345
|
+
* ```
|
|
1346
|
+
*
|
|
1347
|
+
* @public
|
|
1348
|
+
* @method
|
|
1349
|
+
*/
|
|
432
1350
|
WithinClusterDistance(clusterResult, metric = 'euclidean') {
|
|
433
1351
|
let totalDistance = 0;
|
|
434
1352
|
let totalPairs = 0;
|
|
435
1353
|
clusterResult.clusters.forEach((members) => {
|
|
1354
|
+
// Calculate pairwise distances within cluster
|
|
436
1355
|
for (let i = 0; i < members.length; i++) {
|
|
437
1356
|
for (let j = i + 1; j < members.length; j++) {
|
|
438
1357
|
const vec1 = this.vectors.get(members[i])?.vector;
|
|
439
1358
|
const vec2 = this.vectors.get(members[j])?.vector;
|
|
440
1359
|
if (vec1 && vec2) {
|
|
1360
|
+
// Convert similarity to distance
|
|
441
1361
|
totalDistance += 1 - this.CalculateDistance(vec1, vec2, metric);
|
|
442
1362
|
totalPairs++;
|
|
443
1363
|
}
|
|
@@ -446,17 +1366,45 @@ class SimpleVectorService {
|
|
|
446
1366
|
});
|
|
447
1367
|
return totalPairs > 0 ? totalDistance / totalPairs : 0;
|
|
448
1368
|
}
|
|
1369
|
+
/**
|
|
1370
|
+
* Calculates the average between-cluster distance for a clustering result.
|
|
1371
|
+
* Higher values indicate better cluster separation.
|
|
1372
|
+
*
|
|
1373
|
+
* ## What is Between-Cluster Distance?
|
|
1374
|
+
* Measures how far apart different clusters are from each other.
|
|
1375
|
+
* Also known as cluster separation.
|
|
1376
|
+
*
|
|
1377
|
+
* ## Business Interpretation:
|
|
1378
|
+
* - **High value**: Well-separated groups (good)
|
|
1379
|
+
* - **Low value**: Overlapping groups (may have too many clusters)
|
|
1380
|
+
*
|
|
1381
|
+
* @param {ClusterResult<TMetadata>} clusterResult - The clustering result
|
|
1382
|
+
* @param {DistanceMetric} [metric='euclidean'] - Distance metric to use
|
|
1383
|
+
* @returns {number} Average between-cluster distance (0-1, higher is better)
|
|
1384
|
+
*
|
|
1385
|
+
* @example
|
|
1386
|
+
* ```typescript
|
|
1387
|
+
* const result = service.KMeansCluster(3);
|
|
1388
|
+
* const separation = service.BetweenClusterDistance(result);
|
|
1389
|
+
* console.log(`Cluster separation: ${separation.toFixed(3)}`);
|
|
1390
|
+
* ```
|
|
1391
|
+
*
|
|
1392
|
+
* @public
|
|
1393
|
+
* @method
|
|
1394
|
+
*/
|
|
449
1395
|
BetweenClusterDistance(clusterResult, metric = 'euclidean') {
|
|
450
1396
|
const clusterIds = Array.from(clusterResult.clusters.keys());
|
|
451
1397
|
if (clusterIds.length < 2) {
|
|
452
|
-
return 0;
|
|
1398
|
+
return 0; // No between-cluster distance with single cluster
|
|
453
1399
|
}
|
|
454
1400
|
let totalDistance = 0;
|
|
455
1401
|
let totalPairs = 0;
|
|
1402
|
+
// Calculate distances between all pairs of clusters
|
|
456
1403
|
for (let i = 0; i < clusterIds.length; i++) {
|
|
457
1404
|
for (let j = i + 1; j < clusterIds.length; j++) {
|
|
458
1405
|
const cluster1 = clusterResult.clusters.get(clusterIds[i]);
|
|
459
1406
|
const cluster2 = clusterResult.clusters.get(clusterIds[j]);
|
|
1407
|
+
// Calculate average distance between all pairs across clusters
|
|
460
1408
|
cluster1.forEach(key1 => {
|
|
461
1409
|
cluster2.forEach(key2 => {
|
|
462
1410
|
const vec1 = this.vectors.get(key1)?.vector;
|
|
@@ -471,6 +1419,39 @@ class SimpleVectorService {
|
|
|
471
1419
|
}
|
|
472
1420
|
return totalPairs > 0 ? totalDistance / totalPairs : 0;
|
|
473
1421
|
}
|
|
1422
|
+
/**
|
|
1423
|
+
* Calculates the Silhouette Score for a clustering result.
|
|
1424
|
+
* Measures how similar a point is to its own cluster compared to other clusters.
|
|
1425
|
+
*
|
|
1426
|
+
* ## What is Silhouette Score?
|
|
1427
|
+
* A measure of how appropriate the clustering is, combining both cohesion and separation.
|
|
1428
|
+
* Ranges from -1 to 1, where:
|
|
1429
|
+
* - **1**: Perfect clustering (tight, well-separated clusters)
|
|
1430
|
+
* - **0**: Overlapping clusters
|
|
1431
|
+
* - **-1**: Wrong clustering (points assigned to wrong clusters)
|
|
1432
|
+
*
|
|
1433
|
+
* ## Business Interpretation:
|
|
1434
|
+
* - **0.7-1.0**: Strong clustering structure
|
|
1435
|
+
* - **0.5-0.7**: Reasonable structure
|
|
1436
|
+
* - **0.25-0.5**: Weak structure
|
|
1437
|
+
* - **< 0.25**: No meaningful structure
|
|
1438
|
+
*
|
|
1439
|
+
* @param {ClusterResult<TMetadata>} clusterResult - The clustering result
|
|
1440
|
+
* @param {DistanceMetric} [metric='euclidean'] - Distance metric to use
|
|
1441
|
+
* @returns {number} Silhouette score (-1 to 1, higher is better)
|
|
1442
|
+
*
|
|
1443
|
+
* @example
|
|
1444
|
+
* ```typescript
|
|
1445
|
+
* const result = service.KMeansCluster(3);
|
|
1446
|
+
* const score = service.SilhouetteScore(result);
|
|
1447
|
+
* if (score > 0.7) {
|
|
1448
|
+
* console.log('Excellent clustering!');
|
|
1449
|
+
* }
|
|
1450
|
+
* ```
|
|
1451
|
+
*
|
|
1452
|
+
* @public
|
|
1453
|
+
* @method
|
|
1454
|
+
*/
|
|
474
1455
|
SilhouetteScore(clusterResult, metric = 'euclidean') {
|
|
475
1456
|
const scores = [];
|
|
476
1457
|
clusterResult.clusters.forEach((members, clusterId) => {
|
|
@@ -478,6 +1459,7 @@ class SimpleVectorService {
|
|
|
478
1459
|
const vector = this.vectors.get(key)?.vector;
|
|
479
1460
|
if (!vector)
|
|
480
1461
|
return;
|
|
1462
|
+
// Calculate a(i): average distance to other points in same cluster
|
|
481
1463
|
let a = 0;
|
|
482
1464
|
if (members.length > 1) {
|
|
483
1465
|
const sameClusterDistances = members
|
|
@@ -488,6 +1470,7 @@ class SimpleVectorService {
|
|
|
488
1470
|
});
|
|
489
1471
|
a = sameClusterDistances.reduce((sum, d) => sum + d, 0) / sameClusterDistances.length;
|
|
490
1472
|
}
|
|
1473
|
+
// Calculate b(i): minimum average distance to points in other clusters
|
|
491
1474
|
let b = Infinity;
|
|
492
1475
|
clusterResult.clusters.forEach((otherMembers, otherClusterId) => {
|
|
493
1476
|
if (otherClusterId === clusterId)
|
|
@@ -501,16 +1484,49 @@ class SimpleVectorService {
|
|
|
501
1484
|
b = Math.min(b, avgDist);
|
|
502
1485
|
}
|
|
503
1486
|
});
|
|
1487
|
+
// Calculate silhouette coefficient for this point
|
|
504
1488
|
if (b !== Infinity) {
|
|
505
1489
|
const s = (b - a) / Math.max(a, b);
|
|
506
1490
|
scores.push(s);
|
|
507
1491
|
}
|
|
508
1492
|
});
|
|
509
1493
|
});
|
|
1494
|
+
// Return average silhouette score
|
|
510
1495
|
return scores.length > 0 ?
|
|
511
1496
|
scores.reduce((sum, s) => sum + s, 0) / scores.length :
|
|
512
1497
|
0;
|
|
513
1498
|
}
|
|
1499
|
+
/**
|
|
1500
|
+
* Finds the optimal number of clusters using the elbow method.
|
|
1501
|
+
* Tests different values of k and returns their inertias.
|
|
1502
|
+
*
|
|
1503
|
+
* ## What is the Elbow Method?
|
|
1504
|
+
* A technique to find the optimal number of clusters by plotting inertia vs k.
|
|
1505
|
+
* The "elbow" point where inertia stops decreasing rapidly suggests the optimal k.
|
|
1506
|
+
*
|
|
1507
|
+
* ## How to Use:
|
|
1508
|
+
* 1. Run this method with a range of k values
|
|
1509
|
+
* 2. Plot inertia (y-axis) vs k (x-axis)
|
|
1510
|
+
* 3. Look for the "elbow" where the curve flattens
|
|
1511
|
+
* 4. Choose k at the elbow point
|
|
1512
|
+
*
|
|
1513
|
+
* @param {number} minK - Minimum number of clusters to test
|
|
1514
|
+
* @param {number} maxK - Maximum number of clusters to test
|
|
1515
|
+
* @param {DistanceMetric} [metric='euclidean'] - Distance metric to use
|
|
1516
|
+
* @returns {Map<number, number>} Map of k values to inertias
|
|
1517
|
+
*
|
|
1518
|
+
* @example
|
|
1519
|
+
* ```typescript
|
|
1520
|
+
* const elbowData = service.ElbowMethod(2, 10);
|
|
1521
|
+
* elbowData.forEach((inertia, k) => {
|
|
1522
|
+
* console.log(`k=${k}: inertia=${inertia.toFixed(2)}`);
|
|
1523
|
+
* });
|
|
1524
|
+
* // Look for the "elbow" in the results
|
|
1525
|
+
* ```
|
|
1526
|
+
*
|
|
1527
|
+
* @public
|
|
1528
|
+
* @method
|
|
1529
|
+
*/
|
|
514
1530
|
ElbowMethod(minK, maxK, metric = 'euclidean') {
|
|
515
1531
|
if (minK < 1 || maxK > this.vectors.size || minK > maxK) {
|
|
516
1532
|
throw new Error('Invalid k range');
|
|
@@ -523,5 +1539,4 @@ class SimpleVectorService {
|
|
|
523
1539
|
return results;
|
|
524
1540
|
}
|
|
525
1541
|
}
|
|
526
|
-
exports.SimpleVectorService = SimpleVectorService;
|
|
527
1542
|
//# sourceMappingURL=SimpleVectorService.js.map
|