MinAI - Về trang chủ
Lý thuyết
8/1335 phút
Đang tải...

Sentiment Analysis

Phân tích cảm xúc văn bản với LLMs - từ basic đến production

0

🎯 Mục tiêu bài học

TB5 min

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

1

🔍 Sentiment Analysis Approaches

TB5 min
Diagram
Đang vẽ diagram...
LLM Advantages
  • 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?

2

💻 Basic Sentiment Classification

TB5 min
python.py
1from langchain_openai import ChatOpenAI
2from langchain_core.prompts import ChatPromptTemplate
3from pydantic import BaseModel, Field
4from typing import Literal
5
6llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
7
8class 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")
12
13sentiment_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)
21
22result = 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?

3

📐 Aspect-based Sentiment

TB5 min
python.py
1from typing import List
2
3class 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")
7
8class DetailedAnalysis(BaseModel):
9 overall: Literal["positive", "negative", "neutral", "mixed"]
10 aspects: List[AspectSentiment]
11 key_emotions: List[str]
12
13aspect_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)
22
23review = """
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"""
29
30analysis = 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?

4

⚡ Batch Analysis Pipeline

TB5 min
python.py
1import pandas as pd
2
3reviews = [
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]
10
11# Batch process
12results = sentiment_chain.batch(
13 [{"text": r} for r in reviews],
14 config={"max_concurrency": 5}
15)
16
17# To DataFrame
18df = pd.DataFrame([
19 {
20 "review": reviews[i],
21 "sentiment": r.sentiment,
22 "confidence": r.confidence
23 }
24 for i, r in enumerate(results)
25])
26
27print(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?

5

📐 Few-shot for Custom Categories

TB5 min
python.py
1from langchain_core.prompts import FewShotChatMessagePromptTemplate
2
3examples = [
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]
9
10example_prompt = ChatPromptTemplate.from_messages([
11 ("human", "{text}"),
12 ("ai", "{label}")
13])
14
15few_shot = FewShotChatMessagePromptTemplate(
16 example_prompt=example_prompt,
17 examples=examples
18)
19
20custom_chain = (
21 ChatPromptTemplate.from_messages([
22 ("system", "Classify customer feedback: satisfied/churning/constructive/advocate"),
23 few_shot,
24 ("human", "{text}")
25 ])
26 | llm
27)

Checkpoint

Bạn đã hiểu cách sử dụng few-shot prompting cho custom sentiment categories chưa?

6

📐 Emotion Detection

TB5 min
python.py
1class EmotionAnalysis(BaseModel):
2 primary_emotion: str
3 secondary_emotions: List[str]
4 intensity: Literal["low", "medium", "high"]
5 triggers: List[str]
6
7emotion_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?

7

🛠️ Monitoring Dashboard

TB5 min
python.py
1from collections import Counter
2from datetime import datetime
3
4class SentimentMonitor:
5 def __init__(self, chain):
6 self.chain = chain
7 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": source
17 })
18 return result
19
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 }
27
28monitor = SentimentMonitor(sentiment_chain)

Checkpoint

Bạn đã hiểu cách xây dựng sentiment monitoring system chưa?

8

🎯 Tổng kết

TB5 min
Hands-on Exercise
  1. Build aspect-based review analyzer
  2. Batch process 50+ reviews và tạo distribution chart
  3. Implement custom categories với few-shot
  4. 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

  1. 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ì?
  2. Aspect-based sentiment analysis khác gì so với phân tích sentiment tổng thể?
  3. Emotion detection mở rộng sentiment analysis như thế nào với các cảm xúc cụ thể?
  4. 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!


🚀 Bài tiếp theo

Translation và Multilingual →