# Hugging Face 감정 분석

안녕하세요! 오늘은 **Hugging Face Transformers**를 사용해서 감정 분석을 하는 방법을 알아봅니다! 🎭
## 감정 분석이란?
텍스트에서 긍정/부정/중립 감정을 파악하는 NLP 기술입니다.
**예시:**
– “이 제품 정말 좋아요” → 긍정 (0.9)
– “별로 마음에 안 들어요” → 부정 (0.8)
– “그냥 평범해요” → 중립 (0.5)
—
## 1. 환경 설정
“`bash
pip install transformers torch
“`
—
## 2. 간단한 감정 분석
“`python
from transformers import pipeline
# 파이프라인 생성
sentiment_pipeline = pipeline(“sentiment-analysis”)
# 분석 실행
result = sentiment_pipeline(“이 제품 정말 좋아요!”)
print(result)
# [{‘label’: ‘POSITIVE’, ‘score’: 0.9998}]
“`
—
## 3. 한국어 감정 분석
한국어 모델 사용:
“`python
from transformers import pipeline
# 한국어 모델 로드
classifier = pipeline(
“sentiment-analysis”,
model=”sangminlee/deberta-base-korean-sentiment”
)
results = classifier([
“이 영화 정말 재미있어요!”,
“시간 아까워요”,
“그냥 그래요”
])
for result in results:
print(result)
“`
—
## 4. 여러 텍스트 동시 분석
“`python
texts = [
“최고의 서비스입니다!”,
“너무 늦게 왔어요”,
“그냥 평범해요”,
“강력 추천합니다!”,
“다시는 안 이용할게요”
]
results = sentiment_pipeline(texts)
for text, result in zip(texts, results):
label = result[‘label’]
score = result[‘score’]
emoji = “😊” if label == “POSITIVE” else “😞”
print(f”{emoji} {text} ({label}: {score:.2f})”)
“`
—
## 5. 고급 기능
### 감정 점수 세부화
“`python
from transformers import AutoModelForSequenceClassification, AutoTokenizer
import torch
model_name = “cardiffnlp/twitter-roberta-base-sentiment”
model = AutoModelForSequenceClassification.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name)
text = “이 제품 사용하기 정말 편해요”
# 토큰화
inputs = tokenizer(text, return_tensors=”pt”)
# 예측
with torch.no_grad():
outputs = model(**inputs)
predictions = torch.nn.functional.softmax(outputs.logits, dim=-1)
# 결과
labels = [“부정”, “중립”, “긍정”]
for label, score in zip(labels, predictions[0]):
print(f”{label}: {score.item():.2%}”)
“`
—
## 6. 웹 앱에 통합
### Flask 백엔드
“`python
from flask import Flask, request, jsonify
from transformers import pipeline
app = Flask(__name__)
classifier = pipeline(“sentiment-analysis”)
@app.route(‘/analyze’, methods=[‘POST’])
def analyze():
data = request.json
text = data.get(‘text’, ”)
result = classifier(text)[0]
return jsonify({
‘label’: result[‘label’],
‘score’: result[‘score’]
})
if __name__ == ‘__main__’:
app.run(debug=True)
“`
—
### React 프론트엔드
“`tsx
import { useState } from ‘react’;
export default function SentimentAnalyzer() {
const [text, setText] = useState(”);
const [result, setResult] = useState(null);
const analyze = async () => {
const res = await fetch(‘/api/analyze’, {
method: ‘POST’,
headers: { ‘Content-Type’: ‘application/json’ },
body: JSON.stringify({ text }),
});
const data = await res.json();
setResult(data);
};
return (
);
}
“`
—
## 7. 실시간 스트리밍
“`python
from transformers import pipeline
import time
classifier = pipeline(“sentiment-analysis”, device=0) # GPU
def analyze_stream(text_stream):
for chunk in text_stream:
result = classifier(chunk)
yield result
# 사용
texts = [“좋아요”, “정말 좋아요”, “최고예요”]
for result in analyze_stream(texts):
print(result)
time.sleep(0.5)
“`
—
## 8. 커스텀 모델 훈련
“`python
from transformers import AutoTokenizer, AutoModelForSequenceClassification, TrainingArguments, Trainer
from datasets import load_dataset
# 데이터셋 로드
dataset = load_dataset(“imdb”)
# 토크나이저 로드
tokenizer = AutoTokenizer.from_pretrained(“bert-base-uncased”)
# 전처리
def tokenize_function(examples):
return tokenizer(examples[“text”], padding=”max_length”, truncation=True)
tokenized_datasets = dataset.map(tokenize_function, batched=True)
# 모델 로드
model = AutoModelForSequenceClassification.from_pretrained(
“bert-base-uncased”,
num_labels=2
)
# 훈련
training_args = TrainingArguments(
output_dir=”./results”,
per_device_train_batch_size=8,
num_train_epochs=3,
)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_datasets[“train”],
eval_dataset=tokenized_datasets[“test”],
)
trainer.train()
“`
—
## 9. 성능 최적화
### GPU 가속
“`python
classifier = pipeline(“sentiment-analysis”, device=0) # 첫 번째 GPU
“`
### 배치 처리
“`python
results = classifier(texts, batch_size=32)
“`
### 모델 양자화
“`python
from transformers import pipeline, quantization_config
config = quantization_config(load_in_8bit=True)
classifier = pipeline(
“sentiment-analysis”,
model=”bert-base-uncased”,
quantization_config=config
)
“`
—
## 10. 응용 예시
### 리뷰 감정 분석
“`python
reviews = [
{“text”: “최고의 제품이에요!”, “rating”: 5},
{“text”: “별로에요”, “rating”: 1},
]
sentiments = classifier([r[“text”] for r in reviews])
for review, sentiment in zip(reviews, sentiments):
review[“sentiment”] = sentiment
print(review)
“`
—
### 소셜 미디어 모니터링
“`python
import tweepy
# 트위터 API 설정
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
# 트윗 가져오기
tweets = api.user_timeline(screen_name=”user”, count=10)
# 감정 분석
sentiments = classifier([tweet.text for tweet in tweets])
for tweet, sentiment in zip(tweets, sentiments):
print(f”{tweet.text}: {sentiment[‘label’]}”)
“`
—
## 결론
Hugging Face는 감정 분석을 쉽게 구현할 수 있는 강력한 도구입니다!
**핵심 포인트:**
– ✅ 사전 훈련된 모델 즉시 사용
– ✅ 다양한 언어 지원
– ✅ 커스텀 훈련 가능
– ✅ GPU 가속 지원
—
## 다음 단계
– 🎯 특정 도메인에 맞는 모델 찾기
– 🔧 커스텀 모델 훈련
– 📊 대규모 데이터 처리
## 참고 자료
– [Hugging Face 문서](https://huggingface.co/docs)
– [Sentiment Analysis Tutorial](https://huggingface.co/tasks/sentiment-analysis)
—
질문이 있나요? 댓글로 남겨주세요! 😊
**다음 포스팅:** Pinecone 벡터 DB 입문