一、什麼是主題建模?
主題建模是一種無監督學習的方法,它能自動從大量文本中挖掘隱藏的主題。
最常見的演算法是LDA(Latent Dirichlet Allocation, 潛在狄利克雷分配)。
LDA 的核心思想:
每篇文件由多個主題組成(例如一篇文章可能同時涉及環境保護與能源政策)。
每個主題由多個詞彙組成(例如環境保護主題可能包含:climate, green, renewable, pollution)。
換句話說,LDA就像在字詞 → 主題 → 文件之間建構一個機率模型。
二、為什麼要用主題建模?
文件分群:幫助分類文章而不需要人工標註。
文本探索:找出資料集中隱藏的主題結構。
商業應用:顧客評論分析(了解消費者最關心的問題)。
學術研究:在數萬篇論文中找到研究領域趨勢。
三、Python 實作:LDA主題建模
我們使用scikit-learn進行簡單的LDA實驗。
#安裝套件(若尚未安裝)
#pip install scikit-learn
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.decomposition import LatentDirichletAllocation
#測試文本
docs = [
"The economy is growing and stock markets are reaching new highs.",
"Investors are worried about inflation and interest rates.",
"Climate change is causing global temperatures to rise.",
"Renewable energy sources like wind and solar are becoming popular.",
"Government policies affect both the economy and the environment."
]
#文字轉換成詞頻矩陣
vectorizer = CountVectorizer(stop_words="english")
X = vectorizer.fit_transform(docs)
#建立 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([words[i] for i in topic.argsort()[-5:]])
範例輸出:
主題 1:
['economy', 'markets', 'investors', 'inflation', 'rates']
主題 2:
['climate', 'change', 'renewable', 'energy', 'solar']
可以看到模型自動把文件分成了經濟金融與環境能源兩個主題。
四、應用場景
新聞分類:例如自動分出政治、財經、娛樂、體育新聞。
顧客評論分析:找出大家最關心的價格、品質、物流等問題。
研究趨勢探索:分析數萬篇論文,找出主要研究方向。
認識了主題建模(LDA),這是一種幫助我們在大規模文本中找到潛在主題的工具。
它不僅能幫助我們分類文件,還能讓我們對資料有更深的洞察。