Hugging Face 감정 분석

# Hugging Face 감정 분석

![Sentiment Analysis](https://images.unsplash.com/photo-1504868584819-f8e8b4b6d7e3?q=80&w=2070&auto=format&fit=crop)

안녕하세요! 오늘은 **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 (