Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
import shap
|
| 4 |
+
import numpy as np
|
| 5 |
+
import matplotlib.pyplot as plt
|
| 6 |
+
from transformers import pipeline
|
| 7 |
+
|
| 8 |
+
# Load sentiment model
|
| 9 |
+
classifier = pipeline("sentiment-analysis")
|
| 10 |
+
|
| 11 |
+
def predict_with_shap(text):
|
| 12 |
+
if not text.strip():
|
| 13 |
+
return "Please enter text", None
|
| 14 |
+
|
| 15 |
+
# Get prediction
|
| 16 |
+
result = classifier(text)[0]
|
| 17 |
+
label = result["label"]
|
| 18 |
+
score = result["score"]
|
| 19 |
+
|
| 20 |
+
# SHAP explainer
|
| 21 |
+
explainer = shap.Explainer(classifier)
|
| 22 |
+
shap_values = explainer([text])
|
| 23 |
+
|
| 24 |
+
# Plot SHAP values
|
| 25 |
+
plt.figure()
|
| 26 |
+
shap.plots.text(shap_values[0], display=False)
|
| 27 |
+
|
| 28 |
+
return f"Prediction: {label} (Confidence: {score:.2f})", plt.gcf()
|
| 29 |
+
|
| 30 |
+
with gr.Blocks(title="Sentiment Analysis with SHAP") as demo:
|
| 31 |
+
gr.Markdown("# Sentiment Analysis with SHAP Explanation")
|
| 32 |
+
|
| 33 |
+
inp = gr.Textbox(lines=4, placeholder="Enter text here...")
|
| 34 |
+
out_text = gr.Textbox(label="Prediction")
|
| 35 |
+
out_plot = gr.Plot(label="SHAP Explanation")
|
| 36 |
+
btn = gr.Button("Analyze")
|
| 37 |
+
|
| 38 |
+
btn.click(predict_with_shap, inp, [out_text, out_plot])
|
| 39 |
+
|
| 40 |
+
demo.launch()
|