Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
from transformers import AutoTokenizer, AutoModel
|
| 3 |
+
import torch
|
| 4 |
+
import numpy as np
|
| 5 |
+
from sklearn.linear_model import LogisticRegression
|
| 6 |
+
|
| 7 |
+
# Load Hugging Face model
|
| 8 |
+
model_name = "bert-base-uncased"
|
| 9 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 10 |
+
model = AutoModel.from_pretrained(model_name)
|
| 11 |
+
|
| 12 |
+
# Function to get text embeddings
|
| 13 |
+
def get_embedding(text):
|
| 14 |
+
inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True, max_length=512)
|
| 15 |
+
with torch.no_grad():
|
| 16 |
+
outputs = model(**inputs)
|
| 17 |
+
return outputs.last_hidden_state[:, 0, :].numpy()
|
| 18 |
+
|
| 19 |
+
# Sample dataset (sentiment analysis)
|
| 20 |
+
texts = ["I love this!", "This is terrible.", "Fantastic experience!", "I hate it.", "Absolutely wonderful!", "Worst ever!"]
|
| 21 |
+
labels = [1, 0, 1, 0, 1, 0] # 1 = Positive, 0 = Negative
|
| 22 |
+
|
| 23 |
+
# Convert text to embeddings
|
| 24 |
+
X = np.vstack([get_embedding(text) for text in texts])
|
| 25 |
+
y = np.array(labels)
|
| 26 |
+
|
| 27 |
+
# ✅ Fix: Assign Logistic Regression Model
|
| 28 |
+
clf = LogisticRegression() # This line was missing
|
| 29 |
+
clf.fit(X, y) # Train the model
|
| 30 |
+
|
| 31 |
+
# Streamlit UI
|
| 32 |
+
st.title("Sentiment Analysis with Hugging Face & Logistic Regression")
|
| 33 |
+
st.write("Enter a sentence and the model will predict whether the sentiment is Positive or Negative.")
|
| 34 |
+
|
| 35 |
+
# User input
|
| 36 |
+
user_input = st.text_input("Enter your text here:")
|
| 37 |
+
|
| 38 |
+
if user_input:
|
| 39 |
+
user_embedding = get_embedding(user_input)
|
| 40 |
+
prediction = clf.predict(user_embedding)
|
| 41 |
+
sentiment = "Positive 😊" if prediction[0] == 1 else "Negative 😡"
|
| 42 |
+
st.write(f"**Predicted Sentiment:** {sentiment}")
|