AI時代系列(1) 機器學習三部曲: 🔹 第一部:《機器學習 —— AI 智慧的啟航》
14. 類別變數處理(One-Hot Encoding、Label Encoding) 🔢 把「紅、藍、綠」轉成 0/1,讓機器也能讀懂!
在機器學習和數據分析中,類別變數(Categorical Variables) 通常需要轉換成數值型數據,才能讓演算法理解並進行計算。最常見的類別變數編碼方式有:
1️⃣ One-Hot Encoding (獨熱編碼)
這種方法會為每個類別建立一個獨立的欄位,值為 0 或 1。
🎯 例子:
假設有一個顏色特徵 Color,包含「紅(Red)」、「藍(Blue)」、「綠(Green)」三種顏色,使用 One-Hot Encoding 會變成:
Color Red Blue Green
Red 1 0 0
Blue 0 0 1
Green 0 0 1
📌 優點:
• 不會產生數值大小的偏差,適合樹模型(如決策樹、隨機森林)。
• 保持變數的獨立性,不會讓演算法誤以為某個類別比其他類別「大」或「小」。
📌 缺點:
• 當類別數量過多時,可能會產生「維度爆炸」(大量的 0/1 欄位)。
• 需要額外的記憶體來儲存新的欄位。
✅ 使用方式:
在 Python 中,可以使用 pandas 或 sklearn.preprocessing 來進行 One-Hot Encoding:
import pandas as pd
# 原始資料
df = pd.DataFrame({'Color': ['Red', 'Blue', 'Green', 'Red', 'Green']})
# 進行 One-Hot Encoding
df_encoded = pd.get_dummies(df, columns=['Color'])
print(df_encoded)
________________________________________
2️⃣ Label Encoding (標籤編碼)
這種方法會將類別轉換為 數字標籤,例如:
• Red → 0
• Blue → 1
• Green → 2
🎯 例子:
Color Encoded
Red 0
Blue 1
Green 2
📌 優點:
• 節省空間,不會產生維度爆炸的問題。
• 適合用於類別變數有「順序性」的情況,例如「小、中、大」。
📌 缺點:
• 可能會引入錯誤的數值關係,例如機器學習模型可能誤認為 Green(2)比 Red(0)大,但實際上顏色之間沒有數值上的大小關係。
✅ 使用方式:
可以使用 sklearn.preprocessing.LabelEncoder 來進行 Label Encoding:
python
from sklearn.preprocessing import LabelEncoder
# 原始資料
df = pd.DataFrame({'Color': ['Red', 'Blue', 'Green', 'Red', 'Green']})
# 進行 Label Encoding
encoder = LabelEncoder()
df['Color_Encoded'] = encoder.fit_transform(df['Color'])
print(df)
________________________________________
3️⃣ 該選擇哪一種?
方法 何時使用
One-Hot Encoding 當類別變數無序,例如顏色、城市、性別
Label Encoding 當類別變數有序,例如「低、中、高」等級
📌 進階技巧:
• 當類別數量過多時(例如 1000 個城市),可以考慮 Target Encoding 或 Hash Encoding 來減少維度問題。
• 對於某些神經網絡模型(如 CNN、RNN),可以使用 Embedding 層 來學習類別的關係。
這樣,機器學習模型就能夠正確處理類別數據,提高預測效果!🚀


