File size: 3,864 Bytes
9116a7d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5386b06
9116a7d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# import libraries
import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import joblib
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
from sklearn.model_selection import train_test_split

#load model
import joblib

@st.cache_resource  # Caches the model in Streamlit's memory
def load_model():
    return joblib.load("SA_model.pkl")  # Ensure your model is saved and available

model = load_model()



#load dataset
df = pd.read_csv('Tweets.csv', encoding='utf-8')
X = df['text']
y = df['airline_sentiment']
X_train, X_test, y_train, y_test = train_test_split(
    X, y , test_size=0.33, random_state=42
)


#compute sentiment
class_report_data = {
    "Precision": [0.67, 0.51, 0.88],
    "Recall": [0.73, 0.64, 0.79],
    "F1-score": [0.70, 0.57, 0.83]
}

# Properly structured DataFrame
class_report_df = pd.DataFrame(class_report_data, index=["Positive", "Neutral", "Negative"])

#predict text sentiment
def predict_sentiment(text):
    if isinstance(text, str):
        text = [text]  # Ensure input is a list

    prediction = model.predict(text)  # Get numerical prediction

    # Mapping numerical labels to sentiment categories
    sentiment_mapping = {0: "Negative", 1: "Neutral", 2: "Positive"}

    return sentiment_mapping.get(prediction[0], "Unknown")  # Convert number to label



#Model Introduction
st.title('πŸ“Œ Sentiment Analysis Web Application')

st.markdown(
    """
    ## πŸ“– Introduction
    Welcome to the **Sentiment Analysis Web Application**! This tool is designed to analyze the sentiment of text messages 
    using a **Support Vector Machine (SVM) model**. The model has been trained on the **Airline Tweets dataset from Kaggle** 
    and classifies text into three sentiment categories:
    - βœ… **Positive**
    - ❌ **Negative**
    - βš– **Neutral**
    """
)

#Tab Structuring

tab1, tab2, tab3 = st.tabs(['πŸ“Š Dataset Preview', 'πŸ“ˆ Model Performance', 'πŸ” Sentiment Prediction'])

with tab1:
    st.markdown(
        """
        ## πŸ“Š Dataset Preview
        The dataset used for training this model consists of tweets related to airline services. Each tweet is labeled 
        with one of the three sentiment categories (**Positive, Negative, or Neutral**). Below is a sample of the dataset:
        """
    )
    st.write (df)


with tab2:
    st.markdown(
        """
        ## πŸ“ˆ Model Performance
        Below are the key performance metrics of the trained **Support Vector Machine (SVM)** model:
        
        - **Model Accuracy**: The percentage of correctly classified instances.
        - **Classification Report**: Includes precision and recall for each sentiment class.
        - **Confusion Matrix**: A visual representation comparing actual versus predicted classifications.
        """
    )
    
    st.write(f"**πŸ“Œ Model Accuracy:** 75%")
    
    st.markdown("### πŸ“‹ Classification Report")
    st.dataframe(class_report_df)
    
    st.markdown("### πŸ”’ Confusion Matrix")
    
    # Load and display confusion matrix image
    try:
        st.image("cmap.png", caption="Confusion Matrix", use_container_width=True)
    except FileNotFoundError:
        st.warning("⚠️ Confusion matrix image not found. Please check the file path.")




with tab3:
    st.markdown(
        """
        ## πŸ” Sentiment Prediction
        Type a sentence in the text box below, and the model will classify it as **Positive, Neutral, or Negative**.
        """
    )

    user_input = st.text_area("Type your sentence here:", "")

    if st.button("πŸ”Ž Analyze Sentiment"):
        if user_input.strip():
            sentiment_result = predict_sentiment(user_input)
            st.success(f"### 🎯 Prediction: **{sentiment_result}**")
        else:
            st.warning("⚠️ Please enter a valid text input.")