File size: 6,750 Bytes
5150fd7 2f1c4a9 c9d0f4f 9a19ec8 c9d0f4f 9a19ec8 c9d0f4f 9a19ec8 b3c26d2 76f96aa 9a19ec8 c9d0f4f 9a19ec8 b3c26d2 9a19ec8 3714b45 788a359 3714b45 c9d0f4f 3714b45 c9d0f4f 3714b45 c9d0f4f 3714b45 c9d0f4f 3714b45 9b7e6d8 c9d0f4f 0c89483 c9d0f4f 0c89483 9b7e6d8 0c89483 c9d0f4f 0c89483 c9d0f4f 0c89483 c9d0f4f 0c89483 c9d0f4f 3714b45 c9d0f4f 3714b45 c9d0f4f 3714b45 c9d0f4f 3714b45 c9d0f4f 3714b45 c9d0f4f 3714b45 c9d0f4f 3714b45 c9d0f4f 3714b45 0c89483 | 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 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 | 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() |