File size: 2,879 Bytes
3628643
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66b72cc
3628643
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a173017
 
3628643
 
 
 
 
 
 
ebb4a66
91b3e33
ebb4a66
5d3fc12
697fd9f
3628643
2d9aa1a
fd05e8f
a173017
3628643
c5d00cc
ebb4a66
3628643
 
 
 
015eec3
3628643
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import pandas as pd
import numpy as np
import gradio as gr

from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_absolute_error, root_mean_squared_error

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Input
from tensorflow.keras.callbacks import EarlyStopping
import keras_tuner as kt

# Load dataset
df = pd.read_csv("Student_Performance.csv")

# Features
num_feature = ['Hours Studied', 'Previous Scores', 'Sleep Hours', 'Sample Question Papers Practiced']
cat_feature = ['Extracurricular Activities']

# Preprocessing
preprocess = ColumnTransformer(transformers=[
    ('num', StandardScaler(), num_feature),
    ('cat', OneHotEncoder(drop='first'), cat_feature)
])

x = df.drop(columns=['Performance Index'])
y = df['Performance Index']
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.4, random_state=42)

x_train_scaled = preprocess.fit_transform(x_train)
x_test_scaled = preprocess.transform(x_test)

# Build model
def build_model(hp):
    model = Sequential([
        Input(shape=(x_test_scaled.shape[1],)),
        Dense(units=hp.Int('u1', 32, 256, step=32), activation='relu'),
        Dense(units=hp.Int('u2', 16, 128, step=16), activation='relu'),
        Dense(units=hp.Int('u3', 8, 64, step=8), activation='relu'),
        Dense(1)
    ])
    model.compile(optimizer="adam", loss="mse", metrics=["mae"])
    return model

# Hyperparameter tuning
tuner = kt.RandomSearch(build_model, objective="val_loss", max_trials=5, overwrite=True)
early_stop = EarlyStopping(monitor="val_loss", patience=20, restore_best_weights=True)

tuner.search(x_train_scaled, y_train, epochs=50, batch_size=32, validation_split=0.2,
             callbacks=[early_stop], verbose=0)

best_model = tuner.get_best_models(1)[0]

# Define prediction function for Gradio
def predict_performance(hours, prev_score, activity, sleep, papers):
    cols = x.columns
    values = [hours, prev_score, activity, sleep, papers]
    user_input = pd.DataFrame([dict(zip(cols, values))])
    X_user = preprocess.transform(user_input)
    pred = best_model.predict(X_user).item()
    if pred>=100:
        pred = 100        
    return f"📊 Result: {pred:.2f}"



# Gradio UI
inputs = [
    gr.Number(label="Hours Studied"),
    gr.Number(label="Previous Scores"),
    gr.Radio(choices=["Yes", "No"], label="Extracurricular Activities"),
    gr.Number(label="Sleep Hours"),
    gr.Number(label="Sample Question Papers Practiced"),
]

demo = gr.Interface(
    fn=predict_performance,
    inputs=inputs,
    outputs="text",
    title="🎓 Student Performance Prediction",
    description="Enter student study habits and get predicted performance index."
)

if __name__ == "__main__":
    demo.launch()