shap 无法处理 object 类型的功能。只需确保您的连续变量的类型为 float 并且您的分类变量的类型为 category。
for cont in continuous_variables:
df[cont] = df[cont].astype('float64')
for cat in categorical_variables:
df[cat] = df[cat].astype('category')
最后,您还需要确保在参数中提供相应的值:
params = {
'objective': "binary",
'num_leaves': 100,
'num_trees': 500,
'learning_rate': 0.1,
'tree_learner': 'data',
'device': 'cpu',
'seed': 132,
'max_depth': -1,
'min_data_in_leaf': 50,
'subsample': 0.9,
'feature_fraction': 1,
'metric': 'binary_logloss',
'categorical_feature': ['categoricalFeature1', 'categoricalFeature2']
}
bst = lgbm.Booster(model_file='model_file.txt')
tree_explainer = shap.TreeExplainer(bst)
tree_explainer.model.original_model.params = params
shap_values_result = tree_explainer.shap_values(df[features], y=df[target])
或者,您可以选择对分类特征应用标签编码。例如,
df['categoricalFeature'] = df['categoricalFeature'].astype('category')
df['categoricalFeature'] = df['categoricalFeature'].cat.codes
请注意,请确保您可以重现此映射,以便您也可以以相同的方式转换验证/测试数据集。