I’m trying to save a force plot using SHAP , but I keep encountering the following error repeatedly:
posx and posy should be finite values
posx and posy should be finite values
...
Here is my code for SHAP to visualize the impact of features on my model’s predictions and I would like to save the force plot as an image file (e.g., PNG). However, I’m encountering an issue with the following code.
import shap
import matplotlib.pyplot as plt
import numpy as np
# Get indexes for specific classes
class_1_indexes = np.where(y_test == 1)[0]
class_0_indexes = np.where(y_test == 0)[0]
# Create SHAP explainer and values
shap_explainer = shap.TreeExplainer(model)
shap_values = shap_explainer.shap_values(X_test)
# Create a force plot
plt.figure(figsize=(20, 3)) # Set the figure size
shap.force_plot(
shap_explainer.expected_value,
shap_values[class_1_indexes[5]],
X_test[class_1_indexes[5]], # Assuming X_test is a DataFrame
feature_names=feature_names,
link='logit',
matplotlib=True,
text_rotation=7,
show=False # Prevent the plot from showing immediately
)
# Save the figure
plt.savefig('shap_force_plot.png', bbox_inches='tight')
# Optionally, show the plot if needed
plt.show()
I’m getting the error posx and posy should be finite values when attempting to save the plot.
Here is the output of my code.
How can I properly save a SHAP force plot as an image (PNG)? increase the graph size and font size?