fix: MMRSelect 使用字符 bigram Jaccard 相似度替代空向量 cosineSimilarity
原问题:Rust LanceDB IPC search 不返回 vector,导致 cosineSimilarity 永远为 0, MMR 退化为纯相关性排序(无多样性去重效果)。 修复:改用 Content 字段的字符 bigram Jaccard 相似度,并修正 MMR 公式 (从 (1-λ)*rel - λ*maxSim 改为 (1-λ)*rel + λ*(1-maxSim), 使 maxSim 高时 MMR 降低,符合设计文档 §2.6)
This commit is contained in:
@@ -234,7 +234,38 @@ func (p *RecallPipeline) Recall(query, namespace string, topK int, diversity flo
|
||||
return results, nil
|
||||
}
|
||||
|
||||
// MMRSelect 多样性去重 — 开放给 recall/debug 诊断端点
|
||||
// jaccardBigramSimilarity 计算两个文本的字符 bigram Jaccard 相似度(用于 MMR 去重)
|
||||
func jaccardBigramSimilarity(a, b string) float64 {
|
||||
bgA := make(map[string]bool)
|
||||
bgB := make(map[string]bool)
|
||||
runes := []rune(a)
|
||||
for i := 0; i < len(runes)-1; i++ {
|
||||
bgA[string(runes[i:i+2])] = true
|
||||
}
|
||||
runes = []rune(b)
|
||||
for i := 0; i < len(runes)-1; i++ {
|
||||
bgB[string(runes[i:i+2])] = true
|
||||
}
|
||||
if len(bgA) == 0 && len(bgB) == 0 {
|
||||
return 1.0 // 两个空文本视为相同
|
||||
}
|
||||
if len(bgA) == 0 || len(bgB) == 0 {
|
||||
return 0.0
|
||||
}
|
||||
intersection := 0
|
||||
for k := range bgA {
|
||||
if bgB[k] {
|
||||
intersection++
|
||||
}
|
||||
}
|
||||
union := len(bgA) + len(bgB) - intersection
|
||||
if union == 0 {
|
||||
return 0.0
|
||||
}
|
||||
return float64(intersection) / float64(union)
|
||||
}
|
||||
|
||||
// MMRSelect 多样性去重 — 使用文本 bigram Jaccard 相似度(向量由 Rust LanceDB 返回但为空,改用文本)
|
||||
func MMRSelect(reranked []models.RerankResult, candidates []models.MemoryRecord, k int, lambda float64) []int {
|
||||
if len(reranked) == 0 {
|
||||
return nil
|
||||
@@ -259,13 +290,14 @@ func MMRSelect(reranked []models.RerankResult, candidates []models.MemoryRecord,
|
||||
maxSim := 0.0
|
||||
for _, si := range selected {
|
||||
if si < len(candidates) && ci < len(candidates) {
|
||||
sim := cosineSimilarity(candidates[ci].Vector, candidates[si].Vector)
|
||||
sim := jaccardBigramSimilarity(candidates[ci].Content, candidates[si].Content)
|
||||
if sim > maxSim {
|
||||
maxSim = sim
|
||||
}
|
||||
}
|
||||
}
|
||||
mmr := (1-lambda)*rel - lambda*maxSim
|
||||
// MMR = (1-λ)*rel + λ*(1-maxSim)
|
||||
mmr := (1-lambda)*rel + lambda*(1-maxSim)
|
||||
if mmr > bestScore {
|
||||
bestScore = mmr
|
||||
bestIdx = i
|
||||
|
||||
Reference in New Issue
Block a user