Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import lime
|
| 3 |
+
from lime.lime_text import LimeTextExplainer
|
| 4 |
+
import numpy as np
|
| 5 |
+
from datasets import load_dataset
|
| 6 |
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 7 |
+
from sklearn.model_selection import train_test_split
|
| 8 |
+
from sklearn.linear_model import LogisticRegression
|
| 9 |
+
from sklearn.pipeline import make_pipeline
|
| 10 |
+
import shap
|
| 11 |
+
import matplotlib.pyplot as plt
|
| 12 |
+
import io
|
| 13 |
+
from PIL import Image
|
| 14 |
+
import pandas as pd
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
# Load the IMDB dataset using Hugging Face datasets
|
| 18 |
+
dataset = load_dataset('imdb')
|
| 19 |
+
|
| 20 |
+
# Extract the training and test sets
|
| 21 |
+
text_train = [review['text'] for review in dataset['train']]
|
| 22 |
+
y_train = [review['label'] for review in dataset['train']]
|
| 23 |
+
text_test = [review['text'] for review in dataset['test']]
|
| 24 |
+
y_test = [review['label'] for review in dataset['test']]
|
| 25 |
+
|
| 26 |
+
# Convert the text data into a TF-IDF representation
|
| 27 |
+
vectorizer = TfidfVectorizer(stop_words='english', max_features=5000)
|
| 28 |
+
X_train = vectorizer.fit_transform(text_train)
|
| 29 |
+
X_test = vectorizer.transform(text_test)
|
| 30 |
+
|
| 31 |
+
# Split the training data into train and validation sets
|
| 32 |
+
X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.2, random_state=42)
|
| 33 |
+
|
| 34 |
+
# Train a logistic regression model
|
| 35 |
+
model = LogisticRegression(max_iter=1000)
|
| 36 |
+
model.fit(X_train, y_train)
|
| 37 |
+
|
| 38 |
+
# Initialize LIME explainer
|
| 39 |
+
lime_explainer = LimeTextExplainer(class_names=['Negative', 'Positive'])
|
| 40 |
+
|
| 41 |
+
# Create a SHAP explainer object
|
| 42 |
+
shap_explainer = shap.LinearExplainer(model, X_train)
|
| 43 |
+
|
| 44 |
+
def explain_text(input_text):
|
| 45 |
+
# Predict label
|
| 46 |
+
input_vector = vectorizer.transform([input_text])
|
| 47 |
+
predicted_label = model.predict(input_vector)[0]
|
| 48 |
+
label_name = 'Positive' if predicted_label == 1 else 'Negative'
|
| 49 |
+
|
| 50 |
+
# LIME explanation
|
| 51 |
+
def predict_proba_for_lime(texts):
|
| 52 |
+
return model.predict_proba(vectorizer.transform(texts))
|
| 53 |
+
|
| 54 |
+
lime_exp = lime_explainer.explain_instance(input_text, predict_proba_for_lime, num_features=10)
|
| 55 |
+
lime_fig = lime_exp.as_pyplot_figure()
|
| 56 |
+
lime_img = fig_to_nparray(lime_fig)
|
| 57 |
+
|
| 58 |
+
# Get the complete HTML for LIME explanation
|
| 59 |
+
lime_html = lime_exp.as_html()
|
| 60 |
+
|
| 61 |
+
# SHAP explanation
|
| 62 |
+
shap_values = shap_explainer.shap_values(input_vector)[0]
|
| 63 |
+
feature_names = vectorizer.get_feature_names_out()
|
| 64 |
+
|
| 65 |
+
# Create a SHAP explanation object for the selected instance
|
| 66 |
+
shap_explanation = shap.Explanation(
|
| 67 |
+
values=shap_values,
|
| 68 |
+
base_values=shap_explainer.expected_value,
|
| 69 |
+
feature_names=feature_names,
|
| 70 |
+
data=input_vector.toarray()[0]
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
# Function to highlight text based on SHAP values
|
| 74 |
+
def highlight_text_shap(text, word_importances, feature_names, max_num_features):
|
| 75 |
+
words = text.split()
|
| 76 |
+
word_to_importance = {}
|
| 77 |
+
for idx, word in enumerate(feature_names):
|
| 78 |
+
if word in text.lower():
|
| 79 |
+
word_to_importance[word] = word_importances[idx]
|
| 80 |
+
|
| 81 |
+
sorted_word_importance = sorted(word_to_importance.items(), key=lambda x: abs(x[1]), reverse=True)[:max_num_features]
|
| 82 |
+
top_words = {word: importance for word, importance in sorted_word_importance}
|
| 83 |
+
|
| 84 |
+
highlighted_text = []
|
| 85 |
+
for word in words:
|
| 86 |
+
cleaned_word = ''.join(filter(str.isalnum, word)).lower()
|
| 87 |
+
if cleaned_word in top_words:
|
| 88 |
+
importance = top_words[cleaned_word]
|
| 89 |
+
color = 'red' if importance > 0 else 'blue'
|
| 90 |
+
highlighted_text.append(f'<span style="color:{color}">{word}</span>')
|
| 91 |
+
else:
|
| 92 |
+
highlighted_text.append(word)
|
| 93 |
+
|
| 94 |
+
return ' '.join(highlighted_text)
|
| 95 |
+
|
| 96 |
+
# Set the maximum number of features to display
|
| 97 |
+
max_num_features = 10
|
| 98 |
+
|
| 99 |
+
# Create a DataFrame for SHAP values
|
| 100 |
+
shap_df = pd.DataFrame({
|
| 101 |
+
'Feature': shap_explanation.feature_names,
|
| 102 |
+
'SHAP Value': shap_explanation.values
|
| 103 |
+
}).sort_values(by='SHAP Value', ascending=False).head(max_num_features)
|
| 104 |
+
|
| 105 |
+
# Plot the SHAP values
|
| 106 |
+
plt.figure(figsize=(10, 6))
|
| 107 |
+
plt.barh(shap_df['Feature'], shap_df['SHAP Value'], color=['red' if val > 0 else 'blue' for val in shap_df['SHAP Value']])
|
| 108 |
+
plt.xlabel('SHAP Value')
|
| 109 |
+
plt.title('Top 10 Feature Importance')
|
| 110 |
+
plt.tight_layout()
|
| 111 |
+
shap_fig = fig_to_nparray(plt.gcf())
|
| 112 |
+
|
| 113 |
+
# Highlight the text based on SHAP values
|
| 114 |
+
shap_highlighted_text = highlight_text_shap(input_text, shap_values, feature_names, max_num_features)
|
| 115 |
+
|
| 116 |
+
return label_name, lime_img, shap_fig, lime_html, shap_highlighted_text
|
| 117 |
+
|
| 118 |
+
def fig_to_nparray(fig):
|
| 119 |
+
"""Convert a matplotlib figure to a NumPy array."""
|
| 120 |
+
buf = io.BytesIO()
|
| 121 |
+
fig.savefig(buf, format='png')
|
| 122 |
+
buf.seek(0)
|
| 123 |
+
img = Image.open(buf)
|
| 124 |
+
return np.array(img)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
# Create Gradio interface
|
| 128 |
+
iface = gr.Interface(
|
| 129 |
+
fn=explain_text,
|
| 130 |
+
inputs=gr.Textbox(lines=2, placeholder="Enter your text here..."),
|
| 131 |
+
outputs=[
|
| 132 |
+
gr.Label(label="Predicted Label"),
|
| 133 |
+
gr.Image(type="numpy", label="LIME Explanation"),
|
| 134 |
+
gr.Image(type="numpy", label="SHAP Explanation"),
|
| 135 |
+
gr.HTML(label="LIME Highlighted Text Explanation"),
|
| 136 |
+
gr.HTML(label="SHAP Highlighted Text Explanation"),
|
| 137 |
+
],
|
| 138 |
+
title="LIME and SHAP Explanations",
|
| 139 |
+
description="Enter a text sample to see its prediction and explanations using LIME and SHAP."
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
# Launch the interface
|
| 143 |
+
iface.launch()
|