AI/AI 서비스 개발
[AI 서비스 개발] 자연어처리, 허깅페이스 Transformers
brave_sol
2024. 12. 29. 15:04
1. 코랩 설치된 패키지 확인
!pip freeze
2. 로컬에서 pytorch 설치시 필요한 옵션 선택 후 명령어 받기

- pip3대신 pip로 설치
3. 트랜스포머 설치
pip install transformers
4. Text Classification
- https://huggingface.co/docs/transformers/tasks/sequence_classification
# step1: import modules
from transformers import pipeline
# step2: create inference object
# model 부분에 user이름/모델명 이 부분만 수정해주면 됨
classifier = pipeline("sentiment-analysis", model="stevhliu/my_awesome_model")
# step3: prepare data
text = "This was a masterpiece. Not completely faithful to the books, but enthralling from beginning to end. Might be my favorite of the three."
# step4: inference
result = classifier(text)
# step5: post processing
print(result)
- 모델을 변경하고 싶다면

classifier = pipeline("sentiment-analysis", model="snunlp/KR-FinBert-SC")
result = classifier("현대바이오, '폴리탁셀' 코로나19 치료 가능성에 19% 급등")
print(result)
- 욕설탐지ㅋㅋ
- Label 1: Curse detected로 잘 분류한다
classifier = pipeline("sentiment-analysis", model="2tle/korean-curse-detection")
result = classifier("시발")
print(result)
# Device set to use cpu
# [{'label': 'LABEL_1', 'score': 0.9701563119888306}]
5. Token-Classification
- 객체명 인식: Named entity recognition
- 문장에서 이름을 가진 객체를 인식: 지명, 시간, 사람이름 등
- 개인정보 탐지하고 삭제해줄 때 많이 사용
- 모델 선택: https://huggingface.co/Leo97/KoELECTRA-small-v3-modu-ner
# step1: import moduels
from transformers import pipeline
# step2: inference models
classifier = pipeline("ner", model="Leo97/KoELECTRA-small-v3-modu-ner")
# step3: load data
text = "내일 유재석과 서울역으로 가는 방법 안내해줘"
# step4: inference
result = classifier(text)
# step5: post processing
print(result)
6. Summarization
- 이제 llm 나와서 잘 안씀
- 추출식 요약과 추상식 요약
7. Multiple choice
# step1: import modules
from transformers import AutoModelForMultipleChoice
from transformers import AutoTokenizer
import torch
# step2: 모델이랑 전처리기
model = AutoModelForMultipleChoice.from_pretrained("stevhliu/my_awesome_swag_model")
tokenizer = AutoTokenizer.from_pretrained("stevhliu/my_awesome_swag_model")
# step3: 데이터 로드
prompt = "France has a bread law, Le Décret Pain, with strict rules on what is allowed in a traditional baguette."
candidate1 = "The law does not apply to croissants and brioche."
candidate2 = "The law applies to baguettes."
inputs = tokenizer([[prompt, candidate1], [prompt, candidate2]], return_tensors="pt", padding=True)
labels = torch.tensor(0).unsqueeze(0)
# step4: 추론
outputs = model(**{k: v.unsqueeze(0) for k, v in inputs.items()}, labels=labels)
logits = outputs.logits
# step5: 후처리
predicted_class = logits.argmax().item()
predicted_class
반응형