在下面的實(shí)際代碼實(shí)現(xiàn)中,第一層使用了多種基學(xué)習(xí)器,包括隨機(jī)森林、XGBoost、LightGBM、梯度提升、AdaBoost和CatBoost,這些模型分別獨(dú)立訓(xùn)練并生成預(yù)測(cè)結(jié)果,第二層的元學(xué)習(xí)器采用線性回歸,通過學(xué)習(xí)第一層各基學(xué)習(xí)器的預(yù)測(cè)結(jié)果,進(jìn)一步整合優(yōu)化,生成最終的預(yù)測(cè)結(jié)果

SHAP如何解釋Stacking模型?

需要注意的是,SHAP是一種對(duì)單一模型進(jìn)行解釋的工具,它通過分配特征對(duì)模型預(yù)測(cè)的貢獻(xiàn)值來(lái)衡量特征的重要性,所以針對(duì)Stacking需要逐層拆解進(jìn)行分析,可以通過以下兩種方式來(lái)解釋Stacking模型:

代碼實(shí)現(xiàn)

模型構(gòu)建

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings("ignore")

plt.rcParams['font.family'] = 'Times New Roman'
plt.rcParams['axes.unicode_minus'] = False
df = pd.read_excel('2024-12-7公眾號(hào)Python機(jī)器學(xué)習(xí)AI.xlsx')

from sklearn.model_selection import train_test_split, KFold

X = df.drop(['Y'],axis=1)
y = df['Y']

# 劃分訓(xùn)練集和測(cè)試集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,
random_state=42)

from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor, AdaBoostRegressor, StackingRegressor
from xgboost import XGBRegressor
from lightgbm import LGBMRegressor
from catboost import CatBoostRegressor
from sklearn.linear_model import LinearRegression

# 定義一級(jí)學(xué)習(xí)器
base_learners = [
("RF", RandomForestRegressor(n_estimators=100, random_state=42)),
("XGB", XGBRegressor(n_estimators=100, random_state=42, verbosity=0)),
("LGBM", LGBMRegressor(n_estimators=100, random_state=42, verbose=-1)),
("GBM", GradientBoostingRegressor(n_estimators=100, random_state=42)),
("AdaBoost", AdaBoostRegressor(n_estimators=100, random_state=42)),
("CatBoost", CatBoostRegressor(n_estimators=100, random_state=42, verbose=0))
]

# 定義二級(jí)學(xué)習(xí)器
meta_model = LinearRegression()

# 創(chuàng)建Stacking回歸器
stacking_regressor = StackingRegressor(estimators=base_learners, final_estimator=meta_model, cv=5)

# 訓(xùn)練模型
stacking_regressor.fit(X_train, y_train)

通過訓(xùn)練多個(gè)基學(xué)習(xí)器(如隨機(jī)森林、XGBoost等)和一個(gè)線性回歸作為元學(xué)習(xí)器,構(gòu)建并訓(xùn)練了一個(gè)用于回歸任務(wù)的Stacking集成模型。

基學(xué)習(xí)器SHAP值計(jì)算

針對(duì)RF單一模型解釋

shap_dfs['RF']

計(jì)算SHAP值,逐一解析Stacking模型中每個(gè)基學(xué)習(xí)器的特征重要性并保存為數(shù)據(jù)框,便于后續(xù)分析,這里只展示了隨機(jī)森林的shap值結(jié)果。

RF模型蜂巢圖

plt.figure()
shap.summary_plot(np.array(shap_dfs['RF']), X_test, feature_names=X_test.columns, plot_type="dot", show=False)
plt.savefig("RF summary_plot.pdf", format='pdf',bbox_inches='tight')

RF模型shap特征貢獻(xiàn)圖

plt.figure(figsize=(10, 5), dpi=1200)
shap.summary_plot(np.array(shap_dfs['RF']), X_test, plot_type="bar", show=False)
plt.title('SHAP_numpy Sorted Feature Importance')
plt.tight_layout()
plt.savefig("RF Sorted Feature Importance.pdf", format='pdf',bbox_inches='tight')
plt.show()

繪制基學(xué)習(xí)器里隨機(jī)森林的SHAP蜂巢圖和特征貢獻(xiàn)排序圖,其他基學(xué)習(xí)器也可用類似方法進(jìn)行特征重要性分析

繪制完整基學(xué)習(xí)器蜂巢圖

為Stacking模型中的所有基學(xué)習(xí)器繪制SHAP特征重要性蜂巢圖,可以發(fā)現(xiàn)每個(gè)基學(xué)習(xí)器的 SHAP 解釋并不相同,正是因?yàn)槊總€(gè)基學(xué)習(xí)器獨(dú)立工作并對(duì)特征有不同的偏好所導(dǎo)致的

繪制完整基學(xué)習(xí)器shap特征貢獻(xiàn)圖

為Stacking模型中的所有基學(xué)習(xí)器繪制SHAP特征貢獻(xiàn)排序圖(柱狀圖),展示每個(gè)基學(xué)習(xí)器特征重要性的平均影響,其它SHAP可視化同樣的道理繪制。

元學(xué)習(xí)器SHAP值計(jì)算

shap_df

