Sitemap

程式語言 — LDA模型分析

12 min readNov 28, 2023

什麼是LDA?

這是一種主題模型,它可以將文檔集中每篇文檔的主題按照概率分布的形式給出。同時它是一種無監督學習算法,在訓練時不需要手工標註的訓練集,需要的僅僅是文檔集以及指定主題的數量k即可。此外LDA的另一個優點則是,對於每一個主題均可找出一些詞語來描述它。

STEP1.安裝指定程式庫

!pip install pyLDAvis
!pip install --upgrade numpy
!pip install --upgrade gensim
  1. !pip install pyLDAvis: pyLDAvis 是一個用於呈現和視覺化 LDA(Latent Dirichlet Allocation)主題模型的工具,這個套件通常用於解釋主題模型的結果,並提供互動式的視覺化。
  2. !pip install numpy: numpy 是一個用於科學計算的強大套件,提供了對多維陣列和矩陣的支援,並包含許多數學函數。
  3. !pip install --upgrade gensim: gensim 是一個用於文本建模和主題建模的套件,通常用於處理大型文本語料庫執行主題模型的訓練

ps.在這裡使用 ! 來執行 shell 命令。

import re
import requests
import jieba
import gensim
from gensim import corpora, models
from gensim.models.coherencemodel import CoherenceModel
from gensim.models.ldamodel import LdaModel
import matplotlib.pyplot as plt
import pyLDAvis.gensim_models
from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS
from bs4 import BeautifulSoup
  1. re: 正則表達式模塊,用於處理字符串的模式匹配。
  2. requests: 用於發送 HTTP 請求和處理響應的套件,通常用於網路資料的擷取
  3. jieba: 中文分詞套件,用於將中文文本分割詞語
  4. gensim: 一個用於文本建模和主題建模的套件,包括 Latent Dirichlet Allocation(LDA)等模型。
  5. corpora: gensim 中的一個模塊,用於處理文檔集合。
  6. models: 包含了各種文本建模和主題建模的模型,如 LDA。
  7. CoherenceModel: 用於計算主題模型的一致性的類。
  8. LdaModel: gensim 中實現的 LDA 模型。
  9. matplotlib.pyplot: 用於畫圖和視覺化的套件。
  10. pyLDAvis.gensim_models: 用於呈現和視覺化 LDA 模型的工具。
  11. ENGLISH_STOP_WORDS: scikit-learn 中提供的一組英文停用詞。
  12. BeautifulSoup: 用於解析 HTML 和 XML 文件的套件,通常用於網路資料擷取。

STEP2.從指定的網站抓取文本內容

