Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -9,23 +9,34 @@ from sklearn.pipeline import make_pipeline
|
|
| 9 |
sentiment_model = pipeline("text-classification", model="cardiffnlp/twitter-roberta-base-sentiment", top_k=None)
|
| 10 |
|
| 11 |
# Define possible sentiment classes
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
# Function to get sentiment prediction
|
| 15 |
def analyze_sentiment(text):
|
| 16 |
results = sentiment_model(text)
|
| 17 |
-
scores = {res['label']: res['score'] for res in results[0]}
|
| 18 |
sorted_scores = sorted(scores.items(), key=lambda x: x[1], reverse=True)
|
| 19 |
top_label, top_confidence = sorted_scores[0]
|
| 20 |
return f"Sentiment: {top_label} (Confidence: {top_confidence:.2f})"
|
| 21 |
|
| 22 |
# Explainability function using LIME
|
| 23 |
def explain_prediction(text):
|
| 24 |
-
explainer = lime.lime_text.LimeTextExplainer(class_names=
|
| 25 |
|
| 26 |
def predictor(texts):
|
| 27 |
predictions = [sentiment_model(text)[0] for text in texts]
|
| 28 |
-
return np.array([[pred[label] if label in pred else 0 for label in
|
| 29 |
|
| 30 |
exp = explainer.explain_instance(text, predictor, num_features=6)
|
| 31 |
return exp.as_list()
|
|
|
|
| 9 |
sentiment_model = pipeline("text-classification", model="cardiffnlp/twitter-roberta-base-sentiment", top_k=None)
|
| 10 |
|
| 11 |
# Define possible sentiment classes
|
| 12 |
+
label_mapping = {
|
| 13 |
+
"LABEL_0": "very negative",
|
| 14 |
+
"LABEL_1": "negative",
|
| 15 |
+
"LABEL_2": "slightly negative",
|
| 16 |
+
"LABEL_3": "neutral",
|
| 17 |
+
"LABEL_4": "slightly positive",
|
| 18 |
+
"LABEL_5": "positive",
|
| 19 |
+
"LABEL_6": "very positive",
|
| 20 |
+
"LABEL_7": "anger",
|
| 21 |
+
"LABEL_8": "joy",
|
| 22 |
+
"LABEL_9": "sadness"
|
| 23 |
+
}
|
| 24 |
|
| 25 |
# Function to get sentiment prediction
|
| 26 |
def analyze_sentiment(text):
|
| 27 |
results = sentiment_model(text)
|
| 28 |
+
scores = {label_mapping.get(res['label'], res['label']): res['score'] for res in results[0]}
|
| 29 |
sorted_scores = sorted(scores.items(), key=lambda x: x[1], reverse=True)
|
| 30 |
top_label, top_confidence = sorted_scores[0]
|
| 31 |
return f"Sentiment: {top_label} (Confidence: {top_confidence:.2f})"
|
| 32 |
|
| 33 |
# Explainability function using LIME
|
| 34 |
def explain_prediction(text):
|
| 35 |
+
explainer = lime.lime_text.LimeTextExplainer(class_names=list(label_mapping.values()))
|
| 36 |
|
| 37 |
def predictor(texts):
|
| 38 |
predictions = [sentiment_model(text)[0] for text in texts]
|
| 39 |
+
return np.array([[pred[label] if label in pred else 0 for label in label_mapping.values()] for pred in predictions])
|
| 40 |
|
| 41 |
exp = explainer.explain_instance(text, predictor, num_features=6)
|
| 42 |
return exp.as_list()
|