Download app.py from AmalOmar/MHIS_Student_Program_Predictor: direct link, hf CLI and curl.
- Browser
- Download file 6.75 kB
-
https://huggingface.co/spaces/AmalOmar/MHIS_Student_Program_Predictor/resolve/main/app.py
- Command line
-
hf download hf://spaces/AmalOmar/MHIS_Student_Program_Predictor/app.py
-
curl -L -o app.py https://huggingface.co/spaces/AmalOmar/MHIS_Student_Program_Predictor/resolve/main/app.py
6.75 kB
| import pandas as pd | |
| import numpy as np | |
| import gradio as gr | |
| import matplotlib.pyplot as plt | |
| import seaborn as sns | |
| from io import BytesIO | |
| import base64 | |
| # Sklearn imports | |
| from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler | |
| from sklearn.compose import ColumnTransformer | |
| from sklearn.model_selection import train_test_split | |
| from sklearn.ensemble import RandomForestClassifier | |
| from sklearn.metrics import accuracy_score, confusion_matrix, classification_report | |
| from sklearn.pipeline import Pipeline | |
| # Load dataset | |
| df = pd.read_csv("https://huggingface.co/spaces/AmalOmar/MHIS_Student_Program_Predictor/resolve/dc9a782b5fd3fc491ef297f9d4a9048102335701/80_20_dataset.csv") | |
| # ========== Data Processing ========== | |
| X = df.drop('Program', axis=1) | |
| y = df['Program'] | |
| numeric_cols = X.select_dtypes(include=np.number).columns.tolist() | |
| categorical_cols = X.select_dtypes(include='object').columns.tolist() | |
| preprocessor = ColumnTransformer( | |
| transformers=[ | |
| ('num', StandardScaler(), numeric_cols), | |
| ('cat', OneHotEncoder(handle_unknown='ignore'), categorical_cols) | |
| ] | |
| ) | |
| label_encoder = LabelEncoder() | |
| y_encoded = label_encoder.fit_transform(y) | |
| X_train, X_test, y_train, y_test = train_test_split( | |
| X, y_encoded, test_size=0.2, random_state=42, stratify=y_encoded | |
| ) | |
| model = Pipeline([ | |
| ('preprocessor', preprocessor), | |
| ('classifier', RandomForestClassifier( | |
| class_weight='balanced', | |
| random_state=42 | |
| )) | |
| ]) | |
| model.fit(X_train, y_train) | |
| # ========== Visualization Functions ========== | |
| def create_target_distribution(): | |
| fig, ax = plt.subplots(figsize=(10, 6)) | |
| sns.countplot(data=df, y='Program', order=df['Program'].value_counts().index, ax=ax) | |
| ax.set_title('Program Distribution') | |
| return fig | |
| def create_confusion_matrix(): | |
| y_pred = model.predict(X_test) | |
| cm = confusion_matrix(y_test, y_pred) | |
| fig, ax = plt.subplots(figsize=(8, 6)) | |
| sns.heatmap(cm, annot=True, fmt='d', | |
| xticklabels=label_encoder.classes_, | |
| yticklabels=label_encoder.classes_, | |
| ax=ax) | |
| ax.set_title('Confusion Matrix') | |
| return fig | |
| def create_feature_importance(): | |
| if hasattr(model.named_steps['classifier'], 'feature_importances_'): | |
| importances = model.named_steps['classifier'].feature_importances_ | |
| feature_names = numeric_cols + list(model.named_steps['preprocessor'] | |
| .named_transformers_['cat'] | |
| .get_feature_names_out(categorical_cols)) | |
| feat_imp = pd.DataFrame({'Feature': feature_names, 'Importance': importances}) | |
| feat_imp = feat_imp.sort_values('Importance', ascending=False).head(20) | |
| fig, ax = plt.subplots(figsize=(10, 8)) | |
| sns.barplot(x='Importance', y='Feature', data=feat_imp, ax=ax) | |
| ax.set_title('Top 20 Most Important Features') | |
| return fig | |
| return None | |
| def create_classification_report(): | |
| y_pred = model.predict(X_test) | |
| report = classification_report(y_test, y_pred, target_names=label_encoder.classes_, output_dict=True) | |
| report_df = pd.DataFrame(report).transpose().reset_index() | |
| report_df.columns = ['Class', 'Precision', 'Recall', 'F1-Score', 'Support'] | |
| return report_df | |
| # ========== Gradio Interface ========== | |
| with gr.Blocks(title="MHIS Educational Tools") as demo: | |
| with gr.Tab("Program Predictor"): | |
| # Input components | |
| category_options = {col: sorted(df[col].dropna().unique().tolist()) for col in categorical_cols} | |
| inputs = [] | |
| for feature in X.columns: | |
| if feature in numeric_cols: | |
| inputs.append(gr.Number(label=feature)) | |
| else: | |
| inputs.append(gr.Dropdown(label=feature, choices=category_options[feature])) | |
| # Prediction function | |
| def predict_program(*args): | |
| try: | |
| input_dict = {col: [val] for col, val in zip(X.columns, args)} | |
| input_df = pd.DataFrame(input_dict) | |
| prediction_encoded = model.predict(input_df) | |
| prediction = label_encoder.inverse_transform(prediction_encoded) | |
| return f"Predicted Program: {prediction[0]}" | |
| except Exception as e: | |
| return f"Error: {e}" | |
| gr.Interface( | |
| fn=predict_program, | |
| inputs=inputs, | |
| outputs="text", | |
| title="MHIS Student Program Predictor", | |
| examples=[ | |
| [80083, 3.8, "10", "35", "Perennialism"], | |
| [20229, 4.2, "2", "95", "Progressivism"] | |
| ] | |
| ) | |
| with gr.Tab("Philosophy Comparison"): | |
| comparison_data = [ | |
| ["Aspect", "Perennialism", "Progressivism"], | |
| ["Focus", "Eternal truths, intellectual discipline", "Student experience, real-world relevance"], | |
| ["Curriculum", "Fixed, classic texts (Great Books)", "Flexible, interdisciplinary"], | |
| ["Teaching Method", "Teacher-centered, lecture-based", "Student-centered, hands-on learning"], | |
| ["Goal", "Cultivate rational, moral thinkers", "Develop problem-solvers for democracy"], | |
| ["Key Thinkers", "Robert Hutchins, Mortimer Adler", "John Dewey, William Kilpatrick"] | |
| ] | |
| gr.Markdown("## 🎓 Perennialism vs Progressivism in Education") | |
| gr.DataFrame( | |
| value=comparison_data, | |
| headers=["Aspect", "Perennialism", "Progressivism"], | |
| interactive=False | |
| ) | |
| with gr.Tab("Model Analysis"): | |
| gr.Markdown("## 🔍 Model Evaluation and EDA") | |
| with gr.Row(): | |
| with gr.Column(): | |
| gr.Markdown("### Program Distribution") | |
| target_plot = gr.Plot() | |
| with gr.Column(): | |
| gr.Markdown("### Confusion Matrix") | |
| cm_plot = gr.Plot() | |
| with gr.Row(): | |
| gr.Markdown("### Feature Importance") | |
| fi_plot = gr.Plot() | |
| gr.Markdown("### Classification Report") | |
| report_table = gr.Dataframe() | |
| # Generate plots when tab loads | |
| def load_analysis(): | |
| target_fig = create_target_distribution() | |
| cm_fig = create_confusion_matrix() | |
| fi_fig = create_feature_importance() | |
| report_df = create_classification_report() | |
| return [ | |
| target_fig, | |
| cm_fig, | |
| fi_fig if fi_fig else None, | |
| report_df | |
| ] | |
| demo.load( | |
| load_analysis, | |
| outputs=[target_plot, cm_plot, fi_plot, report_table], | |
| queue=False | |
| ) | |
| demo.launch() |