我已经使用GridSearchCV调整了一个模型。现在我想计算Shapley值并可视化它们。困难在于shap
包需要一个模型,而不是GridSearch的结果。同样,当我传递best_estimator_属性时,它也不喜欢。它说模型不被支持。我如何从GridSearchCV或其他东西中获取Shapley值来计算Shapley值。我的一个列是分类列,因此需要预处理。由于我从网格搜索中获得了最佳参数,我可以将模型作为xgboost_regressor模型运行,但自从没有预处理的情况下这样做已经有一段时间了。
from xgboost import XGBRegressor as xgr model=xgr(booster ='gbtree', random_state = 13)cv_inner = KFold(n_splits=5, shuffle=True)params = { 'model__n_estimators' : [1500,2000] ,'model__learning_rate' : [0.1,0.2,0.3] ,'model__gamma' : [0, 0.005,0.01] ,'model__lambda' : [0.1, 0.2,0.3] ,'model__alpha' : [0, 0.001, 0.05] ,'model__max_depth' : [6] ,'model__min_child_weight' : [1] ,'model__subsample' : [0.8] }preprocessor = ColumnTransformer( transformers=[ ('cat', OneHotEncoder(), [0]) ] ,remainder = 'passthrough')mymodel = Pipeline(steps = [ ('preprocessor',preprocessor), ('model', model) ])optimize_hparams = GridSearchCV( estimator = mymodel, param_grid=params, n_jobs = -1, cv=cv_inner, scoring='neg_mean_absolute_error')optimize_hparams.fit(X, y)import shapshap_values = shap.TreeExplainer(optimize_hparams.best_estimator_['model']).shap_values(X)shap.summary_plot(shap_values, X, plot_type="bar")
回答:
在计算Shap值之前,你需要将预处理器和网格搜索中最佳模型都拟合到数据上,参见下面的代码示例。