Skip to content

Commit

Permalink
feat(metrics/similarity): create jaccard_index
Browse files Browse the repository at this point in the history
  • Loading branch information
drewxs committed Jan 26, 2024
1 parent d76381b commit 53b2d2d
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/metrics/similarity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,25 @@ pub fn cosine_similarity(a: &[f64], b: &[f64]) -> f64 {
let norm_b = norm_l2(b);
dot / (norm_a * norm_b)
}

/// Compute the Jaccard index between two sets.
///
/// # Examples
///
/// ```
/// # use engram::metrics::jaccard_index;
/// let a = [true, true, false, false];
/// let b = [true, false, true, false];
/// let c = [false, false, false, false];
/// assert_eq!(jaccard_index(&a, &b), 0.3333333333333333);
/// assert_eq!(jaccard_index(&a, &c), 0.0);
/// ```
pub fn jaccard_index(a: &[bool], b: &[bool]) -> f64 {
let intersection = a.iter().zip(b.iter()).filter(|(&a, &b)| a && b).count();
let union = a.iter().zip(b.iter()).filter(|(&a, &b)| a || b).count();
if union == 0 {
0.0
} else {
intersection as f64 / union as f64
}
}

0 comments on commit 53b2d2d

Please sign in to comment.