freddyaboulton HF staff commited on
Commit
3d326ae
1 Parent(s): fc1396e

Add app file

Browse files
Files changed (2) hide show
  1. app.py +57 -0
  2. requirements.txt +3 -0
app.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import shap
3
+ from transformers import pipeline
4
+ import matplotlib
5
+ import matplotlib.pyplot as plt
6
+ matplotlib.use('Agg')
7
+
8
+
9
+ sentiment_classifier = pipeline("text-classification", return_all_scores=True)
10
+
11
+
12
+ def classifier(text):
13
+ pred = sentiment_classifier(text)
14
+ return {p["label"]: p["score"] for p in pred[0]}
15
+
16
+
17
+ def interpretation_function(text):
18
+ explainer = shap.Explainer(sentiment_classifier)
19
+ shap_values = explainer([text])
20
+ # Dimensions are (batch size, text size, number of classes)
21
+ # Since we care about positive sentiment, use index 1
22
+ scores = list(zip(shap_values.data[0], shap_values.values[0, :, 1]))
23
+
24
+ scores_desc = sorted(scores, key=lambda t: t[1])[::-1]
25
+
26
+ # Filter out empty string added by shap
27
+ scores_desc = [t for t in scores_desc if t[0] != ""]
28
+
29
+ fig_m = plt.figure()
30
+ plt.bar(x=[s[0] for s in scores_desc[:5]],
31
+ height=[s[1] for s in scores_desc[:5]])
32
+ plt.title("Top words contributing to positive sentiment")
33
+ plt.ylabel("Shap Value")
34
+ plt.xlabel("Word")
35
+ return {"original": text, "interpretation": scores}, fig_m
36
+
37
+
38
+ with gr.Blocks() as demo:
39
+ with gr.Row():
40
+ with gr.Column():
41
+ input_text = gr.Textbox(label="Input Text")
42
+ with gr.Row():
43
+ classify = gr.Button("Classify Sentiment")
44
+ interpret = gr.Button("Interpret")
45
+ with gr.Column():
46
+ label = gr.Label(label="Predicted Sentiment")
47
+ with gr.Column():
48
+ with gr.Tabs():
49
+ with gr.TabItem("Display interpretation with built-in component"):
50
+ interpretation = gr.components.Interpretation(input_text)
51
+ with gr.TabItem("Display interpretation with plot"):
52
+ interpretation_plot = gr.Plot()
53
+
54
+ classify.click(classifier, input_text, label)
55
+ interpret.click(interpretation_function, input_text, [interpretation, interpretation_plot])
56
+
57
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ torch
2
+ transformers==4.16.2
3
+ shap