0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

小学校3年生でもわかる図解Bi-Encoder と Cross-Encoder

0
Posted at

image.png

image.png

image.png

image.png

image.png

image.png

image.png

image.png

image.png

image.png

image.png

image.png

image.png

image.png

image.png

pip install sentence-transformers torch

image.png

from sentence_transformers import SentenceTransformer, util


# Bi-Encoderのモデルを用意する

model = SentenceTransformer(

    "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"

)


# さくらさんの質問

question = "宇宙で水はどう使うの?"


# 答えの候補

sentences = [

    "宇宙船では水をくり返し使います。",

    "宇宙飛行士は訓練をします。",

    "ねこはボールで遊びます。",

]


# 質問と候補を、べつべつに数字カードへ変える

question_vector = model.encode(

    question,

    convert_to_tensor=True,

)


sentence_vectors = model.encode(

    sentences,

    convert_to_tensor=True,

)


# 数字カードの近さを計算する

scores = util.cos_sim(

    question_vector,

    sentence_vectors,

)[0]


# 点数が高い順に表示する

ranking = sorted(

    zip(sentences, scores),

    key=lambda item: item[1],

    reverse=True,

)


for rank, (sentence, score) in enumerate(ranking, start=1):

    print(f"{rank}位: {sentence}")

    print(f"似ている度: {score.item():.3f}\n")

image.png

from sentence_transformers import CrossEncoder


# Cross-Encoderのモデルを用意する

model = CrossEncoder(

    "cross-encoder/mmarco-mMiniLMv2-L12-H384-v1"

)


question = "宇宙で水はどう使うの?"


sentences = [

    "宇宙船では水をくり返し使います。",

    "宇宙飛行士は訓練をします。",

    "ねこはボールで遊びます。",

]


# 質問と候補をペアにする

pairs = [

    [question, sentence]

    for sentence in sentences

]


# ペアをいっしょに読んで点数をつける

scores = model.predict(pairs)


# 点数が高い順に並べる

ranking = sorted(

    zip(sentences, scores),

    key=lambda item: item[1],

    reverse=True,

)


for rank, (sentence, score) in enumerate(ranking, start=1):

    print(f"{rank}位: {sentence}")

    print(f"相性スコア: {score:.3f}\n")

image.png

image.png

image.png

image.png

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?