iT邦幫忙

2025 iThome 鐵人賽

DAY 21
0
Software Development

來一場軟體開發學習之旅系列 第 21

Day 21:文字分類(Text Classification)

  • 分享至 

  • xImage
  •  

一、什麼是文字分類?
文字分類(Text Classification)是將文本自動歸類到預先定義的類別。
例如:給定一段文字台灣隊在比賽中獲得冠軍,我們希望模型能判斷它屬於體育新聞
核心步驟:
資料收集與標註 → 需要一批帶標籤的資料(例如:垃圾郵件vs正常郵件)。
文字轉換成數字特徵 → 使用Bag-of-Words、TF-IDF或詞向量。
模型訓練 → 常見的分類模型有Naive Bayes、SVM、Logistic Regression、深度學習。
模型評估與應用 → 使用測試集檢查分類準確度。

二、常見方法
機器學習基礎方法
Naive Bayes:適合簡單分類,速度快。
SVM(支持向量機):在高維空間中效果好。
Logistic Regression:直觀且解釋性強。

深度學習方法
CNN / RNN:擅長捕捉文字序列的特徵。
Transformer(例如 BERT):目前NLP的主流,效果最佳。

三、Python實作:新聞分類
我們來做一個簡單範例,將新聞分成體育/政治/科技三類。

#安裝套件
#pip install scikit-learn

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import make_pipeline

#訓練資料
texts = [
"The team won the championship after a tough match.", # 體育
"The player scored a record number of goals this season.", # 體育
"The government announced a new policy on healthcare.", # 政治
"Elections will be held next year to choose the president.", # 政治
"A new smartphone model was released with advanced AI features.", # 科技
"Researchers developed a new algorithm for faster computation." # 科技
]
labels = ["sports", "sports", "politics", "politics", "tech", "tech"]

#建立管線(TF-IDF + Naive Bayes)
model = make_pipeline(TfidfVectorizer(), MultinomialNB())

#訓練
model.fit(texts, labels)

#測試
test_texts = [
"The match ended with a surprising victory.",
"The parliament debated about tax reforms.",
"Scientists discovered a new method in quantum computing."
]

predictions = model.predict(test_texts)
for text, pred in zip(test_texts, predictions):
print(f"文章:{text} → 分類:{pred}")

範例輸出:
文章:The match ended with a surprising victory. → 分類:sports
文章:The parliament debated about tax reforms. → 分類:politics
文章:Scientists discovered a new method in quantum computing. → 分類:tech

模型能根據文本內容自動判斷文章類別。

四、應用場景
垃圾郵件過濾:郵件系統自動攔截垃圾郵件。
新聞分類:新聞網站自動把文章歸類。
客服系統:自動標籤顧客問題,分派給正確部門。
內容推薦:社群平台根據分類結果推薦相關內容。

學會了文字分類,了解了它的基本流程與Python實作。
從這裡開始,我們不僅能判斷情緒(情感分析),還能更廣泛地應用到 多種類型的分類任務。


上一篇
Day 20:情感分析(Sentiment Analysis)
系列文
來一場軟體開發學習之旅21
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言