You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用@huggingface/transformers JS实现句子相似度重排遇问题求助

解决@huggingface/transformers JS实现句子重排序(相似度)的问题

你遇到的分数全为1的问题,根源是text-classification pipeline默认会对模型输出的logits做softmax转换为概率,而重排序模型(比如Cross-Encoder类)输出的logits本身就是相似度相关的得分,不需要这个转换。以下是适配pipeline的解决方案:

方案1:启用回归模式(推荐)

初始化text-classification pipeline时添加regression: true参数,跳过softmax步骤,直接返回模型原始输出的得分:

async function rerankBatch(
  anchor,
  candidates,
  modelPath = "<model path>"
) {

  const reranker = await pipeline('text-classification', modelPath, {
    local_files_only: true,
    regression: true, // 关键:禁用softmax,直接返回原始相似度得分
  });

  const inputs = candidates.map((candidate) => ({
    text: anchor,
    text_pair: candidate,
  }));

  const results = await reranker(inputs);

  const scoredCandidates = candidates.map((candidate, idx) => ({
    candidate,
    score: results[idx].score,
  }));

  scoredCandidates.sort((a, b) => b.score - a.score);
  return scoredCandidates;
}

方案2:自定义postProcess函数

如果回归模式不适用,可以直接覆盖pipeline的postProcess方法,手动处理模型输出的logits:

async function rerankBatch(
  anchor,
  candidates,
  modelPath = "<model path>"
) {

  const reranker = await pipeline('text-classification', modelPath, {
    local_files_only: true,
    // 自定义后处理,直接返回logits作为得分(根据模型输出结构调整索引)
    postProcess: (outputs) => outputs.map(logit => ({ score: logit[0] }))
  });

  const inputs = candidates.map((candidate) => ({
    text: anchor,
    text_pair: candidate,
  }));

  const results = await reranker(inputs);

  const scoredCandidates = candidates.map((candidate, idx) => ({
    candidate,
    score: results[idx].score,
  }));

  scoredCandidates.sort((a, b) => b.score - a.score);
  return scoredCandidates;
}

说明

  • 重排序模型(如Cross-Encoder)的输出通常是一个连续值,表示输入句子对的相似度,不需要经过softmax转换为概率。
  • 若你的模型是二分类结构(输出"相似"/"不相似"两类),可以设置return_all_scores: true,然后提取对应类别的得分(比如取"相似"类的score)。

内容的提问来源于stack exchange,提问作者Edv Beq

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 23:38:16