1. sentence-transformer 활용하기
◼ sentence-transformer 라이브러리 _ Hugging Face
링크: https://huggingface.co/sentence-transformers/distiluse-base-multilingual-cased-v1
◼ 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] |
예시로 주어진 두 문장:
|
[[-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차원 배열로, 특정 값 하나를 포함하고 있습니다. 각 값은 모델의 계산 결과로 나온 수치이며, 일반적으로 이 값은 모델의 출력이나 계산된 특정 특성값을 나타냅니다.
|
◼ 긍정/부정 확인
# 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}] |
단일 문장 분석:
|
◼ 뒷 문장 생성
# 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': '루트비히 판 베토벤은 독일의 서양 고전'} |
결과 분석:
|
◼ 번역하기
# 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'})이 호환되지 않음을 나타냅니다.
|
◼ 요약하기
# 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 |