線性模型的可解釋性

Python 的 Explainable AI

Fouad Trad

Machine Learning Engineer

線性模型

線性迴歸
  • 預測連續值

顯示一條擬合多個點的直線,x 軸是測驗分數,y 軸是錄取機率。

Python 的 Explainable AI

線性模型

線性迴歸
  • 預測連續值

顯示一條擬合多個點的直線,x 軸是測驗分數,y 軸是錄取機率。

邏輯斯迴歸
  • 用於二元分類

顯示一條線分隔多個代表交易的資料點,依交易金額與執行時間區分。

Python 的 Explainable AI

為何線性模型可解釋?

  • 學習輸入特徵的線性組合
  • $c_0 + c_1 \times \text{feature}_1 + c_2 \times \text{feature}_2 + \ldots + c_n \times \text{feature}_n$

與前面相同的線性與邏輯斯迴歸圖,但標示各自學到的方程式:線性迴歸學到 Mobile price=푐_0+푐_1∗Storage;邏輯斯迴歸學到 푐_0+푐_1∗Time of day+푐_2∗Transaction amount=0。

Python 的 Explainable AI

係數(Coefficients)

  • 告訴你各特徵的重要性
    • 絕對值較大 → 重要性較高
    • 絕對值較小 → 重要性較低
  • 比較係數 → 看絕對值
  • 注意:先正規化特徵尺度再計算係數

顯示方程 Mobile price=푐_0+5∗Storage+2∗Number of lenses,並標示係數。

Python 的 Explainable AI

係數(Coefficients)

  • 告訴你各特徵的重要性
    • 絕對值較大 → 重要性較高
    • 絕對值較小 → 重要性較低
  • 比較係數 → 看絕對值
  • 注意:先正規化特徵尺度再計算係數

顯示方程 Mobile price=𝑐_0+𝑐_1∗Storage+c_2∗Number of lenses,並標示 Storage 通常為數百到上千 Gigabytes,鏡頭數通常小於 4。

Python 的 Explainable AI

入學申請

GRE Score TOEFL Score University Rating SOP LOR CGPA Chance of Admit Accept
337 118 4 4.5 4.5 9.65 0.92 1
324 107 4 4 4.5 8.87 0.76 1
316 104 3 3 3.5 8 0.72 1
322 110 3 3.5 2.5 8.67 0.8 1
314 103 2 2 3 8.21 0.45 0
X_train = data.drop(['Chance of Admit', 'Accept'], axis=1)

y_reg = data['Chance of Admit']
y_cls = data['Accept']
Python 的 Explainable AI

模型訓練

from sklearn.preprocessing import MinMaxScaler
from sklearn.linear_model import LinearRegression, LogisticRegression


scaler = MinMaxScaler() X_train_scaled = scaler.fit_transform(X_train)
lin_reg = LinearRegression() lin_reg.fit(X_train_scaled, y_reg)
log_reg = LogisticRegression() log_reg.fit(X_train_scaled, y_cls)
Python 的 Explainable AI

計算係數

線性迴歸
print(lin_reg.coef_)
[0.03052087 0.01665433 0.00668971 
 0.00326926 0.01724815 0.0661691 ]
邏輯斯迴歸
print(log_reg.coef_)
[[1.28985577  0.49441086  0.47593379 
  0.05434322  0.41800927  1.31980189]]
Python 的 Explainable AI

視覺化係數

線性迴歸
import matplotlib.pyplot as plt
plt.bar(X_train.columns, lin_reg.coef_)

長條圖顯示重要性,CGPA 與 GRE 分數是最重要的特徵。

邏輯斯迴歸
import matplotlib.pyplot as plt
plt.bar(X_train.columns, log_reg.coef_[0])

長條圖顯示重要性,CGPA 與 GRE 分數是最重要的特徵。

Python 的 Explainable AI

一起來練習吧!

Python 的 Explainable AI

Preparing Video For Download...