Generating SHAP Values with SHAP Library

  • Share this:

Code introduction


This function uses the SHAP library to generate SHAP values for a given dataset and model, which can explain the contribution of each feature in the model's predictions.


Technology Stack : SHAP library, NumPy, scikit-learn

Code Type : Function

Code Difficulty : Intermediate


                
                    
import numpy as np
import shap
from sklearn.ensemble import RandomForestClassifier

def generate_shap_values(data, target, model):
    """
    Generates SHAP values for a given dataset and model using SHAP library.
    """
    # Create a SHAP explainer
    explainer = shap.TreeExplainer(model)
    
    # Compute SHAP values
    shap_values = explainer.shap_values(data)
    
    # Return the SHAP values
    return shap_values

# Example usage
data = np.array([[1, 2], [3, 4], [5, 6]])
target = np.array([0, 1, 0])
model = RandomForestClassifier()
model.fit(data, target)

shap_values = generate_shap_values(data, target, model)