@memberjunction/ai-vectors-memory 3.4.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,60 +1,1005 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Supported distance/similarity metrics for vector operations
|
|
3
|
+
*/
|
|
1
4
|
export type DistanceMetric = 'cosine' | 'euclidean' | 'manhattan' | 'dotproduct' | 'jaccard' | 'hamming';
|
|
5
|
+
/**
|
|
6
|
+
* Result of clustering operations
|
|
7
|
+
*/
|
|
2
8
|
export interface ClusterResult<TMetadata = Record<string, unknown>> {
|
|
9
|
+
/** Map of cluster ID to array of vector keys in that cluster */
|
|
3
10
|
clusters: Map<number, string[]>;
|
|
11
|
+
/** Map of cluster ID to centroid vector (for K-means) */
|
|
4
12
|
centroids?: Map<number, number[]>;
|
|
13
|
+
/** Array of vector keys identified as outliers (for DBSCAN) */
|
|
5
14
|
outliers?: string[];
|
|
15
|
+
/** Metadata about the clustering operation */
|
|
6
16
|
metadata?: {
|
|
17
|
+
/** Distance metric used */
|
|
7
18
|
metric: DistanceMetric;
|
|
19
|
+
/** Number of iterations until convergence */
|
|
8
20
|
iterations?: number;
|
|
21
|
+
/** Sum of squared distances to centroids (for K-means) */
|
|
9
22
|
inertia?: number;
|
|
23
|
+
/** Silhouette score (-1 to 1, higher is better) */
|
|
10
24
|
silhouetteScore?: number;
|
|
11
25
|
};
|
|
12
26
|
}
|
|
27
|
+
/**
|
|
28
|
+
* Represents a vector entry with a unique key and associated embedding
|
|
29
|
+
*/
|
|
13
30
|
export interface VectorEntry<TMetadata = Record<string, unknown>> {
|
|
31
|
+
/** User-defined unique identifier for the vector */
|
|
14
32
|
key: string;
|
|
33
|
+
/** The embedding/vector as an array of numbers */
|
|
15
34
|
vector: number[];
|
|
35
|
+
/** Optional metadata associated with the vector */
|
|
16
36
|
metadata?: TMetadata;
|
|
17
37
|
}
|
|
38
|
+
/**
|
|
39
|
+
* Search result returned from vector similarity operations
|
|
40
|
+
*/
|
|
18
41
|
export interface VectorSearchResult<TMetadata = Record<string, unknown>> {
|
|
42
|
+
/** The unique key of the matched vector */
|
|
19
43
|
key: string;
|
|
44
|
+
/** Similarity score (0-1 for cosine similarity, where 1 is most similar) */
|
|
20
45
|
score: number;
|
|
46
|
+
/** Optional metadata associated with the matched vector */
|
|
21
47
|
metadata?: TMetadata;
|
|
22
48
|
}
|
|
49
|
+
/**
|
|
50
|
+
* SimpleVectorService provides in-memory vector similarity search capabilities.
|
|
51
|
+
* This service is storage-agnostic and allows developers to manage their own vector persistence.
|
|
52
|
+
*
|
|
53
|
+
* @example
|
|
54
|
+
* ```typescript
|
|
55
|
+
* // Create service instance
|
|
56
|
+
* const vectorService = new SimpleVectorService();
|
|
57
|
+
*
|
|
58
|
+
* // Load vectors from your data source
|
|
59
|
+
* const vectors = new Map<string, number[]>();
|
|
60
|
+
* vectors.set('item1', [0.1, 0.2, 0.3]);
|
|
61
|
+
* vectors.set('item2', [0.4, 0.5, 0.6]);
|
|
62
|
+
* vectorService.LoadVectors(vectors);
|
|
63
|
+
*
|
|
64
|
+
* // Find similar items
|
|
65
|
+
* const queryVector = [0.15, 0.25, 0.35];
|
|
66
|
+
* const results = vectorService.FindNearest(queryVector, 5);
|
|
67
|
+
* ```
|
|
68
|
+
*
|
|
69
|
+
* @class
|
|
70
|
+
* @public
|
|
71
|
+
*/
|
|
23
72
|
export declare class SimpleVectorService<TMetadata = Record<string, unknown>> {
|
|
24
73
|
private vectors;
|
|
25
74
|
private expectedDimensions;
|
|
75
|
+
/**
|
|
76
|
+
* Loads vectors into memory. Can accept either an array of VectorEntry objects
|
|
77
|
+
* or a Map where keys are identifiers and values are vector arrays.
|
|
78
|
+
*
|
|
79
|
+
* @param {VectorEntry<TMetadata>[] | Map<string, number[]>} entries - The vectors to load
|
|
80
|
+
* @throws {Error} If entries is null or undefined
|
|
81
|
+
*
|
|
82
|
+
* @example
|
|
83
|
+
* ```typescript
|
|
84
|
+
* // Load from array
|
|
85
|
+
* service.LoadVectors([
|
|
86
|
+
* { key: 'doc1', vector: [0.1, 0.2], metadata: { title: 'Document 1' } },
|
|
87
|
+
* { key: 'doc2', vector: [0.3, 0.4], metadata: { title: 'Document 2' } }
|
|
88
|
+
* ]);
|
|
89
|
+
*
|
|
90
|
+
* // Load from Map
|
|
91
|
+
* const vectorMap = new Map();
|
|
92
|
+
* vectorMap.set('doc1', [0.1, 0.2]);
|
|
93
|
+
* vectorMap.set('doc2', [0.3, 0.4]);
|
|
94
|
+
* service.LoadVectors(vectorMap);
|
|
95
|
+
* ```
|
|
96
|
+
*
|
|
97
|
+
* @public
|
|
98
|
+
* @method
|
|
99
|
+
*/
|
|
26
100
|
LoadVectors(entries: VectorEntry<TMetadata>[] | Map<string, number[]>): void;
|
|
101
|
+
/**
|
|
102
|
+
* Adds or updates a single vector in the service
|
|
103
|
+
*
|
|
104
|
+
* @param {string} key - The unique identifier for the vector
|
|
105
|
+
* @param {number[]} vector - The vector/embedding array
|
|
106
|
+
* @param {TMetadata} metadata - Optional metadata to associate with the vector
|
|
107
|
+
* @throws {Error} If key is null/undefined, or if vector is invalid
|
|
108
|
+
*
|
|
109
|
+
* @example
|
|
110
|
+
* ```typescript
|
|
111
|
+
* service.AddVector('product123', [0.1, 0.2, 0.3], {
|
|
112
|
+
* name: 'Product Name',
|
|
113
|
+
* category: 'Electronics'
|
|
114
|
+
* });
|
|
115
|
+
* ```
|
|
116
|
+
*
|
|
117
|
+
* @public
|
|
118
|
+
* @method
|
|
119
|
+
*/
|
|
27
120
|
AddVector(key: string, vector: number[], metadata?: TMetadata): void;
|
|
121
|
+
/**
|
|
122
|
+
* Finds the K nearest neighbors to a query vector using the specified similarity metric
|
|
123
|
+
*
|
|
124
|
+
* @param {number[]} queryVector - The vector to search for similar items
|
|
125
|
+
* @param {number} [topK=10] - Number of nearest neighbors to return
|
|
126
|
+
* @param {number} [threshold] - Optional minimum similarity threshold (0-1)
|
|
127
|
+
* @param {DistanceMetric} [metric='cosine'] - The distance metric to use
|
|
128
|
+
* @param {(metadata: TMetadata) => boolean} [filter] - Optional filter to pre-filter vectors by metadata before similarity calculation
|
|
129
|
+
* @returns {VectorSearchResult<TMetadata>[]} Array of search results sorted by similarity (highest first)
|
|
130
|
+
* @throws {Error} If queryVector is null/undefined or empty
|
|
131
|
+
*
|
|
132
|
+
* @example
|
|
133
|
+
* ```typescript
|
|
134
|
+
* // Default cosine similarity
|
|
135
|
+
* const nearestItems = service.FindNearest(queryEmbedding, 5);
|
|
136
|
+
*
|
|
137
|
+
* // Using Euclidean distance for numeric features
|
|
138
|
+
* const similarProducts = service.FindNearest(productFeatures, 10, undefined, 'euclidean');
|
|
139
|
+
*
|
|
140
|
+
* // With threshold - only return items with similarity > 0.7
|
|
141
|
+
* const highSimilarity = service.FindNearest(queryVector, 10, 0.7, 'cosine');
|
|
142
|
+
*
|
|
143
|
+
* // Using Jaccard for categorical data
|
|
144
|
+
* const similarUsers = service.FindNearest(userPreferences, 5, undefined, 'jaccard');
|
|
145
|
+
*
|
|
146
|
+
* // Filter by metadata before searching (efficient pre-filtering)
|
|
147
|
+
* const agentNotes = service.FindNearest(
|
|
148
|
+
* queryVector,
|
|
149
|
+
* 5,
|
|
150
|
+
* 0.5,
|
|
151
|
+
* 'cosine',
|
|
152
|
+
* (metadata) => metadata.agentId === 'agent-123'
|
|
153
|
+
* );
|
|
154
|
+
* ```
|
|
155
|
+
*
|
|
156
|
+
* @public
|
|
157
|
+
* @method
|
|
158
|
+
*/
|
|
28
159
|
FindNearest(queryVector: number[], topK?: number, threshold?: number, metric?: DistanceMetric, filter?: (metadata: TMetadata) => boolean): VectorSearchResult<TMetadata>[];
|
|
160
|
+
/**
|
|
161
|
+
* Finds vectors similar to an existing vector identified by its key.
|
|
162
|
+
* The source vector itself is excluded from the results.
|
|
163
|
+
*
|
|
164
|
+
* @param {string} key - The key of the source vector
|
|
165
|
+
* @param {number} [topK=10] - Number of similar vectors to return
|
|
166
|
+
* @param {number} [threshold] - Optional minimum similarity threshold (0-1)
|
|
167
|
+
* @param {DistanceMetric} [metric='cosine'] - The distance metric to use
|
|
168
|
+
* @param {(metadata: TMetadata) => boolean} [filter] - Optional filter to pre-filter vectors by metadata before similarity calculation
|
|
169
|
+
* @returns {VectorSearchResult<TMetadata>[]} Array of similar vectors sorted by similarity
|
|
170
|
+
* @throws {Error} If the key doesn't exist in the service
|
|
171
|
+
*
|
|
172
|
+
* @example
|
|
173
|
+
* ```typescript
|
|
174
|
+
* // Find items similar to 'product123'
|
|
175
|
+
* const similarProducts = service.FindSimilar('product123', 5);
|
|
176
|
+
*
|
|
177
|
+
* // Find highly similar items (similarity > 0.8)
|
|
178
|
+
* const verySimilar = service.FindSimilar('product123', 10, 0.8);
|
|
179
|
+
*
|
|
180
|
+
* // Find similar items using Euclidean distance
|
|
181
|
+
* const similar = service.FindSimilar('product123', 5, undefined, 'euclidean');
|
|
182
|
+
*
|
|
183
|
+
* // Find similar items filtered by category
|
|
184
|
+
* const similarInCategory = service.FindSimilar(
|
|
185
|
+
* 'product123',
|
|
186
|
+
* 5,
|
|
187
|
+
* 0.7,
|
|
188
|
+
* 'cosine',
|
|
189
|
+
* (metadata) => metadata.category === 'Electronics'
|
|
190
|
+
* );
|
|
191
|
+
* ```
|
|
192
|
+
*
|
|
193
|
+
* @public
|
|
194
|
+
* @method
|
|
195
|
+
*/
|
|
29
196
|
FindSimilar(key: string, topK?: number, threshold?: number, metric?: DistanceMetric, filter?: (metadata: TMetadata) => boolean): VectorSearchResult<TMetadata>[];
|
|
197
|
+
/**
|
|
198
|
+
* Calculates the cosine similarity between two vectors identified by their keys
|
|
199
|
+
*
|
|
200
|
+
* @param {string} key1 - Key of the first vector
|
|
201
|
+
* @param {string} key2 - Key of the second vector
|
|
202
|
+
* @returns {number} Cosine similarity score between 0 and 1
|
|
203
|
+
* @throws {Error} If either key doesn't exist in the service
|
|
204
|
+
*
|
|
205
|
+
* @example
|
|
206
|
+
* ```typescript
|
|
207
|
+
* const similarity = service.Similarity('item1', 'item2');
|
|
208
|
+
* console.log(`Similarity: ${similarity}`);
|
|
209
|
+
* ```
|
|
210
|
+
*
|
|
211
|
+
* @public
|
|
212
|
+
* @method
|
|
213
|
+
*/
|
|
30
214
|
Similarity(key1: string, key2: string): number;
|
|
215
|
+
/**
|
|
216
|
+
* Calculates cosine similarity between two vectors using the formula:
|
|
217
|
+
* similarity = (A · B) / (||A|| × ||B||)
|
|
218
|
+
*
|
|
219
|
+
* ## What is Cosine Similarity?
|
|
220
|
+
* Cosine similarity measures the cosine of the angle between two vectors in multi-dimensional space.
|
|
221
|
+
* It tells us how similar two vectors are regardless of their magnitude (length).
|
|
222
|
+
*
|
|
223
|
+
* ## Return Values:
|
|
224
|
+
* - **1.0**: Vectors point in exactly the same direction (identical)
|
|
225
|
+
* - **0.0**: Vectors are perpendicular (orthogonal/unrelated)
|
|
226
|
+
* - **-1.0**: Vectors point in opposite directions (completely different)
|
|
227
|
+
* - **0.7-1.0**: High similarity (vectors are closely related)
|
|
228
|
+
* - **0.3-0.7**: Moderate similarity
|
|
229
|
+
* - **< 0.3**: Low similarity
|
|
230
|
+
*
|
|
231
|
+
* ## Why Use Cosine Similarity for Embeddings?
|
|
232
|
+
* Text embeddings encode semantic meaning as vectors. Cosine similarity is ideal because:
|
|
233
|
+
* - It focuses on direction (meaning) rather than magnitude (importance)
|
|
234
|
+
* - It's normalized between -1 and 1, making scores comparable
|
|
235
|
+
* - It works well in high-dimensional spaces (384-1536 dimensions)
|
|
236
|
+
*
|
|
237
|
+
* ## Mathematical Formula:
|
|
238
|
+
* ```
|
|
239
|
+
* cosine_similarity = dot_product(A, B) / (magnitude(A) * magnitude(B))
|
|
240
|
+
*
|
|
241
|
+
* Where:
|
|
242
|
+
* - dot_product(A, B) = Σ(a[i] * b[i]) for all i
|
|
243
|
+
* - magnitude(A) = √(Σ(a[i]²)) for all i
|
|
244
|
+
* ```
|
|
245
|
+
*
|
|
246
|
+
* @param {number[]} a - First vector (e.g., embedding of document A)
|
|
247
|
+
* @param {number[]} b - Second vector (e.g., embedding of document B)
|
|
248
|
+
* @returns {number} Cosine similarity score between -1 and 1
|
|
249
|
+
* @throws {Error} If vectors have different dimensions (must be same length)
|
|
250
|
+
*
|
|
251
|
+
* @example
|
|
252
|
+
* ```typescript
|
|
253
|
+
* // Two identical vectors have similarity of 1
|
|
254
|
+
* const similarity1 = CosineSimilarity([1, 2, 3], [1, 2, 3]); // ≈ 1.0
|
|
255
|
+
*
|
|
256
|
+
* // Perpendicular vectors have similarity of 0
|
|
257
|
+
* const similarity2 = CosineSimilarity([1, 0], [0, 1]); // = 0.0
|
|
258
|
+
*
|
|
259
|
+
* // Opposite vectors have similarity of -1
|
|
260
|
+
* const similarity3 = CosineSimilarity([1, 2], [-1, -2]); // = -1.0
|
|
261
|
+
* ```
|
|
262
|
+
*
|
|
263
|
+
* @protected
|
|
264
|
+
* @method
|
|
265
|
+
*/
|
|
31
266
|
protected CosineSimilarity(a: number[], b: number[]): number;
|
|
267
|
+
/**
|
|
268
|
+
* Calculates Euclidean distance between two vectors, normalized to 0-1 range.
|
|
269
|
+
*
|
|
270
|
+
* ## What is Euclidean Distance?
|
|
271
|
+
* Euclidean distance is the "straight-line" distance between two points in space.
|
|
272
|
+
* It's what you'd measure with a ruler in the physical world.
|
|
273
|
+
*
|
|
274
|
+
* ## Mathematical Formula:
|
|
275
|
+
* ```
|
|
276
|
+
* distance = √(Σ(a[i] - b[i])²)
|
|
277
|
+
* normalized_similarity = 1 / (1 + distance)
|
|
278
|
+
* ```
|
|
279
|
+
*
|
|
280
|
+
* ## Return Values (Normalized):
|
|
281
|
+
* - **1.0**: Identical vectors (distance = 0)
|
|
282
|
+
* - **0.5**: Moderate distance (distance = 1)
|
|
283
|
+
* - **→0**: Very different vectors (large distance)
|
|
284
|
+
*
|
|
285
|
+
* ## Business Use Cases:
|
|
286
|
+
* - **Product specifications**: Compare products by numeric features (size, weight, price)
|
|
287
|
+
* - **Quality control**: Measure deviation from target specifications
|
|
288
|
+
* - **Geographic analysis**: Distance between store locations (lat/long)
|
|
289
|
+
* - **Customer segmentation**: Group customers by purchase behavior metrics
|
|
290
|
+
* - **Inventory management**: Find similar SKUs by dimensions
|
|
291
|
+
*
|
|
292
|
+
* ## When to Use:
|
|
293
|
+
* ✅ Continuous numeric features where magnitude matters
|
|
294
|
+
* ✅ Physical measurements and specifications
|
|
295
|
+
* ✅ When you need true geometric distance
|
|
296
|
+
* ❌ High-dimensional sparse data (use cosine instead)
|
|
297
|
+
* ❌ Text embeddings (use cosine for better results)
|
|
298
|
+
*
|
|
299
|
+
* @param {number[]} a - First vector
|
|
300
|
+
* @param {number[]} b - Second vector
|
|
301
|
+
* @returns {number} Normalized similarity score (0-1, where 1 = identical)
|
|
302
|
+
* @throws {Error} If vectors have different dimensions
|
|
303
|
+
*
|
|
304
|
+
* @protected
|
|
305
|
+
* @method
|
|
306
|
+
*/
|
|
32
307
|
protected EuclideanDistance(a: number[], b: number[]): number;
|
|
308
|
+
/**
|
|
309
|
+
* Calculates Manhattan distance between two vectors, normalized to 0-1 range.
|
|
310
|
+
*
|
|
311
|
+
* ## What is Manhattan Distance?
|
|
312
|
+
* Manhattan distance (also called L1 distance, city block distance, or taxicab distance)
|
|
313
|
+
* measures the distance between two points by summing the absolute differences of their coordinates.
|
|
314
|
+
* Like navigating a city grid where you can only move along streets.
|
|
315
|
+
*
|
|
316
|
+
* ## Mathematical Formula:
|
|
317
|
+
* ```
|
|
318
|
+
* distance = Σ|a[i] - b[i]|
|
|
319
|
+
* normalized_similarity = 1 / (1 + distance)
|
|
320
|
+
* ```
|
|
321
|
+
*
|
|
322
|
+
* ## Return Values (Normalized):
|
|
323
|
+
* - **1.0**: Identical vectors (distance = 0)
|
|
324
|
+
* - **0.5**: Moderate distance (sum of differences = 1)
|
|
325
|
+
* - **→0**: Very different vectors (large total difference)
|
|
326
|
+
*
|
|
327
|
+
* ## Business Use Cases:
|
|
328
|
+
* - **Supply chain**: Warehouse grid navigation, pick-path optimization
|
|
329
|
+
* - **Time series**: Comparing trends (robust to outliers)
|
|
330
|
+
* - **Resource allocation**: Movement costs in grid systems
|
|
331
|
+
* - **Urban planning**: Actual travel distance in city blocks
|
|
332
|
+
* - **Inventory differences**: Total units different across SKUs
|
|
333
|
+
*
|
|
334
|
+
* ## When to Use:
|
|
335
|
+
* ✅ Grid-based movement systems
|
|
336
|
+
* ✅ When outliers should have linear (not squared) impact
|
|
337
|
+
* ✅ Discrete movements or changes
|
|
338
|
+
* ✅ Each dimension represents independent cost/distance
|
|
339
|
+
* ❌ Smooth gradients needed
|
|
340
|
+
* ❌ True geometric distance required
|
|
341
|
+
*
|
|
342
|
+
* @param {number[]} a - First vector
|
|
343
|
+
* @param {number[]} b - Second vector
|
|
344
|
+
* @returns {number} Normalized similarity score (0-1, where 1 = identical)
|
|
345
|
+
* @throws {Error} If vectors have different dimensions
|
|
346
|
+
*
|
|
347
|
+
* @protected
|
|
348
|
+
* @method
|
|
349
|
+
*/
|
|
33
350
|
protected ManhattanDistance(a: number[], b: number[]): number;
|
|
351
|
+
/**
|
|
352
|
+
* Calculates dot product similarity between two vectors, normalized to 0-1 range.
|
|
353
|
+
*
|
|
354
|
+
* ## What is Dot Product?
|
|
355
|
+
* Dot product (inner product) measures both direction AND magnitude alignment.
|
|
356
|
+
* Unlike cosine similarity, it rewards vectors that point the same way AND have similar magnitudes.
|
|
357
|
+
*
|
|
358
|
+
* ## Mathematical Formula:
|
|
359
|
+
* ```
|
|
360
|
+
* dot_product = Σ(a[i] × b[i])
|
|
361
|
+
* normalized = (tanh(dot_product / scale) + 1) / 2
|
|
362
|
+
* ```
|
|
363
|
+
*
|
|
364
|
+
* ## Return Values (Normalized):
|
|
365
|
+
* - **1.0**: Perfect alignment with similar magnitude
|
|
366
|
+
* - **0.5**: Orthogonal or neutral relationship
|
|
367
|
+
* - **0.0**: Opposite direction or very different magnitudes
|
|
368
|
+
*
|
|
369
|
+
* ## Business Use Cases:
|
|
370
|
+
* - **Recommendation systems**: When popularity (magnitude) matters
|
|
371
|
+
* - **Revenue analysis**: Quantity × Price calculations
|
|
372
|
+
* - **Weighted scoring**: Features × Importance weights
|
|
373
|
+
* - **Portfolio analysis**: Holdings × Performance
|
|
374
|
+
* - **Marketing effectiveness**: Reach × Engagement metrics
|
|
375
|
+
*
|
|
376
|
+
* ## When to Use:
|
|
377
|
+
* ✅ Magnitude is meaningful (popularity, importance, quantity)
|
|
378
|
+
* ✅ Pre-normalized vectors with semantic magnitude
|
|
379
|
+
* ✅ Weighted feature comparisons
|
|
380
|
+
* ✅ Collaborative filtering with implicit feedback
|
|
381
|
+
* ❌ Vectors with different scales
|
|
382
|
+
* ❌ When only direction matters (use cosine)
|
|
383
|
+
*
|
|
384
|
+
* @param {number[]} a - First vector
|
|
385
|
+
* @param {number[]} b - Second vector
|
|
386
|
+
* @returns {number} Normalized similarity score (0-1, where 1 = high similarity)
|
|
387
|
+
* @throws {Error} If vectors have different dimensions
|
|
388
|
+
*
|
|
389
|
+
* @protected
|
|
390
|
+
* @method
|
|
391
|
+
*/
|
|
34
392
|
protected DotProduct(a: number[], b: number[]): number;
|
|
393
|
+
/**
|
|
394
|
+
* Calculates Jaccard similarity between two vectors treated as sets.
|
|
395
|
+
*
|
|
396
|
+
* ## What is Jaccard Similarity?
|
|
397
|
+
* Jaccard similarity (Jaccard index) measures the similarity between two sets
|
|
398
|
+
* as the size of their intersection divided by the size of their union.
|
|
399
|
+
* For vectors, non-zero elements are treated as "present" in the set.
|
|
400
|
+
*
|
|
401
|
+
* ## Mathematical Formula:
|
|
402
|
+
* ```
|
|
403
|
+
* jaccard = |A ∩ B| / |A ∪ B|
|
|
404
|
+
* where A and B are sets of non-zero indices
|
|
405
|
+
* ```
|
|
406
|
+
*
|
|
407
|
+
* ## Return Values:
|
|
408
|
+
* - **1.0**: Identical sets (same non-zero positions)
|
|
409
|
+
* - **0.5**: Half of combined elements are shared
|
|
410
|
+
* - **0.0**: No overlap (completely different sets)
|
|
411
|
+
*
|
|
412
|
+
* ## Business Use Cases:
|
|
413
|
+
* - **Customer behavior**: Products purchased, features used
|
|
414
|
+
* - **Document similarity**: Presence/absence of keywords
|
|
415
|
+
* - **Market basket**: Product co-occurrence analysis
|
|
416
|
+
* - **User permissions**: Comparing access control sets
|
|
417
|
+
* - **Tag similarity**: Comparing item categorizations
|
|
418
|
+
*
|
|
419
|
+
* ## When to Use:
|
|
420
|
+
* ✅ Binary or categorical data (presence/absence)
|
|
421
|
+
* ✅ Sparse vectors where zeros mean "not present"
|
|
422
|
+
* ✅ Set membership comparisons
|
|
423
|
+
* ✅ When magnitude doesn't matter, only presence
|
|
424
|
+
* ❌ Continuous numeric features
|
|
425
|
+
* ❌ Dense embeddings
|
|
426
|
+
*
|
|
427
|
+
* ## Note on Sparse Vectors:
|
|
428
|
+
* This implementation treats 0 as absence and any non-zero as presence.
|
|
429
|
+
* This is suitable for sparse representations where 0 explicitly means "not in set".
|
|
430
|
+
*
|
|
431
|
+
* @param {number[]} a - First vector (treated as set)
|
|
432
|
+
* @param {number[]} b - Second vector (treated as set)
|
|
433
|
+
* @returns {number} Jaccard similarity (0-1, where 1 = identical sets)
|
|
434
|
+
* @throws {Error} If vectors have different dimensions
|
|
435
|
+
*
|
|
436
|
+
* @protected
|
|
437
|
+
* @method
|
|
438
|
+
*/
|
|
35
439
|
protected JaccardSimilarity(a: number[], b: number[]): number;
|
|
440
|
+
/**
|
|
441
|
+
* Calculates Hamming distance between two vectors, normalized to similarity score.
|
|
442
|
+
*
|
|
443
|
+
* ## What is Hamming Distance?
|
|
444
|
+
* Hamming distance counts the number of positions where two vectors differ.
|
|
445
|
+
* Originally designed for error detection in telecommunications, it's useful
|
|
446
|
+
* for comparing categorical data or binary strings.
|
|
447
|
+
*
|
|
448
|
+
* ## Mathematical Formula:
|
|
449
|
+
* ```
|
|
450
|
+
* hamming_distance = count(a[i] ≠ b[i])
|
|
451
|
+
* similarity = 1 - (hamming_distance / vector_length)
|
|
452
|
+
* ```
|
|
453
|
+
*
|
|
454
|
+
* ## Return Values (Normalized):
|
|
455
|
+
* - **1.0**: Identical vectors (no differences)
|
|
456
|
+
* - **0.5**: Half of positions differ
|
|
457
|
+
* - **0.0**: All positions differ
|
|
458
|
+
*
|
|
459
|
+
* ## Business Use Cases:
|
|
460
|
+
* - **Data quality**: Detecting errors in data entry
|
|
461
|
+
* - **A/B testing**: Comparing feature flags or configurations
|
|
462
|
+
* - **Fraud detection**: Unusual patterns in categorical attributes
|
|
463
|
+
* - **Product variants**: Comparing product configurations
|
|
464
|
+
* - **System monitoring**: Configuration drift detection
|
|
465
|
+
*
|
|
466
|
+
* ## When to Use:
|
|
467
|
+
* ✅ Categorical data comparison
|
|
468
|
+
* ✅ Binary feature vectors
|
|
469
|
+
* ✅ Error detection and correction
|
|
470
|
+
* ✅ Fixed-length codes or identifiers
|
|
471
|
+
* ❌ Continuous numeric features
|
|
472
|
+
* ❌ When magnitude of difference matters
|
|
473
|
+
*
|
|
474
|
+
* ## Note on Continuous Values:
|
|
475
|
+
* For continuous values, this uses exact equality. Consider binning
|
|
476
|
+
* continuous values first if approximate matching is needed.
|
|
477
|
+
*
|
|
478
|
+
* @param {number[]} a - First vector
|
|
479
|
+
* @param {number[]} b - Second vector
|
|
480
|
+
* @returns {number} Normalized similarity (0-1, where 1 = identical)
|
|
481
|
+
* @throws {Error} If vectors have different dimensions
|
|
482
|
+
*
|
|
483
|
+
* @protected
|
|
484
|
+
* @method
|
|
485
|
+
*/
|
|
36
486
|
protected HammingDistance(a: number[], b: number[]): number;
|
|
487
|
+
/**
|
|
488
|
+
* Calculates distance/similarity between two vectors using the specified metric.
|
|
489
|
+
* All metrics are normalized to 0-1 range where 1 indicates highest similarity.
|
|
490
|
+
*
|
|
491
|
+
* @param {number[]} a - First vector
|
|
492
|
+
* @param {number[]} b - Second vector
|
|
493
|
+
* @param {DistanceMetric} [metric='cosine'] - The metric to use
|
|
494
|
+
* @returns {number} Normalized similarity score (0-1)
|
|
495
|
+
* @throws {Error} If vectors have different dimensions or invalid metric
|
|
496
|
+
*
|
|
497
|
+
* @example
|
|
498
|
+
* ```typescript
|
|
499
|
+
* const similarity = service.CalculateDistance(vec1, vec2, 'euclidean');
|
|
500
|
+
* ```
|
|
501
|
+
*
|
|
502
|
+
* @public
|
|
503
|
+
* @method
|
|
504
|
+
*/
|
|
37
505
|
CalculateDistance(a: number[], b: number[], metric?: DistanceMetric): number;
|
|
506
|
+
/**
|
|
507
|
+
* Gets the current number of vectors in the service
|
|
508
|
+
*
|
|
509
|
+
* @returns {number} The number of vectors currently loaded
|
|
510
|
+
*
|
|
511
|
+
* @public
|
|
512
|
+
* @readonly
|
|
513
|
+
*/
|
|
38
514
|
get Size(): number;
|
|
515
|
+
/**
|
|
516
|
+
* Clears all vectors from memory
|
|
517
|
+
*
|
|
518
|
+
* @example
|
|
519
|
+
* ```typescript
|
|
520
|
+
* service.Clear();
|
|
521
|
+
* console.log(service.Size); // 0
|
|
522
|
+
* ```
|
|
523
|
+
*
|
|
524
|
+
* @public
|
|
525
|
+
* @method
|
|
526
|
+
*/
|
|
39
527
|
Clear(): void;
|
|
528
|
+
/**
|
|
529
|
+
* Checks if a vector with the given key exists
|
|
530
|
+
*
|
|
531
|
+
* @param {string} key - The key to check
|
|
532
|
+
* @returns {boolean} True if the key exists, false otherwise
|
|
533
|
+
*
|
|
534
|
+
* @example
|
|
535
|
+
* ```typescript
|
|
536
|
+
* if (service.Has('product123')) {
|
|
537
|
+
* console.log('Product vector exists');
|
|
538
|
+
* }
|
|
539
|
+
* ```
|
|
540
|
+
*
|
|
541
|
+
* @public
|
|
542
|
+
* @method
|
|
543
|
+
*/
|
|
40
544
|
Has(key: string): boolean;
|
|
545
|
+
/**
|
|
546
|
+
* Retrieves a specific vector by its key
|
|
547
|
+
*
|
|
548
|
+
* @param {string} key - The key of the vector to retrieve
|
|
549
|
+
* @returns {number[] | undefined} The vector array, or undefined if not found
|
|
550
|
+
*
|
|
551
|
+
* @example
|
|
552
|
+
* ```typescript
|
|
553
|
+
* const vector = service.GetVector('product123');
|
|
554
|
+
* if (vector) {
|
|
555
|
+
* console.log(`Vector dimensions: ${vector.length}`);
|
|
556
|
+
* }
|
|
557
|
+
* ```
|
|
558
|
+
*
|
|
559
|
+
* @public
|
|
560
|
+
* @method
|
|
561
|
+
*/
|
|
41
562
|
GetVector(key: string): number[] | undefined;
|
|
563
|
+
/**
|
|
564
|
+
* Retrieves the metadata associated with a specific vector
|
|
565
|
+
*
|
|
566
|
+
* @param {string} key - The key of the vector
|
|
567
|
+
* @returns {TMetadata | undefined} The metadata, or undefined if not found
|
|
568
|
+
*
|
|
569
|
+
* @example
|
|
570
|
+
* ```typescript
|
|
571
|
+
* const metadata = service.GetMetadata('product123');
|
|
572
|
+
* if (metadata) {
|
|
573
|
+
* console.log(`Product name: ${metadata.name}`);
|
|
574
|
+
* }
|
|
575
|
+
* ```
|
|
576
|
+
*
|
|
577
|
+
* @public
|
|
578
|
+
* @method
|
|
579
|
+
*/
|
|
42
580
|
GetMetadata(key: string): TMetadata | undefined;
|
|
581
|
+
/**
|
|
582
|
+
* Updates an existing vector entry in-place, allowing partial updates to the vector data,
|
|
583
|
+
* metadata, or both without removing and re-adding the entry. Unlike {@link AddVector}, this
|
|
584
|
+
* method requires the key to already exist and will throw if it does not.
|
|
585
|
+
*
|
|
586
|
+
* This is useful when you need to:
|
|
587
|
+
* - Update the embedding for an existing key after re-encoding (e.g., content changed)
|
|
588
|
+
* - Patch metadata without touching the vector data
|
|
589
|
+
* - Atomically update both vector and metadata in a single call
|
|
590
|
+
*
|
|
591
|
+
* @param {string} key - The unique identifier of the vector to update. Must already exist.
|
|
592
|
+
* @param {Object} updates - The fields to update. At least one of `vector` or `metadata` must be provided.
|
|
593
|
+
* @param {number[]} [updates.vector] - New vector/embedding to replace the existing one.
|
|
594
|
+
* Must match the expected dimensions of the service.
|
|
595
|
+
* @param {TMetadata} [updates.metadata] - New metadata to replace the existing metadata.
|
|
596
|
+
* @returns {boolean} True if the update was applied successfully
|
|
597
|
+
* @throws {Error} If the key does not exist in the service
|
|
598
|
+
* @throws {Error} If neither `vector` nor `metadata` is provided
|
|
599
|
+
* @throws {Error} If the new vector has mismatched dimensions
|
|
600
|
+
*
|
|
601
|
+
* @example
|
|
602
|
+
* ```typescript
|
|
603
|
+
* // Update only the vector (e.g., after re-embedding content)
|
|
604
|
+
* service.UpdateVector('doc123', { vector: newEmbedding });
|
|
605
|
+
*
|
|
606
|
+
* // Update only metadata (e.g., status changed)
|
|
607
|
+
* service.UpdateVector('doc123', { metadata: { title: 'Updated Title', status: 'reviewed' } });
|
|
608
|
+
*
|
|
609
|
+
* // Update both vector and metadata atomically
|
|
610
|
+
* service.UpdateVector('doc123', {
|
|
611
|
+
* vector: newEmbedding,
|
|
612
|
+
* metadata: { title: 'Updated Title', version: 2 }
|
|
613
|
+
* });
|
|
614
|
+
* ```
|
|
615
|
+
*
|
|
616
|
+
* @public
|
|
617
|
+
* @method
|
|
618
|
+
*/
|
|
619
|
+
UpdateVector(key: string, updates: {
|
|
620
|
+
vector?: number[];
|
|
621
|
+
metadata?: TMetadata;
|
|
622
|
+
}): boolean;
|
|
623
|
+
/**
|
|
624
|
+
* Adds a new vector or updates an existing one based on whether the key already exists.
|
|
625
|
+
* If the key does not exist, a new entry is created. If the key already exists, the
|
|
626
|
+
* vector and/or metadata are updated in place.
|
|
627
|
+
*
|
|
628
|
+
* @param {string} key - The unique identifier for the vector
|
|
629
|
+
* @param {number[]} vector - The vector/embedding array
|
|
630
|
+
* @param {TMetadata} [metadata] - Optional metadata to associate with the vector
|
|
631
|
+
* @returns {boolean} True if an existing vector was updated, false if a new vector was added
|
|
632
|
+
* @throws {Error} If key is null/undefined, or if vector is invalid
|
|
633
|
+
*
|
|
634
|
+
* @example
|
|
635
|
+
* ```typescript
|
|
636
|
+
* // First call creates the entry
|
|
637
|
+
* const wasUpdate = service.AddOrUpdateVector('doc1', [0.1, 0.2, 0.3], { title: 'Doc 1' });
|
|
638
|
+
* console.log(wasUpdate); // false (new entry)
|
|
639
|
+
*
|
|
640
|
+
* // Second call updates the existing entry
|
|
641
|
+
* const wasUpdate2 = service.AddOrUpdateVector('doc1', [0.4, 0.5, 0.6], { title: 'Doc 1 v2' });
|
|
642
|
+
* console.log(wasUpdate2); // true (updated)
|
|
643
|
+
* ```
|
|
644
|
+
*
|
|
645
|
+
* @public
|
|
646
|
+
* @method
|
|
647
|
+
*/
|
|
648
|
+
AddOrUpdateVector(key: string, vector: number[], metadata?: TMetadata): boolean;
|
|
649
|
+
/**
|
|
650
|
+
* Removes a vector from the service
|
|
651
|
+
*
|
|
652
|
+
* @param {string} key - The key of the vector to remove
|
|
653
|
+
* @returns {boolean} True if the vector was removed, false if it didn't exist
|
|
654
|
+
*
|
|
655
|
+
* @example
|
|
656
|
+
* ```typescript
|
|
657
|
+
* if (service.RemoveVector('product123')) {
|
|
658
|
+
* console.log('Vector removed successfully');
|
|
659
|
+
* }
|
|
660
|
+
* ```
|
|
661
|
+
*
|
|
662
|
+
* @public
|
|
663
|
+
* @method
|
|
664
|
+
*/
|
|
43
665
|
RemoveVector(key: string): boolean;
|
|
666
|
+
/**
|
|
667
|
+
* Gets all keys currently stored in the service
|
|
668
|
+
*
|
|
669
|
+
* @returns {string[]} Array of all vector keys
|
|
670
|
+
*
|
|
671
|
+
* @example
|
|
672
|
+
* ```typescript
|
|
673
|
+
* const allKeys = service.GetAllKeys();
|
|
674
|
+
* console.log(`Total vectors: ${allKeys.length}`);
|
|
675
|
+
* ```
|
|
676
|
+
*
|
|
677
|
+
* @public
|
|
678
|
+
* @method
|
|
679
|
+
*/
|
|
44
680
|
GetAllKeys(): string[];
|
|
681
|
+
/**
|
|
682
|
+
* Exports all vectors as an array of VectorEntry objects.
|
|
683
|
+
* Useful for persistence or transferring data.
|
|
684
|
+
*
|
|
685
|
+
* @returns {VectorEntry<TMetadata>[]} Array of all vector entries
|
|
686
|
+
*
|
|
687
|
+
* @example
|
|
688
|
+
* ```typescript
|
|
689
|
+
* const allVectors = service.ExportVectors();
|
|
690
|
+
* // Save to database or file
|
|
691
|
+
* await saveToDatabase(allVectors);
|
|
692
|
+
* ```
|
|
693
|
+
*
|
|
694
|
+
* @public
|
|
695
|
+
* @method
|
|
696
|
+
*/
|
|
45
697
|
ExportVectors(): VectorEntry<TMetadata>[];
|
|
698
|
+
/**
|
|
699
|
+
* Validates vector dimensions and sets expected dimensions if not yet set.
|
|
700
|
+
* Ensures all vectors have consistent dimensions for valid similarity calculations.
|
|
701
|
+
*
|
|
702
|
+
* @param {number[]} vector - The vector to validate
|
|
703
|
+
* @throws {Error} If vector dimensions don't match expected dimensions
|
|
704
|
+
*
|
|
705
|
+
* @private
|
|
706
|
+
* @method
|
|
707
|
+
*/
|
|
46
708
|
private validateAndSetDimensions;
|
|
709
|
+
/**
|
|
710
|
+
* Gets the expected vector dimensions for this service instance
|
|
711
|
+
*
|
|
712
|
+
* @returns {number | null} The expected dimensions, or null if no vectors loaded yet
|
|
713
|
+
*
|
|
714
|
+
* @public
|
|
715
|
+
* @readonly
|
|
716
|
+
*/
|
|
47
717
|
get ExpectedDimensions(): number | null;
|
|
718
|
+
/**
|
|
719
|
+
* Finds all vectors with similarity above a threshold
|
|
720
|
+
*
|
|
721
|
+
* @param {number[]} queryVector - The vector to search for similar items
|
|
722
|
+
* @param {number} threshold - Minimum similarity threshold (0-1)
|
|
723
|
+
* @param {DistanceMetric} [metric='cosine'] - The distance metric to use
|
|
724
|
+
* @param {(metadata: TMetadata) => boolean} [filter] - Optional filter to pre-filter vectors by metadata before similarity calculation
|
|
725
|
+
* @returns {VectorSearchResult<TMetadata>[]} Array of search results sorted by similarity
|
|
726
|
+
*
|
|
727
|
+
* @example
|
|
728
|
+
* ```typescript
|
|
729
|
+
* // Find all highly similar items (similarity > 0.8)
|
|
730
|
+
* const similar = service.FindAboveThreshold(queryVector, 0.8);
|
|
731
|
+
*
|
|
732
|
+
* // Find all items with Jaccard similarity > 0.5
|
|
733
|
+
* const matches = service.FindAboveThreshold(features, 0.5, 'jaccard');
|
|
734
|
+
*
|
|
735
|
+
* // Find all similar items in a specific category
|
|
736
|
+
* const categoryMatches = service.FindAboveThreshold(
|
|
737
|
+
* queryVector,
|
|
738
|
+
* 0.7,
|
|
739
|
+
* 'cosine',
|
|
740
|
+
* (metadata) => metadata.status === 'Active'
|
|
741
|
+
* );
|
|
742
|
+
* ```
|
|
743
|
+
*
|
|
744
|
+
* @public
|
|
745
|
+
* @method
|
|
746
|
+
*/
|
|
48
747
|
FindAboveThreshold(queryVector: number[], threshold: number, metric?: DistanceMetric, filter?: (metadata: TMetadata) => boolean): VectorSearchResult<TMetadata>[];
|
|
748
|
+
/**
|
|
749
|
+
* Performs K-Means clustering on the loaded vectors.
|
|
750
|
+
* Uses K-Means++ initialization for better starting centroids.
|
|
751
|
+
*
|
|
752
|
+
* ## What is K-Means Clustering?
|
|
753
|
+
* K-Means divides vectors into K clusters by minimizing within-cluster variance.
|
|
754
|
+
* Each vector is assigned to the nearest centroid, and centroids are iteratively updated.
|
|
755
|
+
*
|
|
756
|
+
* ## Business Use Cases:
|
|
757
|
+
* - **Customer Segmentation**: Group customers by behavior patterns
|
|
758
|
+
* - **Product Categorization**: Organize products into natural groups
|
|
759
|
+
* - **Market Segmentation**: Identify distinct market segments
|
|
760
|
+
* - **Anomaly Detection**: Identify unusual patterns (far from all centroids)
|
|
761
|
+
* - **Document Organization**: Group similar documents together
|
|
762
|
+
*
|
|
763
|
+
* ## When to Use:
|
|
764
|
+
* ✅ Known or estimated number of clusters
|
|
765
|
+
* ✅ Spherical, well-separated clusters
|
|
766
|
+
* ✅ Similar cluster sizes
|
|
767
|
+
* ✅ Need interpretable centroids
|
|
768
|
+
* ❌ Non-spherical clusters
|
|
769
|
+
* ❌ Varying cluster densities
|
|
770
|
+
* ❌ Unknown number of clusters
|
|
771
|
+
*
|
|
772
|
+
* @param {number} k - Number of clusters
|
|
773
|
+
* @param {number} [maxIterations=100] - Maximum iterations before stopping
|
|
774
|
+
* @param {DistanceMetric} [metric='euclidean'] - Distance metric to use
|
|
775
|
+
* @param {number} [tolerance=0.0001] - Convergence tolerance
|
|
776
|
+
* @returns {ClusterResult<TMetadata>} Clustering results with assignments and centroids
|
|
777
|
+
*
|
|
778
|
+
* @example
|
|
779
|
+
* ```typescript
|
|
780
|
+
* const result = service.KMeansCluster(3, 100, 'euclidean');
|
|
781
|
+
* result.clusters.forEach((members, clusterId) => {
|
|
782
|
+
* console.log(`Cluster ${clusterId}: ${members.length} members`);
|
|
783
|
+
* });
|
|
784
|
+
* ```
|
|
785
|
+
*
|
|
786
|
+
* @public
|
|
787
|
+
* @method
|
|
788
|
+
*/
|
|
49
789
|
KMeansCluster(k: number, maxIterations?: number, metric?: DistanceMetric, tolerance?: number): ClusterResult<TMetadata>;
|
|
790
|
+
/**
|
|
791
|
+
* K-Means++ initialization for better starting centroids.
|
|
792
|
+
* Chooses initial centroids that are far apart from each other.
|
|
793
|
+
*
|
|
794
|
+
* @private
|
|
795
|
+
*/
|
|
50
796
|
private initializeKMeansPlusPlus;
|
|
797
|
+
/**
|
|
798
|
+
* Check if cluster assignments have converged
|
|
799
|
+
* @private
|
|
800
|
+
*/
|
|
51
801
|
private checkConvergence;
|
|
802
|
+
/**
|
|
803
|
+
* Performs DBSCAN (Density-Based Spatial Clustering of Applications with Noise) clustering.
|
|
804
|
+
*
|
|
805
|
+
* ## What is DBSCAN?
|
|
806
|
+
* DBSCAN groups together points that are closely packed together (high density),
|
|
807
|
+
* marking points in low-density regions as outliers. Unlike K-Means, it doesn't require
|
|
808
|
+
* specifying the number of clusters beforehand.
|
|
809
|
+
*
|
|
810
|
+
* ## Business Use Cases:
|
|
811
|
+
* - **Fraud Detection**: Identify unusual transaction patterns
|
|
812
|
+
* - **Anomaly Detection**: Find outliers in any dataset
|
|
813
|
+
* - **Customer Behavior**: Find natural groupings without preconceptions
|
|
814
|
+
* - **Geographic Clustering**: Find areas of high activity
|
|
815
|
+
* - **Quality Control**: Identify defective products
|
|
816
|
+
*
|
|
817
|
+
* ## When to Use:
|
|
818
|
+
* ✅ Unknown number of clusters
|
|
819
|
+
* ✅ Non-spherical clusters
|
|
820
|
+
* ✅ Varying cluster densities
|
|
821
|
+
* ✅ Need to identify outliers
|
|
822
|
+
* ✅ Noise in the data
|
|
823
|
+
* ❌ High-dimensional sparse data
|
|
824
|
+
* ❌ Clusters of vastly different densities
|
|
825
|
+
*
|
|
826
|
+
* @param {number} epsilon - Maximum distance between two vectors to be considered neighbors
|
|
827
|
+
* @param {number} minPoints - Minimum number of points to form a dense region
|
|
828
|
+
* @param {DistanceMetric} [metric='euclidean'] - Distance metric to use
|
|
829
|
+
* @param {(metadata: TMetadata) => boolean} [filter] - Optional filter to pre-filter vectors by metadata before clustering
|
|
830
|
+
* @returns {ClusterResult<TMetadata>} Clustering results with outliers identified
|
|
831
|
+
*
|
|
832
|
+
* @example
|
|
833
|
+
* ```typescript
|
|
834
|
+
* // epsilon=0.3 means similarity must be > 0.7
|
|
835
|
+
* const result = service.DBSCANCluster(0.3, 3, 'cosine');
|
|
836
|
+
* console.log(`Found ${result.clusters.size} clusters`);
|
|
837
|
+
* console.log(`Outliers: ${result.outliers?.length || 0}`);
|
|
838
|
+
*
|
|
839
|
+
* // Cluster only active items
|
|
840
|
+
* const activeResult = service.DBSCANCluster(
|
|
841
|
+
* 0.3,
|
|
842
|
+
* 3,
|
|
843
|
+
* 'cosine',
|
|
844
|
+
* (metadata) => metadata.status === 'Active'
|
|
845
|
+
* );
|
|
846
|
+
* ```
|
|
847
|
+
*
|
|
848
|
+
* @public
|
|
849
|
+
* @method
|
|
850
|
+
*/
|
|
52
851
|
DBSCANCluster(epsilon: number, minPoints: number, metric?: DistanceMetric, filter?: (metadata: TMetadata) => boolean): ClusterResult<TMetadata>;
|
|
852
|
+
/**
|
|
853
|
+
* Expand a cluster in DBSCAN
|
|
854
|
+
* @private
|
|
855
|
+
*/
|
|
53
856
|
private expandCluster;
|
|
857
|
+
/**
|
|
858
|
+
* Finds the centroid (mean) of a set of vectors.
|
|
859
|
+
*
|
|
860
|
+
* ## What is a Centroid?
|
|
861
|
+
* A centroid is the mean position of all vectors in a group.
|
|
862
|
+
* It represents the "center" of the cluster in vector space.
|
|
863
|
+
*
|
|
864
|
+
* ## Business Use Cases:
|
|
865
|
+
* - **Representative Selection**: Find the average customer profile
|
|
866
|
+
* - **Summarization**: Create a summary vector for a group
|
|
867
|
+
* - **Cluster Analysis**: Understand cluster characteristics
|
|
868
|
+
* - **Trend Analysis**: Find the average trend across time periods
|
|
869
|
+
*
|
|
870
|
+
* @param {number[][]} vectors - Array of vectors to find centroid of
|
|
871
|
+
* @returns {number[]} The centroid vector
|
|
872
|
+
*
|
|
873
|
+
* @example
|
|
874
|
+
* ```typescript
|
|
875
|
+
* const vectors = [[1, 2], [3, 4], [5, 6]];
|
|
876
|
+
* const centroid = service.FindCentroid(vectors);
|
|
877
|
+
* // Returns [3, 4] (mean of each dimension)
|
|
878
|
+
* ```
|
|
879
|
+
*
|
|
880
|
+
* @public
|
|
881
|
+
* @method
|
|
882
|
+
*/
|
|
54
883
|
FindCentroid(vectors: number[][]): number[];
|
|
884
|
+
/**
|
|
885
|
+
* Calculates the average within-cluster distance for a clustering result.
|
|
886
|
+
* Lower values indicate tighter, more cohesive clusters.
|
|
887
|
+
*
|
|
888
|
+
* ## What is Within-Cluster Distance?
|
|
889
|
+
* Measures how close points are to other points in the same cluster.
|
|
890
|
+
* Also known as cluster cohesion or compactness.
|
|
891
|
+
*
|
|
892
|
+
* ## Business Interpretation:
|
|
893
|
+
* - **Low value**: Tight, well-defined groups (good)
|
|
894
|
+
* - **High value**: Loose, scattered groups (may need more clusters)
|
|
895
|
+
*
|
|
896
|
+
* @param {ClusterResult<TMetadata>} clusterResult - The clustering result
|
|
897
|
+
* @param {DistanceMetric} [metric='euclidean'] - Distance metric to use
|
|
898
|
+
* @returns {number} Average within-cluster distance (0-1, lower is better)
|
|
899
|
+
*
|
|
900
|
+
* @example
|
|
901
|
+
* ```typescript
|
|
902
|
+
* const result = service.KMeansCluster(3);
|
|
903
|
+
* const cohesion = service.WithinClusterDistance(result);
|
|
904
|
+
* console.log(`Cluster cohesion: ${cohesion.toFixed(3)}`);
|
|
905
|
+
* ```
|
|
906
|
+
*
|
|
907
|
+
* @public
|
|
908
|
+
* @method
|
|
909
|
+
*/
|
|
55
910
|
WithinClusterDistance(clusterResult: ClusterResult<TMetadata>, metric?: DistanceMetric): number;
|
|
911
|
+
/**
|
|
912
|
+
* Calculates the average between-cluster distance for a clustering result.
|
|
913
|
+
* Higher values indicate better cluster separation.
|
|
914
|
+
*
|
|
915
|
+
* ## What is Between-Cluster Distance?
|
|
916
|
+
* Measures how far apart different clusters are from each other.
|
|
917
|
+
* Also known as cluster separation.
|
|
918
|
+
*
|
|
919
|
+
* ## Business Interpretation:
|
|
920
|
+
* - **High value**: Well-separated groups (good)
|
|
921
|
+
* - **Low value**: Overlapping groups (may have too many clusters)
|
|
922
|
+
*
|
|
923
|
+
* @param {ClusterResult<TMetadata>} clusterResult - The clustering result
|
|
924
|
+
* @param {DistanceMetric} [metric='euclidean'] - Distance metric to use
|
|
925
|
+
* @returns {number} Average between-cluster distance (0-1, higher is better)
|
|
926
|
+
*
|
|
927
|
+
* @example
|
|
928
|
+
* ```typescript
|
|
929
|
+
* const result = service.KMeansCluster(3);
|
|
930
|
+
* const separation = service.BetweenClusterDistance(result);
|
|
931
|
+
* console.log(`Cluster separation: ${separation.toFixed(3)}`);
|
|
932
|
+
* ```
|
|
933
|
+
*
|
|
934
|
+
* @public
|
|
935
|
+
* @method
|
|
936
|
+
*/
|
|
56
937
|
BetweenClusterDistance(clusterResult: ClusterResult<TMetadata>, metric?: DistanceMetric): number;
|
|
938
|
+
/**
|
|
939
|
+
* Calculates the Silhouette Score for a clustering result.
|
|
940
|
+
* Measures how similar a point is to its own cluster compared to other clusters.
|
|
941
|
+
*
|
|
942
|
+
* ## What is Silhouette Score?
|
|
943
|
+
* A measure of how appropriate the clustering is, combining both cohesion and separation.
|
|
944
|
+
* Ranges from -1 to 1, where:
|
|
945
|
+
* - **1**: Perfect clustering (tight, well-separated clusters)
|
|
946
|
+
* - **0**: Overlapping clusters
|
|
947
|
+
* - **-1**: Wrong clustering (points assigned to wrong clusters)
|
|
948
|
+
*
|
|
949
|
+
* ## Business Interpretation:
|
|
950
|
+
* - **0.7-1.0**: Strong clustering structure
|
|
951
|
+
* - **0.5-0.7**: Reasonable structure
|
|
952
|
+
* - **0.25-0.5**: Weak structure
|
|
953
|
+
* - **< 0.25**: No meaningful structure
|
|
954
|
+
*
|
|
955
|
+
* @param {ClusterResult<TMetadata>} clusterResult - The clustering result
|
|
956
|
+
* @param {DistanceMetric} [metric='euclidean'] - Distance metric to use
|
|
957
|
+
* @returns {number} Silhouette score (-1 to 1, higher is better)
|
|
958
|
+
*
|
|
959
|
+
* @example
|
|
960
|
+
* ```typescript
|
|
961
|
+
* const result = service.KMeansCluster(3);
|
|
962
|
+
* const score = service.SilhouetteScore(result);
|
|
963
|
+
* if (score > 0.7) {
|
|
964
|
+
* console.log('Excellent clustering!');
|
|
965
|
+
* }
|
|
966
|
+
* ```
|
|
967
|
+
*
|
|
968
|
+
* @public
|
|
969
|
+
* @method
|
|
970
|
+
*/
|
|
57
971
|
SilhouetteScore(clusterResult: ClusterResult<TMetadata>, metric?: DistanceMetric): number;
|
|
972
|
+
/**
|
|
973
|
+
* Finds the optimal number of clusters using the elbow method.
|
|
974
|
+
* Tests different values of k and returns their inertias.
|
|
975
|
+
*
|
|
976
|
+
* ## What is the Elbow Method?
|
|
977
|
+
* A technique to find the optimal number of clusters by plotting inertia vs k.
|
|
978
|
+
* The "elbow" point where inertia stops decreasing rapidly suggests the optimal k.
|
|
979
|
+
*
|
|
980
|
+
* ## How to Use:
|
|
981
|
+
* 1. Run this method with a range of k values
|
|
982
|
+
* 2. Plot inertia (y-axis) vs k (x-axis)
|
|
983
|
+
* 3. Look for the "elbow" where the curve flattens
|
|
984
|
+
* 4. Choose k at the elbow point
|
|
985
|
+
*
|
|
986
|
+
* @param {number} minK - Minimum number of clusters to test
|
|
987
|
+
* @param {number} maxK - Maximum number of clusters to test
|
|
988
|
+
* @param {DistanceMetric} [metric='euclidean'] - Distance metric to use
|
|
989
|
+
* @returns {Map<number, number>} Map of k values to inertias
|
|
990
|
+
*
|
|
991
|
+
* @example
|
|
992
|
+
* ```typescript
|
|
993
|
+
* const elbowData = service.ElbowMethod(2, 10);
|
|
994
|
+
* elbowData.forEach((inertia, k) => {
|
|
995
|
+
* console.log(`k=${k}: inertia=${inertia.toFixed(2)}`);
|
|
996
|
+
* });
|
|
997
|
+
* // Look for the "elbow" in the results
|
|
998
|
+
* ```
|
|
999
|
+
*
|
|
1000
|
+
* @public
|
|
1001
|
+
* @method
|
|
1002
|
+
*/
|
|
58
1003
|
ElbowMethod(minK: number, maxK: number, metric?: DistanceMetric): Map<number, number>;
|
|
59
1004
|
}
|
|
60
1005
|
//# sourceMappingURL=SimpleVectorService.d.ts.map
|