Munazz commited on
Commit
9ead773
·
verified ·
1 Parent(s): 2110e49

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -32
app.py CHANGED
@@ -1,18 +1,30 @@
1
  import gradio as gr
2
  import joblib
 
 
 
 
 
 
 
 
3
 
4
- # Load models (Ensure the correct paths to where your models are stored)
5
  logreg_model = joblib.load('best_lr_model.pkl')
6
  knn_model = joblib.load('best_knn_model.pkl')
7
  svc_model = joblib.load('best_svc_model.pkl')
8
  rf_model = joblib.load('best_rf_model.pkl')
9
 
 
 
 
10
  # Prediction function
11
  def predict_sentiment(review_text, model_name):
12
- # Reshape input to match expected 2D array format (single sample, single feature)
13
- review_text_reshaped = [review_text] # This ensures the input is in a 2D array (1 sample, N features)
14
-
15
- # Select the appropriate model
 
16
  if model_name == "Logistic Regression":
17
  model = logreg_model
18
  elif model_name == "K-Nearest Neighbors":
@@ -21,48 +33,40 @@ def predict_sentiment(review_text, model_name):
21
  model = svc_model
22
  elif model_name == "Random Forest":
23
  model = rf_model
24
- else:
25
- return "Model not found", {}
26
-
27
- # Assuming the models support `predict_proba` for probabilities
28
- try:
29
- prob = model.predict_proba(review_text_reshaped) # Adjust according to your preprocessing steps
30
- positive_prob = prob[0][1]
31
- negative_prob = prob[0][0]
32
-
33
- # Predict the sentiment class (based on the highest probability)
34
- predicted_class = "Positive Feedback" if positive_prob > negative_prob else "Negative Feedback"
35
-
36
- return predicted_class, {"Positive Comment": f"{positive_prob * 100:.2f}%", "Negative Comment": f"{negative_prob * 100:.2f}%"}
37
-
38
- except Exception as e:
39
- return f"Error: {e}", {}
40
 
41
- # Gradio interface setup
42
  def create_interface():
 
43
  model_dropdown = gr.Dropdown(
44
  choices=["Logistic Regression", "K-Nearest Neighbors", "Support Vector Machine", "Random Forest"],
45
  label="Select Model"
46
  )
47
 
48
- # Textbox for review input
49
- review_input = gr.Textbox(lines=2, placeholder="Enter your review comment here...")
 
 
50
 
51
- # Gradio output for predicted sentiment and probabilities
52
- sentiment_output = gr.Textbox(label="Predicted Sentiment Class")
53
- prob_output = gr.JSON(label="Predicted Probability")
54
 
55
- # Create Gradio interface
56
  interface = gr.Interface(
57
  fn=predict_sentiment,
58
  inputs=[review_input, model_dropdown],
59
- outputs=[sentiment_output, prob_output],
60
  live=True, # Optionally update in real-time
61
  description="Sentiment Analysis Model",
62
- allow_flagging="never" # Disable flagging option if you prefer
63
  )
64
 
65
  return interface
66
 
67
- # Launch the interface
68
- create_interface().launch(share=True) # Add share=True to create a public link
 
 
1
  import gradio as gr
2
  import joblib
3
+ import numpy as np
4
+ from sklearn.feature_extraction.text import CountVectorizer
5
+ from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, roc_auc_score
6
+ from sklearn.model_selection import train_test_split
7
+ from sklearn.svm import SVC
8
+ from sklearn.neighbors import KNeighborsClassifier
9
+ from sklearn.linear_model import LogisticRegression
10
+ from sklearn.ensemble import RandomForestClassifier
11
 
12
+ # Load your pre-trained models (make sure the models are uploaded to the Hugging Face Space)
13
  logreg_model = joblib.load('best_lr_model.pkl')
14
  knn_model = joblib.load('best_knn_model.pkl')
15
  svc_model = joblib.load('best_svc_model.pkl')
16
  rf_model = joblib.load('best_rf_model.pkl')
17
 
18
+ # Load the vectorizer (assuming the same vectorizer used during training)
19
+ vectorizer = joblib.load('vectorizer.pkl') # You must upload this file as well
20
+
21
  # Prediction function
22
  def predict_sentiment(review_text, model_name):
23
+ # Preprocess the review text with the same vectorizer
24
+ review_features = vectorizer.transform([review_text]) # Transform review to features
25
+ review_features = review_features.toarray() # Ensure it's in array form
26
+
27
+ # Select the model based on the input
28
  if model_name == "Logistic Regression":
29
  model = logreg_model
30
  elif model_name == "K-Nearest Neighbors":
 
33
  model = svc_model
34
  elif model_name == "Random Forest":
35
  model = rf_model
36
+
37
+ # Use the model to predict sentiment probabilities
38
+ prob = model.predict_proba(review_features) # Use predict_proba to get probabilities
39
+
40
+ # Return positive and negative sentiment probabilities
41
+ return {"Positive Comment": prob[0][1], "Negative Comment": prob[0][0]}
 
 
 
 
 
 
 
 
 
 
42
 
43
+ # Gradio Interface setup
44
  def create_interface():
45
+ # Create a dropdown for model selection
46
  model_dropdown = gr.Dropdown(
47
  choices=["Logistic Regression", "K-Nearest Neighbors", "Support Vector Machine", "Random Forest"],
48
  label="Select Model"
49
  )
50
 
51
+ # Create a textbox for the review input
52
+ review_input = gr.Textbox(
53
+ lines=2, placeholder="Enter your review comment here...", label="Review Comment"
54
+ )
55
 
56
+ # Create a JSON output to display predicted sentiment and probabilities
57
+ output = gr.JSON()
 
58
 
59
+ # Create the Gradio interface
60
  interface = gr.Interface(
61
  fn=predict_sentiment,
62
  inputs=[review_input, model_dropdown],
63
+ outputs=output,
64
  live=True, # Optionally update in real-time
65
  description="Sentiment Analysis Model",
 
66
  )
67
 
68
  return interface
69
 
70
+ # Launch the Gradio interface
71
+ if __name__ == "__main__":
72
+ create_interface().launch()