langchain 当使用MAX_INNER_PRODUCT和normalize_L2时,FAISS的警告和相关性评分不正确,

64jmpszr  于 2个月前  发布在  其他
关注(0)|答案(2)|浏览(28)

检查其他资源

  • 为这个问题添加了一个非常描述性的标题。
  • 使用集成搜索在LangChain文档中进行了搜索。
  • 使用GitHub搜索找到了一个类似的问题,但没有找到。
  • 我确信这是LangChain中的一个bug,而不是我的代码。
  • 通过更新到LangChain的最新稳定版本(或特定集成包)无法解决此bug。

示例代码

from langchain_community.vectorstores import FAISS
from langchain_aws import BedrockEmbeddings

texts = ["I like apples", "I like oranges"]
distance_strategy = "MAX_INNER_PRODUCT"

embeddings = BedrockEmbeddings(
    region_name="us-east-1", model_id="amazon.titan-embed-text-v1"
)

normalize_L2 = False
vectorstore = FAISS.from_texts(
    texts,
    embeddings,
    distance_strategy=distance_strategy,
    normalize_L2=normalize_L2
)
results = vectorstore.similarity_search_with_score("I like apples", k=1)
print(results)

normalize_L2 = True
vectorstore = FAISS.from_texts(
    texts,
    embeddings,
    distance_strategy=distance_strategy,
    normalize_L2=normalize_L2
)
results = vectorstore.similarity_search_with_score("I like apples", k=1)
print(results)
results = vectorstore.similarity_search_with_relevance_scores("I like apples", k=1)
print(results)

错误信息和堆栈跟踪(如果适用)

  • 无响应*

描述

根据FAISS,首先需要对向量进行归一化,然后使用内积构建索引以获得余弦相似度。然而,运行上面的代码时,当设置normalize_L2 = True时,会出现警告:

UserWarning: Normalizing L2 is not applicable for metric type: MAX_INNER_PRODUCT

此外,相关性分数不符合直觉。如果我们计算余弦相似度,那么从similarity_search_with_relevance_scores获得的相关性分数应该与从similarity_search_with_score获得的相关性分数相同。然而,实现将导致两个向量更接近时的相关性分数较小。
langchain/libs/core/langchain_core/vectorstores/base.py
第422行至第427行 fd54619
| def_max_inner_product_relevance_score_fn(distance: float) ->float: |
| """将距离归一化为[0, 1]范围内的分数.""" |
| if distance > 0: |
| return 1.0 - distance |
| |
| return -1.0 * distance |

zpjtge22

zpjtge221#

关于相关性分数问题,之前提到了一些问题:#9519#22209#14948。而normalize_L2问题从未讨论过。我想这是因为许多嵌入模型对嵌入进行归一化处理,而Titan嵌入模型没有这样做。
运行上述代码将给出以下输出:

[(Document(page_content='I like apples'), 388.789)]
[(Document(page_content='I like apples'), 1.0000002)]
[(Document(page_content='I like apples'), -2.384185791015625e-07)]
0pizxfdo

0pizxfdo2#

如果这种行为确实出乎意料,我可以帮忙提交PR来解决这个问题。

相关问题