Markndrei commited on
Commit
9116a7d
Β·
verified Β·
1 Parent(s): 49ce054

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +127 -128
app.py CHANGED
@@ -1,128 +1,127 @@
1
- # import libraries
2
- import streamlit as st
3
- import pandas as pd
4
- import matplotlib.pyplot as plt
5
- import seaborn as sns
6
- import joblib
7
- from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
8
- from sklearn.model_selection import train_test_split
9
-
10
- #load model
11
- import joblib
12
-
13
- @st.cache_resource # Caches the model in Streamlit's memory
14
- def load_model():
15
- return joblib.load("SA_model.pkl") # Ensure your model is saved and available
16
-
17
- model = load_model()
18
-
19
-
20
-
21
- #load dataset
22
- df = pd.read_csv('Tweets.csv', encoding='utf-8')
23
- X = df['text']
24
- y = df['airline_sentiment']
25
- X_train, X_test, y_train, y_test = train_test_split(
26
- X, y , test_size=0.33, random_state=42
27
- )
28
-
29
-
30
- #compute sentiment
31
- class_report_data = {
32
- "Precision": [0.67, 0.51, 0.88],
33
- "Recall": [0.73, 0.64, 0.79],
34
- "F1-score": [0.70, 0.57, 0.83]
35
- }
36
-
37
- # Properly structured DataFrame
38
- class_report_df = pd.DataFrame(class_report_data, index=["Positive", "Neutral", "Negative"])
39
-
40
- #predict text sentiment
41
- def predict_sentiment(text):
42
- if isinstance(text, str):
43
- text = [text] # Ensure input is a list
44
-
45
- prediction = model.predict(text) # Get numerical prediction
46
-
47
- # Mapping numerical labels to sentiment categories
48
- sentiment_mapping = {0: "Negative", 1: "Neutral", 2: "Positive"}
49
-
50
- return sentiment_mapping.get(prediction[0], "Unknown") # Convert number to label
51
-
52
-
53
-
54
- #Model Introduction
55
- st.title('πŸ“Œ Sentiment Analysis Web Application')
56
-
57
- st.markdown(
58
- """
59
- ## πŸ“– Introduction
60
- Welcome to the **Sentiment Analysis Web Application**! This tool is designed to analyze the sentiment of text messages
61
- using a **Support Vector Machine (SVM) model**. The model has been trained on the **Airline Tweets dataset from Kaggle**
62
- and classifies text into three sentiment categories:
63
- - βœ… **Positive**
64
- - ❌ **Negative**
65
- - βš– **Neutral**
66
- """
67
- )
68
-
69
- #Tab Structuring
70
-
71
- tab1, tab2, tab3 = st.tabs(['πŸ“Š Dataset Preview', 'πŸ“ˆ Model Performance', 'πŸ” Sentiment Prediction'])
72
-
73
- with tab1:
74
- st.markdown(
75
- """
76
- ## πŸ“Š Dataset Preview
77
- The dataset used for training this model consists of tweets related to airline services. Each tweet is labeled
78
- with one of the three sentiment categories (**Positive, Negative, or Neutral**). Below is a sample of the dataset:
79
- """
80
- )
81
- st.write (df)
82
-
83
-
84
- with tab2:
85
- st.markdown(
86
- """
87
- ## πŸ“ˆ Model Performance
88
- Below are the key performance metrics of the trained **Support Vector Machine (SVM)** model:
89
-
90
- - **Model Accuracy**: The percentage of correctly classified instances.
91
- - **Classification Report**: Includes precision and recall for each sentiment class.
92
- - **Confusion Matrix**: A visual representation comparing actual versus predicted classifications.
93
- """
94
- )
95
-
96
- st.write(f"**πŸ“Œ Model Accuracy:** 75%")
97
-
98
- st.markdown("### πŸ“‹ Classification Report")
99
- st.dataframe(class_report_df)
100
-
101
- st.markdown("### πŸ”’ Confusion Matrix")
102
-
103
- # Load and display confusion matrix image
104
- cm_image_path = "cmap.png"
105
- try:
106
- st.image(cm_image_path, caption="Confusion Matrix", use_container_width=True)
107
- except FileNotFoundError:
108
- st.warning("⚠️ Confusion matrix image not found. Please check the file path.")
109
-
110
-
111
-
112
-
113
- with tab3:
114
- st.markdown(
115
- """
116
- ## πŸ” Sentiment Prediction
117
- Type a sentence in the text box below, and the model will classify it as **Positive, Neutral, or Negative**.
118
- """
119
- )
120
-
121
- user_input = st.text_area("Type your sentence here:", "")
122
-
123
- if st.button("πŸ”Ž Analyze Sentiment"):
124
- if user_input.strip():
125
- sentiment_result = predict_sentiment(user_input)
126
- st.success(f"### 🎯 Prediction: **{sentiment_result}**")
127
- else:
128
- st.warning("⚠️ Please enter a valid text input.")
 
