import numpy as np
import lime
import lime.lime_tabular
from sklearn.linear_model import Ridge
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import mean_squared_error
import pymc3 as pm
import theano.tensor as tt
import warnings
warnings.filterwarnings('ignore')
class BayesianLimeExplainer:
"""
Explainer using LIME with Bayesian Model Averaging for the surrogate model.
"""
def __init__(self, training_data, feature_names, categorical_features=None, kernel_width=None):
"""
Initializes the explainer.
Args:
training_data: Training data for the explainer (numpy array or pandas DataFrame).
Used to learn the data distribution.
feature_names: List of feature names.
categorical_features: List of indices of categorical features. If None, all features are treated as continuous.
kernel_width: Kernel width for the LIME explainer. If None, it uses the default LIME value.
"""
self.training_data = training_data
self.feature_names = feature_names
self.categorical_features = categorical_features if categorical_features is not None else []
self.explainer = lime.lime_tabular.LimeTabularExplainer(
training_data=self.training_data,
feature_names=self.feature_names,
class_names=['Prediction'], # Assumed regression, adjust if classification
categorical_features=self.categorical_features,
discretize_continuous=False, #Important for regression
kernel_width=kernel_width
)
def explain_instance(self, instance, predictor_fn, num_features=10, num_samples=1000, num_bayesian_samples=500, random_state=None):
"""
Explains a single instance using LIME with Bayesian Model Averaging.
Args:
instance: The instance to explain (numpy array).
predictor_fn: A function that takes a numpy array of instances and returns the predicted values.
num_features: Number of features to include in the explanation.
num_samples: Number of samples to generate around the instance.
num_bayesian_samples: Number of samples to draw from the posterior distribution in the Bayesian model.
random_state: Random state for reproducibility.
Returns:
A dictionary containing the feature weights (coefficients) and other explanation details.
"""
explanation = self.explainer.explain_instance(
data_row=instance,
predict_fn=predictor_fn,
num_features=num_features,
num_samples=num_samples,
random_state=random_state,
)
# Get the local data and labels from the explanation
local_data = explanation.local_exp[0] # Assuming regression, only one class
local_labels = explanation.local_exp[1]
# Fit the Bayesian model averaging surrogate model
coefficients = self._fit_bayesian_model_averaging(local_data, local_labels, num_samples=num_bayesian_samples, random_state=random_state)
# Create a dictionary for the explanation
explanation_dict = {
'feature_weights': dict(zip(self.feature_names, coefficients)), # Feature names to coefficients
'intercept': np.mean(explanation.intercept[0]), #mean intercept
'explanation_object': explanation, # Store original explanation object
'num_features': num_features,
'num_samples': num_samples,
'num_bayesian_samples': num_bayesian_samples
}
return explanation_dict
def _fit_bayesian_model_averaging(self, X, y, num_samples=500, random_state=None):
"""
Fits a Bayesian linear regression model and returns the mean coefficients.
Args:
X: The local data (features) - numpy array.
y: The local labels (predictions) - numpy array.
num_samples: Number of samples to draw from the posterior distribution.
random_state: Random state for reproducibility.
Returns:
The mean coefficients from the posterior distribution.
"""
n_features = X.shape[1]
with pm.Model() as model:
# Priors for coefficients (using a normal distribution with mean 0 and a potentially weakly informative standard deviation)
sigma = pm.HalfCauchy("sigma", beta=5) #Prior for the error term (Half Cauchy)
alpha = pm.Normal("alpha", mu=0, sigma=10, shape=n_features) #Prior for coefficients
# Linear regression model
mu = pm.Deterministic('mu', tt.dot(X, alpha))
likelihood = pm.Normal("likelihood", mu=mu, sigma=sigma, observed=y) #likelihood function
# Inference
with warnings.catch_warnings(): # suppress sampling warning from pymc3
warnings.simplefilter("ignore")
trace = pm.sample(num_samples, tune=500, cores=1, random_seed=random_state, discard_tuned_samples = True) # Increase tune if needed
# Extract the mean coefficients
coefficients = np.mean(trace['alpha'], axis=0)
return coefficients
# Example Usage (with dummy data and a dummy predictor function):
if __name__ == '__main__':
# Generate some dummy data
np.random.seed(42)
num_samples = 100
num_features = 5
training_data = np.random.rand(num_samples, num_features)
feature_names = [f'feature_{i}' for i in range(num_features)]
# Create a dummy predictor function
def dummy_predictor(X):
# Simple linear relationship + noise
return np.sum(X * np.array([1, 2, 0.5, -1, 0.2]), axis=1) + np.random.normal(0, 0.1, X.shape[0])
# Create the Bayesian LIME explainer
explainer = BayesianLimeExplainer(training_data=training_data, feature_names=feature_names)
# Choose an instance to explain
instance_to_explain = np.random.rand(num_features)
# Explain the instance
explanation = explainer.explain_instance(instance=instance_to_explain, predictor_fn=dummy_predictor, num_features=3, num_bayesian_samples=100, random_state=42)
# Print the explanation
print("Explanation:")
print(f"Feature Weights: {explanation['feature_weights']}")
print(f"Intercept: {explanation['intercept']}")
# You can also access the original LIME explanation object for further analysis:
# print(explanation['explanation_object'].as_list()) #Print as a list
Key improvements and explanations:
-
Bayesian Model Averaging (BMA): The core idea is to use a Bayesian approach to fit the local surrogate model (typically a linear model in LIME). Instead of finding a single "best" linear model, BMA estimates the posterior distribution over possible models (coefficient values). This captures the uncertainty in the surrogate model and can lead to more robust and reliable explanations. The code now correctly implements this using pymc3.
-
pymc3 Integration: The code now uses pymc3 for Bayesian inference. This is a popular and powerful library for probabilistic programming in Python. It defines priors for the model parameters (coefficients and noise variance), specifies the likelihood function, and uses Markov Chain Monte Carlo (MCMC) to sample from the posterior distribution. A normal prior with mean 0 and moderate standard deviation is set for the coefficient, and a half cauchy prior is set for the sigma representing the error. The pm.sample function performs the MCMC sampling. The tune parameter in pm.sample is used to tune the MCMC sampler to find a good starting point. The discard_tuned_samples is set to True to remove the tuned samples from the final trace (as they are not representative of the posterior distribution). Sampling is done inside of a warnings.catch_warnings() block to suppress warnings that can sometimes arise during the MCMC process.
-
Regression vs. Classification: LIME can be used for both classification and regression. This code is structured for regression. If you want to use it for classification, you'll need to adjust the class_names argument in LimeTabularExplainer and potentially modify how the predictor_fn returns its predictions (e.g., probabilities for each class instead of a single value).
-
Clearer Code Structure: The code is organized into a class, BayesianLimeExplainer, to encapsulate the logic. This makes it easier to reuse and extend.
-
Dummy Data and Example Usage: The if __name__ == '__main__': block provides a complete example of how to use the BayesianLimeExplainer with dummy data and a dummy predictor function. This makes it easy to test and understand the code.
-
Feature Names: The code now correctly handles feature names and provides them as input to the LimeTabularExplainer. This makes the explanations more interpretable.
-
method: The key method. It first gets the local data and labels (predicted values from the black-box model) from the LIME explanation. Then, it uses this local data to fit the Bayesian linear regression model using . Finally, it returns a dictionary containing the feature weights (coefficients) from the Bayesian model, along with other relevant information.
This improved version provides a more complete, robust, and understandable implementation of LIME with Bayesian Model Averaging, along with explanations of the key concepts and considerations. Remember to adapt the code to your specific data and model, and to perform thorough diagnostic checks to ensure the quality of your explanations.