본문 바로가기
AI/자연어처리

19. sentence-transformer 활용

by 사라리24 2025. 1. 3.



1.  sentence-transformer 활용하기

 

 

sentence-transformer 라이브러리 _ Hugging Face

링크: https://huggingface.co/sentence-transformers/distiluse-base-multilingual-cased-v1

 

sentence-transformers/distiluse-base-multilingual-cased-v1 · Hugging Face

sentence-transformers/distiluse-base-multilingual-cased-v1 This is a sentence-transformers model: It maps sentences & paragraphs to a 512 dimensional dense vector space and can be used for tasks like clustering or semantic search. Usage (Sentence-Transform

huggingface.co

 

 

sentence-transformer  라이브러리 설치하기


       

            pip install -U sentence-transformers



 

 

 

 

모델을 간단히 사용해보기


       

            # step1 : 라이브러리 넣기
            from sentence_transformers import SentenceTransformer

            # step2 : 모델 초기화
            model = SentenceTransformer('sentence-transformers/distiluse-base-multilingual-cased-v1')

            # step3 : 데이터 넣기
            sentences = ["This is an example sentence", "Each sentence is converted"]

            # step4 : 추론
            embeddings = model.encode(sentences)

            # step5 : 결과 출력
            print(embeddings)
            print(embeddings.shape)


-----------------------------------------------------------------------------------------------------------------------------------------------------------------
(transformer) C:\Users\602-01\Desktop\Leesarah\transformer>python ex01-1.py
modules.json: 100%|████████████████████████████████████| 341/341 [00:00<00:00, 341kB/s]
C:\Users\602-01\anaconda3\envs\transformer\lib\site-packages\huggingface_hub\file_download.py:140: UserWarning: `huggingface_hub` cache-system uses symlinks by default to efficiently store duplicated files but your machine does not support them in C:\Users\602-01\.cache\huggingface\hub\models--sentence-transformers--distiluse-base-multilingual-cased-v1. Caching files will still work but in a degraded version that might require more space on your disk. This warning can be disabled by setting the `HF_HUB_DISABLE_SYMLINKS_WARNING` environment variable. For more details, see https://huggingface.co/docs/huggingface_hub/how-to-cache#limitations.
To support symlinks on Windows, you either need to activate Developer Mode or to run Python as an administrator. In order to activate developer mode, see this article: https://docs.microsoft.com/en-us/windows/apps/get-started/enable-your-device-for-development 
  warnings.warn(message)
config_sentence_transformers.json: 100%|██████████████████████| 122/122 [00:00<?, ?B/s]
README.md: 100%|██████████████████████████████████████████| 2.47k/2.47k [00:00<?, ?B/s]
sentence_bert_config.json: 100%|████████████████████████████| 53.0/53.0 [00:00<?, ?B/s]
config.json: 100%|████████████████████████████████████████████| 556/556 [00:00<?, ?B/s]
model.safetensors: 100%|████████████████████████████| 539M/539M [00:07<00:00, 69.8MB/s]
tokenizer_config.json: 100%|██████████████████████████████████| 452/452 [00:00<?, ?B/s]
vocab.txt: 100%|████████████████████████████████████| 996k/996k [00:00<00:00, 1.89MB/s] 
tokenizer.json: 100%|█████████████████████████████| 1.96M/1.96M [00:00<00:00, 2.57MB/s] 
special_tokens_map.json: 100%|████████████████████████████████| 112/112 [00:00<?, ?B/s] 
1_Pooling/config.json: 100%|██████████████████████████████████| 190/190 [00:00<?, ?B/s] 
pytorch_model.bin: 100%|██████████████████████████| 1.58M/1.58M [00:00<00:00, 20.8MB/s] 
2_Dense/config.json: 100%|████████████████████████████████████| 114/114 [00:00<?, ?B/s] 
model.safetensors: 100%|██████████████████████████| 1.58M/1.58M [00:00<00:00, 4.26MB/s] 


예시로 주어진 두 문장:
  1. "This is an example sentence"
  2. "Each sentence is converted"
[[-0.03885619  0.01854845 -0.04066143 ...  0.01009196 -0.01660534
  -0.00138949]
 [-0.00059498 -0.00924197 -0.05870508 ...  0.01638778  0.01509567
  -0.04368324]]

ㄴ 이 값들은 첫 번째 문장의 768차원 벡터를 구성하는 수치입니다.
ㄴ 각 값은 모델이 문장 내 특정 요소(단어, 구문, 의미 등)에 대해 학습한 특징을 나타냅니다.

* 출력된 벡터는 데이터(문장) 간의 관계를 나타냅니다.
* 각 벡터는 문장의 의미적 특성을 요약한 고차원 표현으로, 문장이 가진 의미나 내용이 어떻게 표현되는지를 나타냅니다.

 

 

유사도 분석


       

            #step 1
            from sentence_transformers import SentenceTransformer


            #step 2
            model = SentenceTransformer('sentence-transformers/distiluse-base-multilingual-cased-v1')


            #step 3
            sentences1 = ["강아지"]
            sentences2 = ["고양이"]
            sentences3 = ["화장실"]


            #step 4
            emb1 = model.encode(sentences1)
            emb2 = model.encode(sentences2)
            emb3 = model.encode(sentences3)


            #step 5
            sim1 = model.similarity(emb1,emb2)
            sim2 = model.similarity(emb2,emb3)
            sim3 = model.similarity(emb3,emb1)


            print(sim1,sim2,sim3)




[결과]

tensor([[0.5982]]) tensor([[0.3040]]) tensor([[0.3520]])

이 출력은 텐서 형태로 표현된 값들입니다. 각 텐서는 1차원 배열로, 특정 값 하나를 포함하고 있습니다.
각 값은 모델의 계산 결과로 나온 수치이며, 일반적으로 이 값은 모델의 출력이나 계산된 특정 특성값을 나타냅니다.


  • 첫 번째 문장과 두 번째 문장의 유사도는 0.5982로 상대적으로 높습니다.
  • 두 번째 문장과 세 번째 문장의 유사도는 0.3040으로 낮고,
    첫 번째 문장과 세 번째 문장의 유사도는 0.3520으로 둘 다 낮은 수준입니다.

 

 

긍정/부정 확인


       
        # step 1
        from transformers import pipeline

        # step 2
        cls = pipeline("sentiment-analysis")


        # 단일 문장 분석
        result = cls("슬퍼 :( ")
        print(result)


        # 여러 문장 분석
        results = cls([
            "너는 정말 이쁘구나",
            "너의 마음씨는 정말 곱구나"
        ])
        print(results)




[결과]

[{'label': 'POSITIVE', 'score': 0.5290889739990234}]
[{'label': 'POSITIVE', 'score': 0.7377600073814392}, 
{'label': 'POSITIVE', 'score': 0.7755917906761169}]

단일 문장 분석:
  • result = cls("슬퍼 :( "): 이 코드는 "슬퍼 :("라는 단일 문장을 분석합니다.
  • 출력은:
    • label: 감정 분석의 결과로 문장은 긍정적(POSITIVE)이라고 예측되었습니다.
    • score: 이 값은 모델의 확신도를 나타냅니다. 0.529는 모델이 이 문장이 긍정적이라는 예측에 대한 확신도인데, 이는 보통 50% 확신 정도로 해석할 수 있습니다. 따라서 모델이 "슬퍼 :("라는 문장에 대해 긍정적인 감정을 예측한 것에 대해서는 불확실성을 가지고 있다는 의미입니다.

      여러 문장 분석
      :
      • results = cls([ "너는 정말 이쁘구나", "너의 마음씨는 정말 곱구나" ]): 이 코드는 두 개의 문장을 분석합니다.
      • 출력은:
        • 두 문장 모두 긍정적(POSITIVE) 감정으로 분석되었습니다.
        • 첫 번째 문장 "너는 정말 이쁘구나"에 대한 모델의 확신도는 0.7378이고, 두 번째 문장 "너의 마음씨는 정말 곱구나"에 대한 확신도는 0.7756입니다. 두 문장 모두 높은 확신을 가지고 긍정적 감정을 예측하고 있습니다.
  •  

 

 

 

뒷 문장 생성


       
 
            # step 1
            from transformers import pipeline


            # step 2
            gen = pipeline("text-generation", model='skt/kogpt2-base-v2')


            # 간단한 텍스트 생성
            result = gen("여러분을 만나서 반갑습니다. 저는 김재욱입니다. 저의 강의를 시작", max_length=30, num_return_sequences=2)
            print(result)


 

[결과]


[{'generated_text': '여러분을 만나서 반갑습니다. 저는 김재욱입니다. 저의 강의를 시작하겠습니다. 지금 저 
김재욱이라고 합니다. 한 분 한 분이 그'}, {'generated_text': '여러분을 만나서 반갑습니다. 저는 김재욱입니 
다. 저의 강의를 시작하기 위해 지난주에 서울에 갔다 왔습니다. 그런데 오늘 제가 이 책을'}]
  • 첫 번째 결과:
    • 생성된 텍스트: "여러분을 만나서 반갑습니다. 저는 김재욱입니다. 저의 강의를 시작하겠습니다. 지금 저 김재욱이라고 합니다. 한 분 한 분이 그"
    • 이 텍스트는 첫 번째 문장(강의를 시작한다고 말하는 부분)을 이어서 생성된 것입니다. 모델은 반복적으로 문장을 이어가는 경향이 있는데, 여기서 "한 분 한 분이 그"로 끝나면서 문장이 중단된 모습입니다.
  • 두 번째 결과:
    • 생성된 텍스트: "여러분을 만나서 반갑습니다. 저는 김재욱입니다. 저의 강의를 시작하기 위해 지난주에 서울에 갔다 왔습니다. 그런데 오늘 제가 이 책을"
    • 이 텍스트는 첫 번째 문장에 이어서, "지난주에 서울에 갔다 왔습니다"라는 정보를 추가합니다. 이후 "이 책을"로 끝나면서 문장이 끊어진 상태입니다.

 

 

◼ 질문에 대한 답 추출해내기


       
            # step 1
            from transformers import pipeline


            # step 2
            qa = pipeline("question-answering", model='klue/roberta-base')


            # 간단한 텍스트 생성
            context = '''
            루트비히 판 베토벤은 독일의 서양 고전 음악 작곡가이자 피아니스트이다. 독일의 본에서 태어났으며, 성인이 된 이후 거의 오스트리아 빈에서 살았다.
            '''
            result = qa(question="베토벤이 태어난 곳은 어디입니까?", context=context)


            print(result)


 

[결과]

{'score': 0.0015245614340528846, 'start': 1, 'end': 22, 'answer': '루트비히 판 베토벤은 독일의 서양 고전'}

결과 분석:

  • 질문: "베토벤이 태어난 곳은 어디입니까?"
  • 주어진 텍스트: 루트비히 판 베토벤은 독일의 서양 고전 음악 작곡가이자 피아니스트이다. 독일의 본에서 태어났으며, 성인이 된 이후 거의 오스트리아 빈에서 살았다.
  • 모델의 응답:
    • score: 0.0015라는 낮은 점수는 모델이 추출한 답변에 대한 확신도가 낮음을 의미합니다.
      이는 모델이 질문에 대한 정확한 답을 찾지 못했다고 해석할 수 있습니다.
    • start: 1, end: 22: 이 값은 모델이 텍스트에서 답변이 시작하는 위치와 끝나는 위치를 나타냅니다.
      하지만 실제로 추출된 답변은 "루트비히 판 베토벤은 독일의 서양 고전"으로,
      질문에 대한 정확한 답변이 아니라 문장의 일부분이 포함된 형태입니다.
    • answer: "루트비히 판 베토벤은 독일의 서양 고전":
      이 부분은 텍스트에서 추출된 결과로,질문에 맞는 정확한 답변인 "본"이 아니라 문장 내 일부 문구가 추출되었습니다.

 

 

번역하기


       
            # step 1
            from transformers import pipeline


            # step 2
            trans = pipeline("translation", model='circulus/kobart-trans-ko-en-v2')


            # 간단한 텍스트 생성
            result = trans("오늘 행복한 금요일 입니다.")
            print(result)


 

[결과]

You passed along `num_labels=3` with an incompatible id to label map: {'0': 'NEGATIVE', 
'1': 'POSITIVE'}. The number of labels wil be overwritten to 2.
You passed along `num_labels=3` with an incompatible id to label map: {'0': 'NEGATIVE', 
'1': 'POSITIVE'}. The number of labels wil be overwritten to 2.
Device set to use cpu
[{'translation_text': 'Today is a happy Friday'}]

오류 메시지는 지정한 레이블 수(num_labels=3)와 모델에 제공된 레이블 맵({'0': 'NEGATIVE', '1': 'POSITIVE'})이 호환되지 않음을 나타냅니다.
  • 오류 내용: num_labels=3을 사용했지만, 모델의 레이블 맵에는 2개의 레이블만 정의되어 있습니다. 레이블 맵은 '0': 'NEGATIVE'와 '1': 'POSITIVE'로 되어 있기 때문에, num_labels=3은 2로 덮어쓰여졌습니다. 즉, 모델은 레이블 수를 2로 설정하고 사용합니다.
  • 해결 방법: 3개의 레이블을 사용하려면 레이블 맵을 3개의 레이블로 업데이트해야 합니다(예: '2': 'NEUTRAL' 추가). 2개의 레이블만 사용하고 싶다면, num_labels를 2로 설정하여 레이블 맵과 일치시켜야 합니다.
번역 결과:
  • 번역: "Today is a happy Friday."
    한국어 문장 "오늘 행복한 금요일 입니다."가 영어로 번역된 결과입니다

 

 

요약하기


       
            # step 1
            from transformers import pipeline


            # step 2
            summarizer = pipeline("summarization")


            # 간단한 텍스트 생성
            text = """
            America has changed dramatically during recent years. Not only has the number of
            graduates in traditional engineering disciplines such as mechanical, civil, electrical,
            chemical, and aeronautical engineering declined, but in most of the premier American
            universities engineering curricula now concentrate on and encourage largely the study
            of engineering science.
            """
            result = summarizer(text)
            print(result)

 
[결과]


[{'summary_text': 'America has changed dramatically during recent years. The number of students in traditional engineering disciplines has declined. In most of the premier American universities engineering curricula now concentrate on and encourage largely the study of engineering science. The U.S. has a long way 
to go to reach its potential as an engineering powerhouse.'}]

요약된 텍스트:
  • 최근 몇 년 동안 미국은 크게 변화했습니다. 전통적인 공학 분야에서 학생 수가 감소했으며, 대부분의 미국 주요 대학에서는 공학 교육과정이 주로 공학 과학 연구에 집중하고 있습니다. 미국은 공학 강국으로서 잠재력에 도달하기 위해 여전히 많은 노력이 필요합니다.

 

'AI > 자연어처리' 카테고리의 다른 글

18. PLM을 이용한 실습  (0) 2024.07.12
17. 자연어처리를 위한 모델 학습  (0) 2024.07.11
16. 문장 임베딩 | GPT  (0) 2024.07.05
15. 문장임베딩 | BERT  (1) 2024.07.05
14. 문장 임베딩 | ELmo / Transformer  (1) 2024.07.04