Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtaining the SHAP values for a prediction made with kNN

Tags:

shap

If I want to obtain the SHAP values with kernel SHAP for a kNN classifier with n variables, do I have to recalculate the prediction 2^n times?

(I'm not using python, but MATLAB, so I need to know the inside of the algorithm)

like image 644
sjv Avatar asked Oct 20 '25 09:10

sjv


1 Answers

For those who use python find the following script to get shap values from a knn model. For step by step modeling follow this link:

# Initialize model
knn = sklearn.neighbors.KNeighborsClassifier()

# Fit the model
knn.fit(X_train, Y_train)

# Get the model explainer object
explainer = shap.KernelExplainer(knn.predict_proba, X_train)

# Get shap values for the test data observation whose index is 0, i.e. first observation in the test set
shap_values = explainer.shap_values(X_test.iloc[0,:])

# Generate a force plot for this first observation using the derived shap values
shap.force_plot(explainer.expected_value[0], shap_values[0], X_test.iloc[0,:])
like image 69
Jane Kathambi Avatar answered Oct 21 '25 23:10

Jane Kathambi