Skip to main content

SimilarityAlgorithms

Struct SimilarityAlgorithms 

Source
pub struct SimilarityAlgorithms;
Expand description

相似度算法工具集

提供多种向量相似度/距离的纯 Rust 计算,不依赖 pgvector。

Implementations§

Source§

impl SimilarityAlgorithms

Source

pub fn l2_distance(a: &[f32], b: &[f32]) -> f32

L2 距离(欧氏距离)

d = sqrt(sum((a_i - b_i)^2))

Source

pub fn inner_product(a: &[f32], b: &[f32]) -> f32

内积(点积)

d = sum(a_i * b_i)

Source

pub fn cosine_similarity(a: &[f32], b: &[f32]) -> f32

余弦相似度

d = (a·b) / (|a| * |b|)

Source

pub fn manhattan_distance(a: &[f32], b: &[f32]) -> f32

曼哈顿距离(L1 距离)

d = sum(|a_i - b_i|)

Source

pub fn l2_norm(v: &[f32]) -> f32

L2 范数(欧氏范数)

|v| = sqrt(sum(v_i^2))

Source

pub fn distance_to_similarity(metric: VectorMetric, distance: f32) -> f32

将距离值转换为相似度分数(值越大越相似)

  • Cosine:相似度 = 1 - 距离(距离 0 → 相似度 1)
  • Euclidean:相似度 = 1 / (1 + 距离)(距离 0 → 相似度 1)
  • DotProduct:相似度 = 点积本身(无转换)
Source

pub fn similarity(metric: VectorMetric, a: &[f32], b: &[f32]) -> f32

按指定度量计算相似度

Source

pub fn batch_similarity( metric: VectorMetric, query: &[f32], candidates: &[Vec<f32>], ) -> Vec<(usize, f32)>

批量计算查询向量与多个候选向量的相似度

返回 (索引, 相似度) 对的列表(未排序)

Source

pub fn batch_top_k( metric: VectorMetric, query: &[f32], candidates: &[Vec<f32>], top_k: usize, ) -> Vec<(usize, f32)>

批量计算并返回 top_k 结果(降序排列)

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.