File size: 2,490 Bytes
2ea2157 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | import streamlit as st
import pickle
import numpy as np
import re
from gensim.models import Word2Vec
from nltk.corpus import stopwords
import nltk
nltk.download('stopwords')
# ===============================
# Word2VecVectorizer class (must be defined before loading pickle)
# ===============================
class Word2VecVectorizer:
def __init__(self, model):
self.model = model
self.size = model.vector_size
def fit(self, X, y=None):
return self
def transform(self, X):
vectors = []
for text in X:
tokens = text.split()
word_vecs = []
for w in tokens:
if w in self.model.wv:
vec = self.model.wv[w]
# normalize each vector
vec = vec / np.linalg.norm(vec)
word_vecs.append(vec)
if word_vecs:
vectors.append(np.mean(word_vecs, axis=0))
else:
vectors.append(np.zeros(self.size))
return np.array(vectors)
# ===============================
# Streamlit App Config
# ===============================
st.set_page_config(page_title="π― Word2Vec Sentiment Classifier")
st.title("π― Live Sentiment Classifier (Word2Vec + Logistic Regression)")
#st.write("This app predicts the sentiment of text using a Word2Vec-based Logistic Regression model trained on your dataset.")
# Stopwords
stop_words = set(stopwords.words('english'))
# ===============================
# Load Trained Pipeline
# ===============================
with open("text_classification_word2vec.pkl", "rb") as f:
pipeline = pickle.load(f)
# ===============================
# User Input
# ===============================
user_input = st.text_area("**Enter a sentence or YouTube comment to analyze:**")
# ===============================
# Prediction
# ===============================
if st.button("Predict Sentiment"):
if user_input.strip():
prediction = pipeline.predict([user_input])[0]
st.markdown(f"## β
Prediction: `{prediction.capitalize()}`")
if prediction.lower() == "positive":
st.success("π Positive Sentiment")
elif prediction.lower() == "negative":
st.error("π Negative Sentiment")
else:
st.info("π Neutral Sentiment")
else:
st.warning("β οΈ Please enter some text to analyze.") |