在處理大量文本資料時,往往我們並不知道這些文章的主題是什麼。
這時就可以用主題建模(Topic Modeling),透過統計或機器學習的方法,幫助我們自動找出文本中隱藏的主題。
常見的方法有:
LSA(Latent Semantic Analysis):利用矩陣分解找到潛在語義。
LDA(Latent Dirichlet Allocation):最常見的主題建模方法,將文章視為主題的混合,主題又是詞語的分佈。
一、主題建模的概念
一篇文章可能不是單一主題,而是多個主題的組合。
例如:
昨天看了足球比賽,之後還和朋友討論了新出的電影。
這篇文章可能同時屬於體育(sports)和娛樂(movies)兩個主題。
LDA 的直覺理解:
每篇文章=多個主題的機率分布
每個主題=多個詞的機率分布
二、實作:用Python建立LDA主題模型
我們使用scikit-learn的LDA來做簡單範例。
from sklearn.decomposition import LatentDirichletAllocation
from sklearn.feature_extraction.text import CountVectorizer
#範例文本
documents = [
"I love watching football and playing soccer.",
"The movie last night was fantastic and thrilling.",
"Basketball is my favorite sport to play.",
"The film was boring but the actors were great.",
"I enjoy sports like football and basketball.",
"Movies with good stories are always enjoyable."
]
#文字轉換為詞袋模型
vectorizer = CountVectorizer(stop_words="english")
X = vectorizer.fit_transform(documents)
#建立LDA模型(假設有 2 個主題)
lda = LatentDirichletAllocation(n_components=2, random_state=42)
lda.fit(X)
#顯示主題
words = vectorizer.get_feature_names_out()
for idx, topic in enumerate(lda.components_):
print(f"主題 {idx+1}:")
print(" ".join([words[i] for i in topic.argsort()[-5:]]))
三、範例輸出結果
主題 1:
football soccer basketball sport play
主題 2:
movie film fantastic boring actors
這樣,我們就能發現:
主題1與運動相關 (football, soccer, basketball, sport, play)
主題2與電影相關 (movie, film, fantastic, boring, actors)
四、延伸應用
新聞自動分群:從海量新聞中自動找到政治、經濟、娛樂、體育等主題。
顧客意見分析:在評論中自動找出價格、品質、服務等核心議題。
數位人文研究:學者可以用主題建模分析歷史文獻、小說或演講。
今天我們學會了主題建模(LDA)的基本概念與實作。
明天我們將學習文本摘要(Text Summarization),看看如何自動幫文章生成摘要!