Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[fix] Compute embedding cosine distance #35

Merged
merged 1 commit into from
Jul 15, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions src/embeddings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,16 +76,20 @@ impl Embedding {
Ok(embeddings.data.swap_remove(0))
}

pub fn magnitude(&self) -> f64 {
self.vec.iter().map(|x| x * x).sum::<f64>().sqrt()
}

pub fn distance(&self, other: &Self) -> f64 {
let dot_product: f64 = self
.vec
.iter()
.zip(other.vec.iter())
.map(|(x, y)| x * y)
.sum();
let product_of_lengths = (self.vec.len() * other.vec.len()) as f64;
let product_of_magnitudes = self.magnitude() * other.magnitude();

dot_product / product_of_lengths
1.0 - dot_product / product_of_magnitudes
}
}

Expand Down Expand Up @@ -145,8 +149,7 @@ mod tests {
total_tokens: 0,
},
};

assert_eq!(embeddings.distances()[0], 0.0);
assert_eq!(embeddings.distances()[0], 1.0);
}

#[test]
Expand All @@ -167,6 +170,6 @@ mod tests {
},
};

assert_ne!(embeddings.distances()[0], 0.0);
assert_eq!(embeddings.distances()[0], 0.29289321881345254);
}
}
Loading