File size: 4,781 Bytes
50dad37
 
 
 
 
 
 
 
c0e659f
80096a1
 
 
 
 
 
 
 
 
50dad37
 
c0e659f
50dad37
 
80096a1
 
50dad37
80096a1
6a9362d
 
80096a1
50dad37
 
c0e659f
50dad37
 
6a9362d
50dad37
 
c0e659f
50dad37
80096a1
50dad37
6a9362d
80096a1
 
 
 
 
6a9362d
 
80096a1
 
 
 
 
 
 
 
 
 
50dad37
 
 
80096a1
 
6a9362d
80096a1
 
 
 
 
 
 
 
 
c0e659f
80096a1
 
 
 
6a9362d
80096a1
 
6a9362d
80096a1
 
c0e659f
80096a1
 
 
50dad37
80096a1
6a9362d
 
 
 
 
 
 
 
 
80096a1
6a9362d
 
 
 
 
 
 
 
 
80096a1
c0e659f
80096a1
 
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
import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, classification_report


def load_data():
    df = pd.read_csv(r"C:\Users\pavilion\Desktop\INNOMATICS_PROJECTS(SL)\Student_Depresion_Prediction(Machine_Learning)\student_depression_dataset.csv")
    
    df.drop(columns=['id', 'City', 'Work Pressure', 'Job Satisfaction'], inplace=True, errors='ignore')

    if 'Profession' in df.columns:
        df = df[df['Profession'].str.lower() == 'student']
        df.drop(columns=['Profession'], inplace=True, errors='ignore')

    return df


def preprocess_data(df):
    label_encoders = {}
    categorical_cols = df.select_dtypes(include=['object']).columns.tolist()
    
    for col in categorical_cols:
        le = LabelEncoder()
        df[col] = le.fit_transform(df[col])  
        label_encoders[col] = le  

    return df, label_encoders


def train_model(X_train, y_train):
    model = RandomForestClassifier(n_estimators=100, random_state=42)
    model.fit(X_train, y_train)  
    return model


def main():
    st.set_page_config(page_title="Student Depression Prediction", layout="wide")
    
    st.markdown("<h1 style='text-align: center;'>๐ŸŽ“ Student Depression Prediction</h1>", unsafe_allow_html=True)
    st.write("This app predicts whether a student is likely to experience depression based on various factors.")

    df = load_data()
    df, label_encoders = preprocess_data(df)

    X = df.drop(columns=['Depression'])  
    y = df['Depression']  

    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)
    model = train_model(X_train, y_train)
    y_pred = model.predict(X_test)

    accuracy = accuracy_score(y_test, y_pred)
    classification_rep = classification_report(y_test, y_pred)

    if st.button("๐Ÿš€ Train Model"):
        st.subheader("โœ… Model Trained Successfully!")
        st.write(f"**Accuracy:** {accuracy:.2f}")
        st.text("Classification Report:")
        st.text(classification_rep)

    feature_importances = model.feature_importances_
    feature_importance_df = pd.DataFrame({'Feature': X.columns, 'Importance': feature_importances}).sort_values(by='Importance', ascending=False)

    st.subheader("๐Ÿ” Feature Importance")
    fig, ax = plt.subplots()
    ax.barh(feature_importance_df['Feature'], feature_importance_df['Importance'], color='skyblue')
    ax.set_xlabel("Importance")
    ax.set_ylabel("Feature")
    ax.set_title("Feature Importance in Random Forest")
    st.pyplot(fig)

   
    st.subheader("๐Ÿ“Š Predict Depression Risk")
    input_data = {}
    
    for col in X.columns:
        if col in label_encoders:  
            input_data[col] = st.selectbox(f"Select {col}", label_encoders[col].classes_)
            input_data[col] = label_encoders[col].transform([input_data[col]])[0]
        else:  
            input_data[col] = st.number_input(f"Enter {col}", min_value=int(X[col].min()), max_value=int(X[col].max()), value=int(X[col].mean()))

    
    if st.button("๐Ÿ”ฎ Predict"):
        input_df = pd.DataFrame([input_data])
        prediction = model.predict(input_df)[0]
        
        if prediction == 1:
            st.error("๐Ÿ˜จ **The student is at risk of depression.**")
            st.subheader("๐Ÿ“Œ Recommended Actions:")
            st.markdown("""
            1. **Seek Professional Help** ๐Ÿ‘ฉโ€โš•๏ธ - Consult a therapist or counselor.
            2. **Stay Connected with Loved Ones** ๐Ÿก - Talk to trusted friends or family.
            3. **Engage in Physical Activities** ๐Ÿƒโ€โ™‚๏ธ - Exercise regularly to improve mood.
            4. **Practice Mindfulness & Relaxation** ๐Ÿง˜โ€โ™‚๏ธ - Try meditation, yoga, or deep breathing.
            5. **Manage Academic Stress** ๐Ÿ“š - Break tasks into smaller steps and seek support.
            """)
        else:
            st.success("๐Ÿฅณ **The student is not at risk of depression.**")
            st.subheader("โœ… Wellness Tips:")
            st.markdown("""
            1. **Maintain a Balanced Lifestyle** โš–๏ธ - Manage studies, social life, and self-care.
            2. **Get Enough Sleep** ๐Ÿ˜ด - Ensure 7โ€“9 hours of quality sleep for better mental health.
            3. **Engage in Hobbies & Creative Activities** ๐ŸŽจ - Pursue music, reading, or painting.
            4. **Stay Active & Exercise** ๐Ÿšดโ€โ™‚๏ธ - Physical activity boosts energy and reduces anxiety.
            5. **Support Others & Build Strong Friendships** ๐Ÿค - Encourage open discussions and check on friends.
            """)


if __name__ == '__main__':
    main()