# 定義抓取文本的函數
def scrape_website(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
paragraphs = soup.find_all('p')
text_data = [p.get_text() for p in paragraphs]
return text_data

# 定義預處理文本的函數
def preprocess_text(text_data):
processed_texts = []
stop_words = set(ENGLISH_STOP_WORDS)

for text in text_data:
seg_list = jieba.cut(text, cut_all=False)
filtered_words = [word for word in seg_list if word not in stop_words]
processed_texts.append(filtered_words)

return processed_texts

# 使用上述的 scrape_website 函數獲取文本數據
website_url = "https://www.sportsv.net/"
text_data = scrape_website(website_url)

# 預處理文本數據
seg_lst = preprocess_text(text_data)

# 打印處理後的結果
for i, seg in enumerate(seg_lst):
print(f"Segmented Text {i+1}: {seg}")

這段程式碼的目的是從指定網站爬取文本數據,並進行中文分詞和停用詞過濾等預處理操作,最終打印出處理後的結果。

  1. scrape_website: 這個函數接受一個URL作為參數,使用 requests 模組發送GET請求並使用BeautifulSoup進行HTML解析。它找到HTML內所有的 <p> 標籤(段落)並提取其中的文本內容,最後將這些文本內容以列表的形式返回。
  2. preprocess_text: 這個函數接受文本數據作為輸入,首先使用 jieba 進行中文分詞。然後,它遍歷每個分詞後的文本,過濾掉屬於英文停用詞集合 (ENGLISH_STOP_WORDS) 中的詞語。最終,處理後的文本被添加到 processed_texts 列表中。
  3. scrape_website:函數獲取文本數據,將指定的網站(https://www.sportsv.net/)的文本數據爬取下來。
  4. preprocess_text(text_data):使用定義的 preprocess_text 函數對獲取的文本進行預處理,即中文分詞並過濾掉停用詞。
  5. 打印處理後的結果: 遍歷處理後的文本列表,打印每個段落的分詞結果。

STEP3.刪去不要的文字、數字、各種多餘的東西

# 停用詞列表的定義
stop_words = ['了', '的', '嗎','繼續','往下','這','什麼','一次','一位','次','個','可以','與','如何','從','為','後']

def preprocess_text(text_data):
# 合併分詞列表成字符串
text_data = ' '.join(text_data)
# 去除HTML標籤
text_data = re.sub(r'<.*?>', '', text_data)
# 使用結巴分詞進行分詞
seg_list = jieba.cut(text_data)
# 去除停用詞
seg_list = [word for word in seg_list if word not in stop_words]
# 去除空格和換行符號
seg_list = [word.strip() for word in seg_list]
# 去除標點符號和數字
seg_list = [word for word in seg_list if word.isalpha()]
# 去除單一字元
seg_list = [word for word in seg_list if len(word) > 1]

return seg_list

# 使用上述的 preprocess_text 函數處理文本
seg_lst = preprocess_text(text_data)

# 顯示處理後的分詞結果
print(seg_lst)
  1. text_data=' '.join(text_data) :將原始文本中的分詞列表轉換為一個以空格分隔的字符串,以有助於後續處理。

2. text_data=re.sub(r'<.*?>','',text_data) :使用正則表達式去除文本中的HTML標籤。HTML標籤通常包含在`<`和`>`之間,這個表達式的目的是找到這樣的標籤並將其替換為空字符串。

3. seg_list=jieba.cut(text_data) :使用結巴分詞工具對文本進行中文分詞,將文本拆分為一系列的詞語。

4. seg_list=[word for word in seg_list if word not in stop_words):通過遍歷分詞後的結果,將停用詞(例如 “了”、”的”、”嗎” 等)從分詞列表中去除,以過濾掉一些常見但無意義的詞語。

5. seg_list=[word.strip()for word in seg_list]:通過遍歷分詞後的結果,去除每個詞語的開頭和結尾的空格,以及換行符號。

6. seg_list=[word for word in seg_list if word.isalpha():通過遍歷分詞後的結果,保留只包含漢字字元的詞語,去除標點符號和數字。

7. seg_list=[word for word in seg_list if len(word)>1]: 通過遍歷分詞後的結果,去除只有一個字元的詞語,因為這樣的詞通常沒有實際意義。

# 從給定 URL 中抓取文字內容的函數
def scrape_website(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
paragraphs = soup.find_all('p')
text_data = [p.get_text() for p in paragraphs]
return text_data

# 要抓取的網站的 URL
website_url = "https://www.sportsv.net/"
text_data = scrape_website(website_url)

# 預處理文字資料(將其替換為實際的文字預處理)
# 我使用上一段的我撰寫的preprocess_text(text_data)
seg_lst = preprocess_text(text_data)

# 繼續使用現有的主題建模程式碼
texts = [doc.split() for doc in seg_lst] # 將每個文檔轉換為分詞列表
dictionary = corpora.Dictionary(texts)
corpus = [dictionary.doc2bow(doc) for doc in texts]



def coherence(num_topics):
ldamodel = LdaModel(corpus, num_topics=num_topics, id2word=dictionary, passes=30, random_state=42)
print(ldamodel.print_topics(num_topics=num_topics, num_words=15))
ldacm = CoherenceModel(model=ldamodel, texts=seg_lst, dictionary=dictionary, coherence="c_v")
print(ldacm.get_coherence())
return ldacm.get_coherence()

def coherence_count(num_topics):
x = range(1, num_topics + 1)
y = [coherence(i) for i in x]
return x, y

x, y = coherence_count(20)

num_topics = 18
lda = LdaModel(corpus, num_topics=num_topics, id2word=dictionary, passes=30, random_state=42)
topics_lst = lda.print_topics()
print(topics_lst)

import pyLDAvis.gensim_models
pyLDAvis.enable_notebook()
data = pyLDAvis.gensim_models.prepare(lda, corpus, dictionary)
pyLDAvis.save_html(data, 'lda_visualization.html') # 可以保存為 HTML 文件,方便在瀏覽器中查看
pyLDAvis.display(data)
  1. 抓取文字內容的函數 (scrape_website): 該函數使用 requests 模組獲取指定URL的內容,然後使用BeautifulSoup進行HTML解析,提取所有段落 <p> 的文字內容。
  2. 抓取指定網站的文字內容: 將函數應用於指定網站(https://www.sportsv.net/),獲取該網站的文字內容。
  3. 預處理文字資料: 使用之前定義的 preprocess_text 函數對抓取到的文字內容進行預處理。預處理包括中文分詞和停用詞過濾。
  4. 主題建模: 使用 gensim 中的 LDA(Latent Dirichlet Allocation)模型進行主題建模。這裡的 corpus 是經過處理的文本數據,dictionary 是構建的詞典。
  5. 計算主題一致性: 使用主題一致性作為評估指標,通過不同主題數目計算主題一致性的值。我的這個例子,是主題數目從1到20。
  6. 可視化主題一致性: 使用 matplotlib 库繪製主題數目與主題一致性之間的曲線。
  7. 建立 LDA 模型: 使用選定的主題數目構建 LDA 模型。
  8. 打印主題: 列印 LDA 模型中每個主題的前15個詞。
  9. 使用 pyLDAvis 可視化: 使用 pyLDAvis 库將 LDA 模型的結果可視化,並保存為 HTML 文件。
  10. 顯示可視化的結果。
Press enter or click to view image in full size

--

--

No responses yet