빅데이터

SBERT

도그사운드 2023. 12. 12. 19:35

NLI(Natural Language Inference)

문장 쌍을 수반(Entailment), 모순(Contradiction), 중립(Neutral)의 관계로 분류하는 문제. 전제와 가설은 다음과 같은 구조를 가진다.

Premise Label Hypothesis
A man inspects the uniform of a figure in some East Asian country. contradiction The man is sleeping.
An older and younger man smiling. neutral Two men are smiling and laughing at the cats playing on the floor.
A soccer game with multiple males playing. entailment Some men are playing a sport.

 

NLI를 학습하기 위해서는 각각의 문장에 대해서 Pooling을 거쳐서 벡터값을 얻는다. Pooling은 Max Pooling이 될 수도 있으며 Average Pooling이 될 수도 있다. 각기 벡터는 u, v, |u-v|로 구성된다.

 

문장 쌍의 구성에 따라 벡터의 차원과 클래스 차원이 정해지며 Softmax 방식으로 풀게 된다.

STS(Semantic Textual Similarity)

서로 다른 두 문장의 유사성을 구하는 문제. 0~5로 유사성의 척도가 결정된다.

코사인 유사도의 범위는 -1~1 사이로 계산된다. 유클리드 내적(dot product)를 변형하여

위와 같이 된다.

학습과정에서는 코사인 유사도와 레이블 유사도의 MSE를 최소화하는 방향으로 진행된다.

from sentence_transformers import SentenceTransformer, SentencesDataset, InputExample, losses

model = SentenceTransformer('nli-distilroberta-base-v2')
train_examples = [InputExample(texts=['My first sentence', 'My second sentence'], label=0.8),
    InputExample(texts=['Another pair', 'Unrelated sentence'], label=0.3)]
train_dataset = SentencesDataset(train_examples, model)

 

 

from sentence_transformers import SentenceTransformer
model = SentenceTransformer('sentence-transformers/xlm-r-100langs-bert-base-nli-stsb-mean-tokens')
model.encode('인생은 미완성')

 

array([ 6.29573524e-01,  2.75600497e-02,  1.02649355e+00, -5.96365146e-02,
        3.05736393e-01,  9.74804997e-01,  7.04725802e-01,  7.21675754e-02,
        ......
        2.30627418e-01, -8.40835154e-01, -2.58124918e-01, -2.03652337e-01,
       -7.09517300e-02, -1.53955728e-01, -3.18080485e-01, -3.44119035e-02],
      dtype=float32)

 

여기서 encode 메소드는?

이 메소드는 문장 임베딩을 계산합니다.
  • sentences: 임베딩할 문장들입니다.
  • batch_size: 계산에 사용될 배치 크기입니다.
  • show_progress_bar: 문장을 인코딩할 때 진행 상황 바를 출력할지 여부입니다.
  • output_value: 기본값은 'sentence_embedding'으로, 문장 임베딩을 얻기 위해 사용됩니다. 'token_embeddings'로 설정하면 워드피스 토큰 임베딩을 얻을 수 있습니다. 모든 출력 값을 얻고 싶다면 None으로 설정합니다.
  • convert_to_numpy: True로 설정하면 출력은 넘파이 벡터의 리스트가 됩니다. 그렇지 않으면 파이토치 텐서의 리스트가 됩니다.
  • convert_to_tensor: True로 설정하면 하나의 큰 텐서로 결과를 얻습니다. 이 설정은 convert_to_numpy 설정을 덮어씁니다.
  • device: 계산에 사용할 torch.device를 지정합니다.
  • normalize_embeddings: True로 설정하면 반환된 벡터는 길이가 1이 됩니다. 이 경우, 코사인 유사도 대신 더 빠른 점곱(dot-product)을 사용할 수 있습니다.
반환값:
  • 기본적으로 텐서의 리스트가 반환됩니다. convert_to_tensor를 사용하면 쌓인(stacked) 텐서가 반환됩니다. convert_to_numpy를 사용하면 넘파이 행렬이 반환됩니다.

 

 

 

 

 

 

 

 

 

 

 

 

 

'빅데이터' 카테고리의 다른 글

도로 노드링크 생성  (1) 2024.02.14
최적 경로 산출  (1) 2024.02.05
Recurrent Neural Network  (0) 2023.11.28
Polars  (0) 2023.11.21
패키지 설치 시 코드 에러 문제  (0) 2023.10.15