Files
2nd/10_Wiki/Topics/AI_and_ML/Sentiment-Analysis.md
T
Antigravity Agent f8b21af4be Wiki cleanup: error-doc removal, dedup merge, link normalization
10_Wiki/Topics 대규모 정리:
- 오류 캡처/미완성 stub 문서 227개 제거
- 교차폴더 중복 43클러스터 병합 (63파일 → redirect)
- 링크명 정규화: 깨진 링크 수정·redirect 직결·개념 매핑 ~2,400건
- 카테고리 MOC 6개 신규 생성
- Graph 섹션 미해결 related-keyword 링크 10,058건 제거

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 23:52:15 +09:00

185 lines
6.2 KiB
Markdown

---
id: wiki-2026-0508-sentiment-analysis
title: Sentiment Analysis
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [Opinion Mining, Emotion Detection, Polarity Classification]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
verification_status: applied
tags: [nlp, sentiment, classification, llm]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: python
framework: transformers/vllm
---
# Sentiment Analysis
## 매 한 줄
> **"매 sentiment analysis 의 lexicon → ML → transformer → LLM 의 evolution"**. 매 2026 의 SOTA 의 fine-tuned RoBERTa / DeBERTa-v3 (90%+ F1 on SST-5) + LLM zero-shot (Claude Opus 4.7, GPT-5) 의 nuance / aspect / sarcasm 의 handle. 매 multimodal (text + voice + face) 의 production 의 standard.
## 매 핵심
### 매 Approaches
- **Lexicon-based**: VADER, TextBlob — 매 fast, 매 nuance X.
- **Classical ML**: TF-IDF + LogReg / SVM — 매 baseline.
- **Transformer fine-tune**: RoBERTa, DeBERTa-v3, XLM-R — 매 SOTA classification.
- **LLM zero/few-shot**: Claude / GPT — 매 aspect, sarcasm, code-switch handle.
- **Multimodal**: text + audio (prosody) + visual (face) — call center, video.
### 매 Granularity
- **Document**: overall polarity.
- **Sentence**: per-sentence.
- **Aspect-based (ABSA)**: aspect + opinion + polarity (e.g., "battery=positive, screen=negative").
- **Emotion**: 6+ class (Ekman) — joy, anger, fear, ...
### 매 응용
1. **Social listening** — brand, product mention monitoring.
2. **Customer support** — ticket triage, escalation.
3. **Finance** — news / earnings call sentiment 의 alpha signal.
4. **Product feedback** — review aspect mining.
## 💻 패턴
### Transformer fine-tune (2026 stack)
```python
from transformers import AutoTokenizer, AutoModelForSequenceClassification, Trainer, TrainingArguments
from datasets import load_dataset
import numpy as np
from sklearn.metrics import f1_score
ds = load_dataset("sst2")
tok = AutoTokenizer.from_pretrained("microsoft/deberta-v3-large")
model = AutoModelForSequenceClassification.from_pretrained("microsoft/deberta-v3-large", num_labels=2)
def preprocess(b):
return tok(b["sentence"], truncation=True, max_length=256)
ds = ds.map(preprocess, batched=True)
def metrics(eval_pred):
preds = np.argmax(eval_pred.predictions, axis=1)
return {"f1": f1_score(eval_pred.label_ids, preds, average="macro")}
args = TrainingArguments(
output_dir="./out", num_train_epochs=3, per_device_train_batch_size=16,
learning_rate=2e-5, eval_strategy="epoch", bf16=True,
)
Trainer(model, args, train_dataset=ds["train"], eval_dataset=ds["validation"],
tokenizer=tok, compute_metrics=metrics).train()
```
### LLM zero-shot (Claude 4.7)
```python
import anthropic
client = anthropic.Anthropic()
def classify(text: str) -> dict:
msg = client.messages.create(
model="claude-opus-4-7",
max_tokens=200,
system="Classify sentiment as positive/negative/neutral and extract aspects. Return JSON: {\"sentiment\":..., \"confidence\":0-1, \"aspects\":[{\"aspect\":..., \"polarity\":...}]}",
messages=[{"role": "user", "content": text}],
)
import json
return json.loads(msg.content[0].text)
print(classify("Battery lasts forever but the screen is dim."))
```
### Aspect-based (ABSA) 의 fine-tune
```python
# 매 PyABSA / DeBERTa-v3-ABSA
from pyabsa import AspectPolarityClassification as APC
config = APC.APCConfigManager.get_apc_config_english()
config.model = APC.APCModelList.FAST_LSA_T_V2
config.pretrained_bert = "microsoft/deberta-v3-base"
trainer = APC.APCTrainer(config=config, dataset="Laptop14",
from_checkpoint="english", auto_device=True)
ckpt = trainer.load_trained_model()
ckpt.predict(text="Battery is great but screen is dim",
aspect="battery", print_result=True)
```
### VADER (lexicon baseline)
```python
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
v = SentimentIntensityAnalyzer()
print(v.polarity_scores("This is amazingly good!"))
# {'neg': 0.0, 'neu': 0.376, 'pos': 0.624, 'compound': 0.7424}
```
### Multimodal (text + audio)
```python
# 매 text RoBERTa + audio Wav2Vec2 의 late fusion
import torch
from transformers import AutoModel
text_emb = text_model(text_inputs).last_hidden_state.mean(1) # [B, 768]
audio_emb = audio_model(audio_inputs).last_hidden_state.mean(1) # [B, 768]
fused = torch.cat([text_emb, audio_emb], dim=-1)
logits = fusion_head(fused)
```
### vLLM batch inference (production)
```python
from vllm import LLM, SamplingParams
llm = LLM(model="meta-llama/Llama-3.3-8B-Instruct")
prompts = [f"Sentiment of: {t}\nReply only positive/negative/neutral." for t in texts]
sp = SamplingParams(temperature=0.0, max_tokens=10)
outs = llm.generate(prompts, sp)
```
### Calibration (production)
```python
# 매 LLM confidence 의 calibrate — temperature scaling
from sklearn.linear_model import LogisticRegression
calib = LogisticRegression()
calib.fit(val_logits.reshape(-1, 1), val_labels)
prod_prob = calib.predict_proba(test_logits.reshape(-1, 1))
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Real-time, simple | VADER / TextBlob |
| Domain-specific, large data | Fine-tune DeBERTa-v3 |
| Few labels, complex | LLM few-shot |
| Aspect granularity | PyABSA / GPT structured output |
| Multimodal | Late fusion or LLaVA-style |
**기본값**: DeBERTa-v3 fine-tune for prod, Claude/GPT few-shot for prototyping.
## 🔗 Graph
- 부모: [[NLP]]
- 변형: [[Emotion-Recognition]]
- Adjacent: [[Transformer_Architecture_and_LLM_Foundations|Transformers]]
## 🤖 LLM 활용
**언제**: zero-shot, sarcasm / nuance, low-data domain, ABSA structured output.
**언제 X**: high-throughput batch (use fine-tuned encoder), strict latency (<10ms).
## ❌ 안티패턴
- **Lexicon on noisy / sarcastic**: 매 fail on "great, just great".
- **No domain adaptation**: 매 finance / medical 의 generic model 의 underperform.
- **Single label**: 매 mixed sentiment ("good X, bad Y") 의 lose.
- **No calibration**: 매 LLM confidence 의 raw use.
## 🧪 검증 / 중복
- Verified (HuggingFace, PyABSA, Anthropic docs).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — full content with classical → LLM patterns |