1
+ # import libraries
2
+ import streamlit as st
3
+ import pandas as pd
4
+ import matplotlib.pyplot as plt
5
+ import seaborn as sns
6
+ import joblib
7
+ from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
8
+ from sklearn.model_selection import train_test_split
9
+
10
+ #load model
11
+ import joblib
12
+
13
+ @st.cache_resource # Caches the model in Streamlit's memory
14
+ def load_model():
15
+ return joblib.load("SA_model.pkl") # Ensure your model is saved and available
16
+
17
+ model = load_model()
18
+
19
+
20
+
21
+ #load dataset
22
+ df = pd.read_csv('Tweets.csv', encoding='utf-8')
23
+ X = df['text']
24
+ y = df['airline_sentiment']
25
+ X_train, X_test, y_train, y_test = train_test_split(
26
+ X, y , test_size=0.33, random_state=42
27
+ )
28
+
29
+
30
+ #compute sentiment
31
+ class_report_data = {
32
+ "Precision": [0.67, 0.51, 0.88],
33
+ "Recall": [0.73, 0.64, 0.79],
34
+ "F1-score": [0.70, 0.57, 0.83]
35
+ }
36
+
37
+ # Properly structured DataFrame
38
+ class_report_df = pd.DataFrame(class_report_data, index=["Positive", "Neutral", "Negative"])
39
+
40
+ #predict text sentiment
41
+ def predict_sentiment(text):
42
+ if isinstance(text, str):
43
+ text = [text] # Ensure input is a list
44
+
45
+ prediction = model.predict(text) # Get numerical prediction
46
+
47
+ # Mapping numerical labels to sentiment categories
48
+ sentiment_mapping = {0: "Negative", 1: "Neutral", 2: "Positive"}
49
+
50
+ return sentiment_mapping.get(prediction[0], "Unknown") # Convert number to label
51
+
52
+
53
+
54
+ #Model Introduction
55
+ st.title('πŸ“Œ Sentiment Analysis Web Application')
56
+
57
+ st.markdown(
58
+ """
59
+ ## πŸ“– Introduction
60
+ Welcome to the **Sentiment Analysis Web Application**! This tool is designed to analyze the sentiment of text messages
61
+ using a **Support Vector Machine (SVM) model**. The model has been trained on the **Airline Tweets dataset from Kaggle**
62
+ and classifies text into three sentiment categories:
63
+ - βœ… **Positive**
64
+ - ❌ **Negative**
65
+ - βš– **Neutral**
66
+ """
67
+ )
68
+
69
+ #Tab Structuring
70
+
71
+ tab1, tab2, tab3 = st.tabs(['πŸ“Š Dataset Preview', 'πŸ“ˆ Model Performance', 'πŸ” Sentiment Prediction'])
72
+
73
+ with tab1:
74
+ st.markdown(
75
+ """
76
+ ## πŸ“Š Dataset Preview
77
+ The dataset used for training this model consists of tweets related to airline services. Each tweet is labeled
78
+ with one of the three sentiment categories (**Positive, Negative, or Neutral**). Below is a sample of the dataset:
79
+ """
80
+ )
81
+ st.write (df)
82
+
83
+
84
+ with tab2:
85
+ st.markdown(
86
+ """
87
+ ## πŸ“ˆ Model Performance
88
+ Below are the key performance metrics of the trained **Support Vector Machine (SVM)** model:
89
+
90
+ - **Model Accuracy**: The percentage of correctly classified instances.
91
+ - **Classification Report**: Includes precision and recall for each sentiment class.
92
+ - **Confusion Matrix**: A visual representation comparing actual versus predicted classifications.
93
+ """
94
+ )
95
+
96
+ st.write(f"**πŸ“Œ Model Accuracy:** 75%")
97
+
98
+ st.markdown("### πŸ“‹ Classification Report")
99
+ st.dataframe(class_report_df)
100
+
101
+ st.markdown("### πŸ”’ Confusion Matrix")
102
+
103
+ # Load and display confusion matrix image
104
+ try:
105
+ st.image("/cmap.png", caption="Confusion Matrix", use_container_width=True)
106
+ except FileNotFoundError:
107
+ st.warning("⚠️ Confusion matrix image not found. Please check the file path.")
108
+
109
+
110
+
111
+
112
+ with tab3:
113
+ st.markdown(
114
+ """
115
+ ## πŸ” Sentiment Prediction
116
+ Type a sentence in the text box below, and the model will classify it as **Positive, Neutral, or Negative**.
117
+ """
118
+ )
119
+
120
+ user_input = st.text_area("Type your sentence here:", "")
121
+
122
+ if st.button("πŸ”Ž Analyze Sentiment"):
123
+ if user_input.strip():
124
+ sentiment_result = predict_sentiment(user_input)
125
+ st.success(f"### 🎯 Prediction: **{sentiment_result}**")
126
+ else:
127
+ st.warning("⚠️ Please enter a valid text input.")