JavaScript · Set Similarity

Set Similarity

import * as numkong from 'numkong'; 8.0.0-rc.1 · b1f866ab

Binary metrics operate on packed storage rather than on generic boolean arrays.

import { toBinary, hamming, jaccard } from "numkong";

const a = toBinary(new Float32Array([1, -2, 3, -4, 5, -6, 7, -8]));
const b = toBinary(new Float32Array([1, 2, -3, -4, 5, 6, -7, -8]));

console.log(hamming(a, b));
console.log(jaccard(a, b));

This is a natural model for sign-quantized embeddings and semantic hashes.

API

Functions

hammingComputes the bitwise Hamming distance between two vectors.
numkong.ts:312 ↗
function hamming(
    a: Uint8Array | BinaryArray | TensorBase,
    b: Uint8Array | BinaryArray | TensorBase,
): number

Both vectors are treated as bit-packed, u1 dtype, where each byte holds 8 bits.

Use toBinary to convert numeric arrays to bit-packed format.

Parameters

aUint8Array | BinaryArray | TensorBaseThe first bit-packed vector, as Uint8Array, BinaryArray, or TensorBase.
bUint8Array | BinaryArray | TensorBaseThe second bit-packed vector, matching the length of a.

Returns

The Hamming distance, the number of differing bits, between a and b.
jaccardComputes the bitwise Jaccard distance between two vectors.
numkong.ts:328 ↗
function jaccard(
    a: Uint8Array | BinaryArray | TensorBase,
    b: Uint8Array | BinaryArray | TensorBase,
): number

Both vectors are treated as bit-packed, u1 dtype, where each byte holds 8 bits.

Use toBinary to convert numeric arrays to bit-packed format.

Parameters

aUint8Array | BinaryArray | TensorBaseThe first bit-packed vector, as Uint8Array, BinaryArray, or TensorBase.
bUint8Array | BinaryArray | TensorBaseThe second bit-packed vector, matching the length of a.

Returns

The Jaccard distance, 1 minus the Jaccard similarity, between a and b.
toBinaryQuantizes a numeric vector into a bit-packed binary representation.
numkong.ts:397 ↗
function toBinary(
    vector: Float32Array | Float64Array | Int8Array,
): Uint8Array

Converts each element to a single bit, 1 for positive values and 0 for non-positive ones, with element 0 in the most significant bit of byte 0, matching BinaryArray and the C nk_u1x8_t. This is the required format for hamming and jaccard distance functions. Dimension count must be a multiple of 8, the dimensions per byte.

Parameters

vectorFloat32Array | Float64Array | Int8ArrayThe vector to quantize and pack.

Returns

A bit-packed array where each byte contains 8 binary values.

Examples

const vec = new Float32Array([1.5, -2.3, 0.0, 3.1, -1.0, 2.0, 0.5, -0.5]);
const binary = toBinary(vec);
// Result: Uint8Array([0b10010110]) = [0x96]
//   bits 7..0: [1, 0, 0, 1, 0, 1, 1, 0] for elements [+, -, 0, +, -, +, +, -]

// Use with Hamming distance
const a = toBinary(new Float32Array([1, 2, 3, 4, 5, 6, 7, 8]));
const b = toBinary(new Float32Array([1, -2, 3, 4, 5, 6, 7, 8]));
const dist = hamming(a, b); // Counts differing bits