Update app.py
Browse files
app.py
CHANGED
|
@@ -6,63 +6,112 @@ from sklearn.preprocessing import LabelEncoder
|
|
| 6 |
from sklearn.ensemble import RandomForestClassifier
|
| 7 |
from sklearn.metrics import accuracy_score, classification_report
|
| 8 |
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
df
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
return df
|
| 13 |
|
|
|
|
| 14 |
def preprocess_data(df):
|
| 15 |
label_encoders = {}
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
|
|
|
| 19 |
for col in categorical_cols:
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
return df, label_encoders
|
| 25 |
|
|
|
|
| 26 |
def train_model(X_train, y_train):
|
| 27 |
model = RandomForestClassifier(n_estimators=100, random_state=42)
|
| 28 |
-
model.fit(X_train, y_train)
|
| 29 |
return model
|
| 30 |
|
|
|
|
| 31 |
def main():
|
| 32 |
-
st.
|
| 33 |
-
st.write("Upload your dataset to train and evaluate the Random Forest model.")
|
| 34 |
-
|
| 35 |
-
uploaded_file = st.file_uploader("Upload CSV", type=["csv"])
|
| 36 |
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
st.write(f"**Accuracy:** {accuracy:.2f}")
|
| 59 |
st.text("Classification Report:")
|
| 60 |
st.text(classification_rep)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
|
|
|
|
|
| 6 |
from sklearn.ensemble import RandomForestClassifier
|
| 7 |
from sklearn.metrics import accuracy_score, classification_report
|
| 8 |
|
| 9 |
+
# Step 1: Load dataset
|
| 10 |
+
def load_data():
|
| 11 |
+
df = pd.read_csv(r"C:\Users\pavilion\Desktop\INNOMATICS_PROJECTS(SL)\Student_Depresion_Prediction(Machine_Learning)\student_depression_dataset.csv")
|
| 12 |
+
|
| 13 |
+
# Drop unnecessary columns
|
| 14 |
+
df.drop(columns=['id', 'City', 'Work Pressure', 'Job Satisfaction'], inplace=True, errors='ignore')
|
| 15 |
+
|
| 16 |
+
# Keep only 'Student' in Profession and then drop the column
|
| 17 |
+
if 'Profession' in df.columns:
|
| 18 |
+
df = df[df['Profession'].str.lower() == 'student']
|
| 19 |
+
df.drop(columns=['Profession'], inplace=True, errors='ignore')
|
| 20 |
+
|
| 21 |
return df
|
| 22 |
|
| 23 |
+
# Step 2: Preprocess data (Convert categorical features to numerical)
|
| 24 |
def preprocess_data(df):
|
| 25 |
label_encoders = {}
|
| 26 |
+
|
| 27 |
+
# Identify categorical columns
|
| 28 |
+
categorical_cols = df.select_dtypes(include=['object']).columns.tolist()
|
| 29 |
+
|
| 30 |
for col in categorical_cols:
|
| 31 |
+
le = LabelEncoder()
|
| 32 |
+
df[col] = le.fit_transform(df[col]) # Convert to numeric values
|
| 33 |
+
label_encoders[col] = le # Store the encoder for later use
|
| 34 |
+
|
| 35 |
return df, label_encoders
|
| 36 |
|
| 37 |
+
# Step 3: Train the Random Forest model
|
| 38 |
def train_model(X_train, y_train):
|
| 39 |
model = RandomForestClassifier(n_estimators=100, random_state=42)
|
| 40 |
+
model.fit(X_train, y_train) # Train the model
|
| 41 |
return model
|
| 42 |
|
| 43 |
+
# Step 4: Streamlit App
|
| 44 |
def main():
|
| 45 |
+
st.set_page_config(page_title="Student Depression Prediction", layout="wide")
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
+
st.markdown("<h1 style='text-align: center;'>๐ Student Depression Prediction App</h1>", unsafe_allow_html=True)
|
| 48 |
+
st.write("This app predicts whether a student is likely to experience depression based on various factors.")
|
| 49 |
+
|
| 50 |
+
# Load dataset
|
| 51 |
+
df = load_data()
|
| 52 |
+
|
| 53 |
+
# Preprocess data
|
| 54 |
+
df, label_encoders = preprocess_data(df)
|
| 55 |
+
|
| 56 |
+
# Split features (X) and target variable (y)
|
| 57 |
+
X = df.drop(columns=['Depression']) # Features
|
| 58 |
+
y = df['Depression'] # Target (Depression)
|
| 59 |
+
|
| 60 |
+
# Train/Test split
|
| 61 |
+
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)
|
| 62 |
+
|
| 63 |
+
# Train model
|
| 64 |
+
model = train_model(X_train, y_train)
|
| 65 |
+
y_pred = model.predict(X_test)
|
| 66 |
+
|
| 67 |
+
# Model evaluation
|
| 68 |
+
accuracy = accuracy_score(y_test, y_pred)
|
| 69 |
+
classification_rep = classification_report(y_test, y_pred)
|
| 70 |
+
|
| 71 |
+
# Train Model Button
|
| 72 |
+
if st.button("๐ Train Model"):
|
| 73 |
+
st.subheader("โ
Model Trained Successfully!")
|
| 74 |
st.write(f"**Accuracy:** {accuracy:.2f}")
|
| 75 |
st.text("Classification Report:")
|
| 76 |
st.text(classification_rep)
|
| 77 |
+
|
| 78 |
+
# Feature Importance
|
| 79 |
+
feature_importances = model.feature_importances_
|
| 80 |
+
feature_importance_df = pd.DataFrame({
|
| 81 |
+
'Feature': X.columns,
|
| 82 |
+
'Importance': feature_importances
|
| 83 |
+
}).sort_values(by='Importance', ascending=False)
|
| 84 |
+
|
| 85 |
+
st.subheader("๐ Feature Importance")
|
| 86 |
+
fig, ax = plt.subplots()
|
| 87 |
+
ax.barh(feature_importance_df['Feature'], feature_importance_df['Importance'], color='skyblue')
|
| 88 |
+
ax.set_xlabel("Importance")
|
| 89 |
+
ax.set_ylabel("Feature")
|
| 90 |
+
ax.set_title("Feature Importance in Random Forest")
|
| 91 |
+
st.pyplot(fig)
|
| 92 |
+
|
| 93 |
+
# User Input for Prediction
|
| 94 |
+
st.subheader("๐ Predict Depression Risk")
|
| 95 |
+
|
| 96 |
+
input_data = {}
|
| 97 |
+
|
| 98 |
+
for col in X.columns:
|
| 99 |
+
if col in label_encoders: # Categorical columns
|
| 100 |
+
input_data[col] = st.selectbox(f"Select {col}", label_encoders[col].classes_)
|
| 101 |
+
input_data[col] = label_encoders[col].transform([input_data[col]])[0]
|
| 102 |
+
else: # Numeric columns
|
| 103 |
+
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()))
|
| 104 |
+
|
| 105 |
+
# Prediction Button
|
| 106 |
+
if st.button("๐ฎ Predict"):
|
| 107 |
+
input_df = pd.DataFrame([input_data])
|
| 108 |
+
prediction = model.predict(input_df)[0]
|
| 109 |
|
| 110 |
+
if prediction == 1:
|
| 111 |
+
st.success("๐จ The student is **at risk of depression**.")
|
| 112 |
+
else:
|
| 113 |
+
st.info("๐ฅณ The student is **not at risk of depression**.")
|
| 114 |
+
|
| 115 |
+
# Run the Streamlit app
|
| 116 |
+
if __name__ == '__main__':
|
| 117 |
+
main()
|