通過生成項目的獨立 HTML 報告,為模型的可審計性做出貢獻
https://github.com/MAIF/shapash?tab=readme-ov-file
import xgboost as xgb
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.model_selection import GridSearchCV, StratifiedKFold, train_test_split
# 加載鳶尾花數據集
iris = load_iris()
X = iris.data
y = iris.target
# 將X和y保存為一個DataFrame
data = pd.DataFrame(data=X, columns=iris.feature_names)
data['target'] = y
# 劃分數據集為訓練集和測試集
X_train, X_test, y_train, y_test = train_test_split(data.drop(['target'], axis=1),
data['target'],
test_size=0.2, random_state=42, stratify=data['target'])
model = xgb.XGBClassifier()
# 定義XGBoost的參數網格
param_grid = {
'learning_rate': [0.01, 0.1, 0.2], # 學習率,控制每個弱學習器的權重縮減,用于防止過擬合
'max_depth': [3, 4, 5], # 每棵樹的最大深度,控制樹的復雜性
'n_estimators': [50, 100, 200], # 弱學習器的數量,即樹的數量
'subsample': [0.8, 0.9, 1.0], # 每棵樹用于訓練的子樣本的比例
'colsample_bytree': [0.8, 0.9, 1.0], # 每棵樹用于訓練的特征的比例
'reg_alpha': [0, 0.1, 0.5], # L1正則化的參數,控制模型復雜性
'reg_lambda': [0, 0.1, 0.5], # L2正則化的參數,控制模型復雜性
}
strkfold = StratifiedKFold(n_splits=3, shuffle=True, random_state=42)
gscv = GridSearchCV(model, param_grid, cv=strkfold, n_jobs=-1, scoring=['accuracy', 'roc_auc_ovr_weighted'], refit='accuracy')
# 在訓練數據上進行網格搜索和交叉驗證,找到最佳模型
gscv.fit(X_train, y_train)
# 在測試數據上評估最佳模型的性能
score_best_estimator = gscv.score(X_test, y_test)
# 打印最佳模型的交叉驗證最高得分、最佳超參數組合和測試數據上的準確性
print('最高得分為:{:.3f}'.format(gscv.best_score_))
print('最佳超參數組合為:{}'.format(gscv.best_params_))
print('最佳模型在測試數據上的準確性為:{:.3f}'.format(score_best_estimator))
# 將 GridSearchCV 的結果轉為 DataFrame 方便查看
df = pd.DataFrame(gscv.cv_results_)
df
利用GridSearchCV和XGBoost來調整模型參數,以獲得在測試數據上表現最佳的分類器,詳細調整模型參數方法參考文章尾所給出的往期文章鏈接
model = xgb.XGBClassifier(
colsample_bytree=0.8,
learning_rate=0.01,
max_depth=3,
n_estimators=100,
reg_alpha=0,
reg_lambda=0,
subsample=0.8
)
# 使用訓練數據擬合模型
model.fit(X_train, y_train)
# 使用擬合好的模型對測試數據進行預測
y_pred = model.predict(X_test)
from sklearn.metrics import classification_report
print(classification_report(y_test, y_pred)) # 輸出模型完整評價指標
from shapash import SmartExplainer
import warnings
# 忽略警告
warnings.filterwarnings("ignore")
# 將 y_pred 轉換為 Pandas Series 并設置索引
y_pred_series = pd.Series(y_pred, name="y_pred", index=X_test.index) # 參數接受 Pandas 數據框 (DataFrame)
# 創建 SmartExplainer 對象
xpl = SmartExplainer(model)
# 編譯數據集,指定 x(特征)、y_pred(預測值)、y_target(真實值)等參數
xpl.compile(
x=X_test,
y_pred=y_pred_series, # 可選參數:自定義預測值(默認使用 model.predict)
y_target=y_test, # 可選參數:允許顯示真實值與預測值的對比
)
# 啟動 Web 應用
app = xpl.run_app()
箭頭所指處會顯示所生成的模型解釋鏈接點擊后如下圖
如圖紅色箭頭可以選擇需要解釋的數據類別,藍色箭頭為在該類別下的特征貢獻度,粉色箭頭為數據集,這里的數據集也就是模型的測試集,其中包含模型的預測結果,其中True Values Vs Predicted Values會顯示該類別下的預測散點圖,如下圖
這里顯示的就是類別1類的預測結果散點圖,從圖中可以發現有一個數據點預測錯誤,實際類別為1預測錯誤為2
藍色箭頭為各個數據在petal width (cm)、類別1下的預測結果、索引以及petal width (cm)對于模型預測輸出的影響程度,紅色箭頭下可視化為指定索引數據在類別1下每個特征的貢獻以及預測為該類別的概率,最后的粉色箭頭可以指定需要探討數據ID以便在紅色箭頭下輸出
如圖通過調整輸出了索引為77數據點的模型解釋,預測結果為2,實際類別為1,通過Shapash的模型解釋工具,能夠更深入地理解模型在特定數據點上的行為,識別潛在的預測錯誤原因,從而改進模型的性能或者對模型的預測結果提出進一步的疑問,這對于調整和優化機器學習模型具有很大的幫助,更多Shapash庫使用技巧參考前文給出的GitHub鏈接
本文章轉載微信公眾號@Python機器學習AI