【问题标题】:How to tell the shap tree explainer and shap values calculator which variables are categorical?如何告诉 shap 树解释器和 shap 值计算器哪些变量是分类的?
【发布时间】:2019-12-08 15:54:13
【问题描述】:

我需要更好地理解我的 LightGBM 模型,所以我使用 SHAP Tree 解释器。 lightgbm 需要对数据进行编码,我将相同的数据传递给树解释器。所以,我担心 SHAP TreeExplainershap_values() 将我的数据视为数字数据。如何指定数据是分类的?这会改变 SHAP 值的计算吗?

我已经通过documentation

【问题讨论】:

    标签: python machine-learning lightgbm shap


    【解决方案1】:

    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
    

    请注意,请确保您可以重现此映射,以便您也可以以相同的方式转换验证/测试数据集。

    【讨论】:

      猜你喜欢
      • 2021-12-19
      • 2021-05-28
      • 2020-07-02
      • 1970-01-01
      • 2021-07-27
      • 2021-03-09
      • 2020-01-31
      • 1970-01-01
      相关资源
      最近更新 更多