🎯 Mục tiêu bài học
Sentiment analysis giúp hiểu cảm xúc của khách hàng, phân tích reviews, và monitor brand reputation. LLMs đem lại độ chính xác vượt trội so với phương pháp truyền thống.
Sau bài này, bạn sẽ:
✅ Implement sentiment classification với LLMs (zero-shot và few-shot) ✅ Phân tích aspect-based sentiment cho reviews chi tiết ✅ Detect emotions và build batch analysis pipeline ✅ Xây dựng sentiment monitoring system
🔍 Sentiment Analysis Approaches
- Zero-shot: Không cần training data
- Nuanced: Hiểu context, sarcasm, implicit sentiment
- Multilingual: Hỗ trợ nhiều ngôn ngữ
- Customizable: Dễ dàng thay đổi categories
Checkpoint
Bạn đã hiểu các approaches cho sentiment analysis và ưu điểm của LLMs chưa?
💻 Basic Sentiment Classification
1from langchain_openai import ChatOpenAI2from langchain_core.prompts import ChatPromptTemplate3from pydantic import BaseModel, Field4from typing import Literal56llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)78class SentimentResult(BaseModel):9 sentiment: Literal["positive", "negative", "neutral"]10 confidence: float = Field(ge=0, le=1, description="0-1 confidence score")11 reasoning: str = Field(description="Short explanation")1213sentiment_chain = (14 ChatPromptTemplate.from_messages([15 ("system", """Phan tich sentiment cua text.16 Tra ve: sentiment (positive/negative/neutral), confidence (0-1), reasoning."""),17 ("human", "{text}")18 ])19 | llm.with_structured_output(SentimentResult)20)2122result = sentiment_chain.invoke({23 "text": "San pham tot nhung gia hoi cao. Dich vu cham soc khach hang tuyet voi!"24})25print(f"Sentiment: {result.sentiment} ({result.confidence:.0%})")26print(f"Reason: {result.reasoning}")Checkpoint
Bạn đã thử implement basic sentiment classification chưa?
📐 Aspect-based Sentiment
1from typing import List23class AspectSentiment(BaseModel):4 aspect: str = Field(description="Khia canh duoc danh gia")5 sentiment: Literal["positive", "negative", "neutral", "mixed"]6 mentions: List[str] = Field(description="Cau lien quan")78class DetailedAnalysis(BaseModel):9 overall: Literal["positive", "negative", "neutral", "mixed"]10 aspects: List[AspectSentiment]11 key_emotions: List[str]1213aspect_chain = (14 ChatPromptTemplate.from_messages([15 ("system", """Phan tich sentiment theo tung khia canh (aspect).16 Identify: product quality, price, service, delivery, etc.17 Cho moi aspect: sentiment + cau mention cu the."""),18 ("human", "{review}")19 ])20 | llm.with_structured_output(DetailedAnalysis)21)2223review = """24Da dat hang tren Shopee. Giao hang nhanh, dong goi can than. 25San pham dung nhu mo ta, chat luong tot. Tuy nhien gia dat hon 26cac shop khac khoang 50k. Ho tro khach hang tra loi nhanh. 27Se mua lai lan sau.28"""2930analysis = aspect_chain.invoke({"review": review})31for aspect in analysis.aspects:32 print(f" {aspect.aspect}: {aspect.sentiment}")Checkpoint
Bạn đã hiểu cách phân tích sentiment theo từng aspect chưa?
⚡ Batch Analysis Pipeline
1import pandas as pd23reviews = [4 "San pham tuyet voi, se mua lai!",5 "Chat luong kem, khong dung mo ta",6 "Binh thuong, khong co gi dac biet",7 "Giao hang cham nhung san pham tot",8 "Gia qua dat so voi chat luong",9]1011# Batch process12results = sentiment_chain.batch(13 [{"text": r} for r in reviews],14 config={"max_concurrency": 5}15)1617# To DataFrame18df = pd.DataFrame([19 {20 "review": reviews[i],21 "sentiment": r.sentiment,22 "confidence": r.confidence23 }24 for i, r in enumerate(results)25])2627print(df.to_string())28print(f"\nDistribution:\n{df['sentiment'].value_counts()}")Checkpoint
Bạn đã hiểu cách batch process nhiều reviews cùng lúc chưa?
📐 Few-shot for Custom Categories
1from langchain_core.prompts import FewShotChatMessagePromptTemplate23examples = [4 {"text": "Rat hai long voi dich vu", "label": "satisfied"},5 {"text": "Se khong bao gio mua lai", "label": "churning"},6 {"text": "Can cai thien them", "label": "constructive"},7 {"text": "Toi se gioi thieu cho ban be", "label": "advocate"},8]910example_prompt = ChatPromptTemplate.from_messages([11 ("human", "{text}"),12 ("ai", "{label}")13])1415few_shot = FewShotChatMessagePromptTemplate(16 example_prompt=example_prompt,17 examples=examples18)1920custom_chain = (21 ChatPromptTemplate.from_messages([22 ("system", "Classify customer feedback: satisfied/churning/constructive/advocate"),23 few_shot,24 ("human", "{text}")25 ])26 | llm27)Checkpoint
Bạn đã hiểu cách sử dụng few-shot prompting cho custom sentiment categories chưa?
📐 Emotion Detection
1class EmotionAnalysis(BaseModel):2 primary_emotion: str3 secondary_emotions: List[str]4 intensity: Literal["low", "medium", "high"]5 triggers: List[str]67emotion_chain = (8 ChatPromptTemplate.from_messages([9 ("system", """Detect emotions in text.10 Emotions: joy, anger, sadness, fear, surprise, disgust, trust, anticipation.11 Identify primary emotion, secondary, intensity, and triggers."""),12 ("human", "{text}")13 ])14 | llm.with_structured_output(EmotionAnalysis)15)Checkpoint
Bạn đã hiểu cách detect emotions chi tiết từ text chưa?
🛠️ Monitoring Dashboard
1from collections import Counter2from datetime import datetime34class SentimentMonitor:5 def __init__(self, chain):6 self.chain = chain7 self.history = []8 9 def analyze(self, text, source="unknown"):10 result = self.chain.invoke({"text": text})11 self.history.append({12 "timestamp": datetime.now().isoformat(),13 "text": text,14 "sentiment": result.sentiment,15 "confidence": result.confidence,16 "source": source17 })18 return result19 20 def get_stats(self):21 sentiments = [h["sentiment"] for h in self.history]22 return {23 "total": len(self.history),24 "distribution": dict(Counter(sentiments)),25 "avg_confidence": sum(h["confidence"] for h in self.history) / len(self.history)26 }2728monitor = SentimentMonitor(sentiment_chain)Checkpoint
Bạn đã hiểu cách xây dựng sentiment monitoring system chưa?
🎯 Tổng kết
- Build aspect-based review analyzer
- Batch process 50+ reviews và tạo distribution chart
- Implement custom categories với few-shot
- Tạo sentiment monitoring system
Dataset: Sử dụng reviews từ e-commerce hoặc app store
Câu hỏi tự kiểm tra
- So sánh sentiment analysis bằng LLMs với phương pháp truyền thống — ưu điểm chính là gì?
- Aspect-based sentiment analysis khác gì so với phân tích sentiment tổng thể?
- Emotion detection mở rộng sentiment analysis như thế nào với các cảm xúc cụ thể?
- Sentiment monitoring system có thể được ứng dụng trong những tình huống thực tế nào?
🎉 Tuyệt vời! Bạn đã hoàn thành bài học Sentiment Analysis với LLMs!
Tiếp theo: Hãy học cách dịch và xử lý đa ngôn ngữ với Translation và Multilingual!
