-
-
Notifications
You must be signed in to change notification settings - Fork 290
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
3d9d227
commit b33aaac
Showing
14 changed files
with
421 additions
and
76 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
import type { Magnitude, VectorType } from '../types.js' | ||
|
||
export type SimilarVector = { | ||
id: string | ||
score: number | ||
} | ||
|
||
export function getMagnitude(vector: Float32Array, vectorLength: number): number { | ||
let magnitude = 0 | ||
for (let i = 0; i < vectorLength; i++) { | ||
magnitude += vector[i] * vector[i] | ||
} | ||
return Math.sqrt(magnitude) | ||
} | ||
|
||
// @todo: Write plugins for Node and Browsers to use parallel computation for this function | ||
export function findSimilarVectors( | ||
targetVector: Float32Array, | ||
vectors: Record<string, [Magnitude, VectorType]>, | ||
length: number, | ||
threshold = 0.8 | ||
) { | ||
const targetMagnitude = getMagnitude(targetVector, length); | ||
|
||
const similarVectors: SimilarVector[] = [] | ||
|
||
for (const [vectorId, [magnitude, vector]] of Object.entries(vectors)) { | ||
let dotProduct = 0 | ||
|
||
for (let i = 0; i < length; i++) { | ||
dotProduct += targetVector[i] * vector[i] | ||
} | ||
|
||
const similarity = dotProduct / (targetMagnitude * magnitude) | ||
|
||
if (similarity >= threshold) { | ||
similarVectors.push({ id: vectorId, score: similarity }) | ||
} | ||
} | ||
|
||
return similarVectors.sort((a, b) => b.score - a.score) | ||
} | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.