計(jì)算元學(xué)習(xí)器的SHAP值,其中輸入特征是各基學(xué)習(xí)器的預(yù)測(cè)結(jié)果,模型僅對(duì)這些特征進(jìn)行解釋以揭示基學(xué)習(xí)器對(duì)最終預(yù)測(cè)的貢獻(xiàn)。

元學(xué)習(xí)器蜂巢圖

plt.figure()
shap.summary_plot(np.array(shap_df), shap_df, feature_names=shap_df.columns, plot_type="dot", show=False)
plt.title("SHAP Contribution Analysis for the Meta-Learner in the Second Layer of Stacking Regressor", fontsize=16, y=1.02)
plt.savefig("SHAP Contribution Analysis for the Meta-Learner in the Second Layer of Stacking Regressor.pdf", format='pdf', bbox_inches='tight')
plt.show()

元學(xué)習(xí)器hap特征貢獻(xiàn)圖

plt.figure(figsize=(10, 5), dpi=1200)
shap.summary_plot(np.array(shap_df), shap_df, plot_type="bar", show=False)
plt.tight_layout()
plt.title("Bar Plot of SHAP Feature Contributions for the Meta-Learner in Stacking Regressor", fontsize=16, y=1.02)
plt.savefig("Bar Plot of SHAP Feature Contributions for the Meta-Learner in Stacking Regressor.pdf", format='pdf', bbox_inches='tight')
plt.show()

繪制元學(xué)習(xí)器(第二層 LinearRegression)的SHAP蜂巢圖和特征貢獻(xiàn)排序圖,分別展示各基學(xué)習(xí)器的預(yù)測(cè)值對(duì)元學(xué)習(xí)器最終決策的影響分布和平均重要性。這些可視化結(jié)果揭示了在Stacking 第二層中,不同基學(xué)習(xí)器對(duì)元學(xué)習(xí)器預(yù)測(cè)的貢獻(xiàn)程度,從而幫助了解每個(gè)基學(xué)習(xí)器在整體模型中的相對(duì)重要性

元學(xué)習(xí)器蜂巢圖與特征關(guān)系圖結(jié)合展示

組合shap可視化蜂巢圖和特征貢獻(xiàn)圖,讓復(fù)雜的機(jī)器學(xué)習(xí)模型變得更加透明和易于解釋。

Stacking模型視為整體的“黑箱”解釋

Stacking模型整體shap計(jì)算

stacking_shap_df

對(duì)Stacking模型進(jìn)行整體解釋,計(jì)算輸入特征對(duì)模型預(yù)測(cè)輸出的貢獻(xiàn),僅關(guān)注輸入特征與最終預(yù)測(cè)輸出的關(guān)系,當(dāng)然這里作者只計(jì)算了測(cè)試集里前100個(gè)樣本的shap值,由于模型本身的復(fù)雜性同時(shí)計(jì)算所有樣本shap值對(duì)于時(shí)間成本有一定要求

Stacking模型整體蜂巢圖

plt.figure()
shap.summary_plot(np.array(stacking_shap_df), stacking_shap_df, feature_names=stacking_shap_df.columns, plot_type="dot", show=False)
plt.title("Based on the overall feature contribution analysis of SHAP to the stacking model", fontsize=16, y=1.02)
plt.savefig("Based on the overall feature contribution analysis of SHAP to the stacking model.pdf", format='pdf', bbox_inches='tight')
plt.show()

Stacking模型整體特征貢獻(xiàn)圖

plt.figure(figsize=(10, 5), dpi=1200)
shap.summary_plot(np.array(stacking_shap_df), shap_df, plot_type="bar", show=False)
plt.tight_layout()
plt.title("SHAP-based Stacking Model Feature Contribution Histogram Analysis", fontsize=16, y=1.02)
plt.savefig("SHAP-based Stacking Model Feature Contribution Histogram Analysis.pdf", format='pdf', bbox_inches='tight')
plt.show()

使用SHAP分析將Stacking模型視為整體的“黑箱”,可視化輸入特征對(duì)最終預(yù)測(cè)結(jié)果的整體貢獻(xiàn)關(guān)系生成蜂巢圖 、特征貢獻(xiàn)圖,同樣可以組合shap可視化蜂巢圖和特征貢獻(xiàn)圖,讓復(fù)雜的機(jī)器學(xué)習(xí)模型變得更加透明和易于解釋。

文章轉(zhuǎn)自微信公眾號(hào)@Python機(jī)器學(xué)習(xí)AI

上一篇:

SHAP進(jìn)階解析:機(jī)器學(xué)習(xí)、深度學(xué)習(xí)模型解釋保姆級(jí)教程

下一篇:

整合數(shù)據(jù)分布+擬合線+置信區(qū)間+相關(guān)系數(shù)的皮爾遜相關(guān)可視化
#你可能也喜歡這些API文章!

我們有何不同?

API服務(wù)商零注冊(cè)

多API并行試用

數(shù)據(jù)驅(qū)動(dòng)選型,提升決策效率

查看全部API→
??

熱門場(chǎng)景實(shí)測(cè),選對(duì)API

#AI文本生成大模型API

對(duì)比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力

25個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)

#AI深度推理大模型API

對(duì)比大模型API的邏輯推理準(zhǔn)確性、分析深度、可視化建議合理性

10個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)