Spaces:
Running
Running
Create 23_NLP_Transformer_Prompt3.py
Browse files
pages/23_NLP_Transformer_Prompt3.py
ADDED
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import torch
|
3 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
4 |
+
import matplotlib.pyplot as plt
|
5 |
+
import seaborn as sns
|
6 |
+
|
7 |
+
# Load pre-trained model and tokenizer
|
8 |
+
model_name = "distilbert-base-uncased-finetuned-sst-2-english"
|
9 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
10 |
+
model = AutoModelForSequenceClassification.from_pretrained(model_name)
|
11 |
+
|
12 |
+
def analyze_sentiment(text):
|
13 |
+
inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True, max_length=512)
|
14 |
+
outputs = model(**inputs)
|
15 |
+
probs = torch.nn.functional.softmax(outputs.logits, dim=-1)
|
16 |
+
return probs.detach().numpy()[0]
|
17 |
+
|
18 |
+
st.title("Sentiment Analysis with Transformer")
|
19 |
+
|
20 |
+
user_input = st.text_area("Enter text for sentiment analysis:", "I love this product!")
|
21 |
+
|
22 |
+
if st.button("Analyze Sentiment"):
|
23 |
+
sentiment_scores = analyze_sentiment(user_input)
|
24 |
+
|
25 |
+
st.write("Sentiment Scores:")
|
26 |
+
st.write(f"Negative: {sentiment_scores[0]:.4f}")
|
27 |
+
st.write(f"Positive: {sentiment_scores[1]:.4f}")
|
28 |
+
|
29 |
+
# Create and display multiple graphs
|
30 |
+
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))
|
31 |
+
|
32 |
+
# Bar plot
|
33 |
+
ax1.bar(['Negative', 'Positive'], sentiment_scores)
|
34 |
+
ax1.set_ylabel('Score')
|
35 |
+
ax1.set_title('Sentiment Analysis Results (Bar Plot)')
|
36 |
+
|
37 |
+
# Pie chart
|
38 |
+
ax2.pie(sentiment_scores, labels=['Negative', 'Positive'], autopct='%1.1f%%')
|
39 |
+
ax2.set_title('Sentiment Analysis Results (Pie Chart)')
|
40 |
+
|
41 |
+
st.pyplot(fig)
|
42 |
+
|
43 |
+
# Heatmap
|
44 |
+
fig, ax = plt.subplots(figsize=(8, 2))
|
45 |
+
sns.heatmap([sentiment_scores], annot=True, cmap="coolwarm", cbar=False, ax=ax)
|
46 |
+
ax.set_xticklabels(['Negative', 'Positive'])
|
47 |
+
ax.set_yticklabels(['Sentiment'])
|
48 |
+
ax.set_title('Sentiment Analysis Results (Heatmap)')
|
49 |
+
st.pyplot(fig)
|
50 |
+
|
51 |
+
st.write("Note: This example uses a pre-trained model for English sentiment analysis.")
|