Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,18 +1,39 @@
|
|
| 1 |
|
| 2 |
import gradio as gr
|
| 3 |
|
| 4 |
-
|
| 5 |
import numpy as np
|
| 6 |
import pandas as pd
|
| 7 |
-
|
| 8 |
from sklearn.model_selection import train_test_split
|
| 9 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
from sklearn.metrics import classification_report,confusion_matrix
|
| 11 |
import re
|
| 12 |
import nltk
|
| 13 |
from nltk.corpus import stopwords
|
| 14 |
nltk.download('stopwords')
|
| 15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
file_path = "https://raw.githubusercontent.com/alexvatti/full-stack-data-science/main/NLP-Exercises/Movie-Review/IMDB%20Dataset.csv"
|
| 17 |
movies_df=pd.read_csv(file_path)
|
| 18 |
|
|
@@ -37,46 +58,46 @@ movies_df['review'] = movies_df['review'].apply(remove_stop_wrods)
|
|
| 37 |
movies_df["Category"]=movies_df["sentiment"].apply(lambda x: 1 if x=='positive' else 0)
|
| 38 |
|
| 39 |
X_train,X_test,y_train,y_test=train_test_split(movies_df['review'],movies_df["Category"],test_size=0.2,random_state=42)
|
| 40 |
-
#
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
|
| 45 |
-
#
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
-
#
|
| 49 |
-
|
| 50 |
|
| 51 |
-
#
|
| 52 |
-
|
| 53 |
-
model.save_model("sentiment_model")
|
| 54 |
|
| 55 |
-
#
|
| 56 |
-
|
| 57 |
-
|
| 58 |
|
| 59 |
-
#
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
predictions, raw_outputs = loaded_model.predict(review)
|
| 64 |
-
print("Predictions:", predictions) # Outputs the label (e.g., 1 for positive, 0 for negative)
|
| 65 |
-
print("Raw Outputs:", raw_outputs) # Outputs the raw model scores
|
| 66 |
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
|
| 72 |
-
|
| 73 |
-
|
| 74 |
|
| 75 |
def fn(test_review):
|
| 76 |
review=remove_tags(test_review)
|
| 77 |
review=remove_stop_wrods(review)
|
| 78 |
-
|
| 79 |
-
|
|
|
|
|
|
|
| 80 |
|
| 81 |
description = "Give a review of a movie that you like(or hate, sarcasm intended XD) and the model will let you know just how much your review truely reflects your emotions. "
|
| 82 |
input_text = gr.Textbox(label="Enter Text")
|
|
|
|
| 1 |
|
| 2 |
import gradio as gr
|
| 3 |
|
|
|
|
| 4 |
import numpy as np
|
| 5 |
import pandas as pd
|
|
|
|
| 6 |
from sklearn.model_selection import train_test_split
|
| 7 |
+
|
| 8 |
+
import tensorflow as tf
|
| 9 |
+
from transformers import BertTokenizer, TFBertModel
|
| 10 |
+
from tensorflow.keras.layers import Dense
|
| 11 |
+
from tensorflow.keras.models import Sequential
|
| 12 |
+
from tensorflow.keras.models import load_model
|
| 13 |
+
|
| 14 |
from sklearn.metrics import classification_report,confusion_matrix
|
| 15 |
import re
|
| 16 |
import nltk
|
| 17 |
from nltk.corpus import stopwords
|
| 18 |
nltk.download('stopwords')
|
| 19 |
|
| 20 |
+
# Load the tokenizer and model
|
| 21 |
+
tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
|
| 22 |
+
bert_model = TFBertModel.from_pretrained("bert-base-uncased")
|
| 23 |
+
|
| 24 |
+
# Define function to create embeddings
|
| 25 |
+
def bert_embeddings(texts, max_length=128):
|
| 26 |
+
inputs = tokenizer(
|
| 27 |
+
texts.tolist(),
|
| 28 |
+
return_tensors="tf",
|
| 29 |
+
padding=True,
|
| 30 |
+
truncation=True,
|
| 31 |
+
max_length=max_length
|
| 32 |
+
)
|
| 33 |
+
outputs = bert_model(inputs['input_ids'], attention_mask=inputs['attention_mask'])
|
| 34 |
+
cls_embeddings = outputs.last_hidden_state[:, 0, :] # CLS token's embedding
|
| 35 |
+
return cls_embeddings
|
| 36 |
+
|
| 37 |
file_path = "https://raw.githubusercontent.com/alexvatti/full-stack-data-science/main/NLP-Exercises/Movie-Review/IMDB%20Dataset.csv"
|
| 38 |
movies_df=pd.read_csv(file_path)
|
| 39 |
|
|
|
|
| 58 |
movies_df["Category"]=movies_df["sentiment"].apply(lambda x: 1 if x=='positive' else 0)
|
| 59 |
|
| 60 |
X_train,X_test,y_train,y_test=train_test_split(movies_df['review'],movies_df["Category"],test_size=0.2,random_state=42)
|
| 61 |
+
# Convert emails to BERT embeddings
|
| 62 |
+
X_train_embeddings = bert_embeddings(X_train)
|
| 63 |
+
X_test_embeddings = bert_embeddings(X_test)
|
|
|
|
| 64 |
|
| 65 |
+
# Define a simple classifier model
|
| 66 |
+
classifier = Sequential([
|
| 67 |
+
Dense(128, activation='relu', input_shape=(768,)),
|
| 68 |
+
Dense(1, activation='sigmoid') # Sigmoid for binary classification
|
| 69 |
+
])
|
| 70 |
|
| 71 |
+
# Compile the classifier
|
| 72 |
+
classifier.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
|
| 73 |
|
| 74 |
+
# Train the classifier
|
| 75 |
+
classifier.fit(X_train_embeddings, y_train, epochs=5, batch_size=32, validation_split=0.1)
|
|
|
|
| 76 |
|
| 77 |
+
# Evaluate on test set
|
| 78 |
+
test_loss, test_accuracy = classifier.evaluate(X_test_embeddings, y_test)
|
| 79 |
+
print(f"Test Accuracy: {test_accuracy}")
|
| 80 |
|
| 81 |
+
# Predictions and confusion matrix
|
| 82 |
+
y_pred = (classifier.predict(X_test_embeddings) > 0.5).astype("int32")
|
| 83 |
+
conf_matrix = confusion_matrix(y_test, y_pred)
|
| 84 |
+
class_report = classification_report(y_test, y_pred)
|
|
|
|
|
|
|
|
|
|
| 85 |
|
| 86 |
+
print("Confusion Matrix:")
|
| 87 |
+
print(conf_matrix)
|
| 88 |
+
print("\nClassification Report:")
|
| 89 |
+
print(class_report)
|
| 90 |
|
| 91 |
+
# Save the trained model to a file
|
| 92 |
+
classifier.save("movie_sentiment_model.h5")
|
| 93 |
|
| 94 |
def fn(test_review):
|
| 95 |
review=remove_tags(test_review)
|
| 96 |
review=remove_stop_wrods(review)
|
| 97 |
+
cls_embeddings = bert_embeddings([review])
|
| 98 |
+
loaded_model = load_model("movie_sentiment_model.h5")
|
| 99 |
+
prediction = loaded_model.predict(cls_embeddings)
|
| 100 |
+
return "Positive" if prediction[0] > 0.5 else "Negative"
|
| 101 |
|
| 102 |
description = "Give a review of a movie that you like(or hate, sarcasm intended XD) and the model will let you know just how much your review truely reflects your emotions. "
|
| 103 |
input_text = gr.Textbox(label="Enter Text")
|