Spaces:
Running
Running
Create NLP_Transformer_Prompt_2.py
Browse files
pages/NLP_Transformer_Prompt_2.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from transformers import BertTokenizer, BertForSequenceClassification
|
| 3 |
+
from transformers import pipeline
|
| 4 |
+
import matplotlib.pyplot as plt
|
| 5 |
+
import streamlit as st
|
| 6 |
+
|
| 7 |
+
# Load pre-trained model and tokenizer
|
| 8 |
+
model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
|
| 9 |
+
model = BertForSequenceClassification.from_pretrained(model_name)
|
| 10 |
+
tokenizer = BertTokenizer.from_pretrained(model_name)
|
| 11 |
+
|
| 12 |
+
# Function to classify text
|
| 13 |
+
def classify_text(text):
|
| 14 |
+
inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True)
|
| 15 |
+
outputs = model(**inputs)
|
| 16 |
+
scores = torch.nn.functional.softmax(outputs.logits, dim=1)
|
| 17 |
+
return scores
|
| 18 |
+
|
| 19 |
+
# Streamlit interface
|
| 20 |
+
st.title("NLP Transformer with PyTorch and Hugging Face")
|
| 21 |
+
st.header("Sentiment Analysis")
|
| 22 |
+
|
| 23 |
+
text = st.text_area("Enter text for sentiment analysis:")
|
| 24 |
+
|
| 25 |
+
if st.button("Classify"):
|
| 26 |
+
scores = classify_text(text).detach().numpy()[0]
|
| 27 |
+
labels = ["1 star", "2 stars", "3 stars", "4 stars", "5 stars"]
|
| 28 |
+
|
| 29 |
+
st.write("Classification Scores:")
|
| 30 |
+
for label, score in zip(labels, scores):
|
| 31 |
+
st.write(f"{label}: {score:.4f}")
|
| 32 |
+
|
| 33 |
+
fig, ax = plt.subplots()
|
| 34 |
+
ax.bar(labels, scores, color='blue')
|
| 35 |
+
ax.set_xlabel('Sentiment')
|
| 36 |
+
ax.set_ylabel('Score')
|
| 37 |
+
ax.set_title('Sentiment Analysis Scores')
|
| 38 |
+
st.pyplot(fig)
|