Files
2nd/10_Wiki/Topic_Programming/AI_and_ML/Sentiment-Analysis.md
T
Antigravity Agent 9148c358d0 docs(10_Wiki): 위키 전체 재구성 — Topic_* 폴더를 4개 카테고리로 통합 + 대규모 중복 제거
Topic_Agent/Topic_Blog/Topics/Topics_Biz/Topics_Meeting/Topics_Rag의 마크다운 지식 문서를
Topic_General/Topic_Programming/Topic_Graphic/Topic_Business 4개 카테고리로 재분류.

- 중복 제거: frontmatter의 status:duplicate/merged + duplicate_of/redirect_to 필드로
  자기 자신을 중복으로 선언한 리다이렉트 stub 1032개 제거, 완전 동일 내용 파일 472개 제거,
  동일 파일명·다른 내용 충돌 시 더 큰(완전한) 버전만 유지(162개 제거) — 총 1639개 중복 제거.
- 분류: 폴더 단위로 명확한 항목(AI_and_ML/Coding/Architecture 등 → Programming,
  Comfyui/Visual_Effects → Graphic, Topics_Biz/Topics_Meeting/사업 등 → Business,
  Poetic_Blog_Writing/창의성/Game_Design 등 → General)은 폴더 우선순위로,
  나머지 혼재 폴더(Topic_Agent/Topic_Blog/Topics 루트/Thinking & Reasoning/Other/UI_UX_Assets)는
  title/tags 키워드 스코어링으로 파일 단위 분류(불명확한 경우 General로 폴백).
  원본 폴더명은 "From_*" 서브폴더로 보존해 추적 가능성 유지.
- 최종 배치: Programming 2784 / General 1608 / Graphic 285 / Business 249 = 4926개 문서.
- 에이전트 운영 상태(.astra/.agent/.obsidian/sessions/memory/_company/docs/lessons/_shared/src)는
  지식 콘텐츠가 아니므로 재분류 대상에서 제외하고 원위치 유지.
- Topics/Topic_email(상위 보호 폴더 Topic_email과 파일명 100% 중복) 삭제 — 보호 폴더 자체는 미변경.
- 완전히 비게 된 Topic_Agent/Topic_Blog/Topics_Biz/Topics_Rag 폴더 제거.
2026-07-05 00:33:48 +09:00

6.2 KiB

id, title, category, status, canonical_id, aliases, duplicate_of, source_trust_level, confidence_score, verification_status, tags, raw_sources, last_reinforced, github_commit, tech_stack
id title category status canonical_id aliases duplicate_of source_trust_level confidence_score verification_status tags raw_sources last_reinforced github_commit tech_stack
wiki-2026-0508-sentiment-analysis Sentiment Analysis 10_Wiki/Topics verified self
Opinion Mining
Emotion Detection
Polarity Classification
none A 0.9 applied
nlp
sentiment
classification
llm
2026-05-10 pending
language framework
python 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)

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)

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

# 매 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)

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)

# 매 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)

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)

# 매 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

🤖 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