File size: 2,239 Bytes
ac44a3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# train.py
import pandas as pd, numpy as np, pickle
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn.multioutput import MultiOutputRegressor
from sklearn.metrics import mean_absolute_error

CSV_PATH = "student_allinone_300_padded.csv"  # change path if needed
FEATURES = ["Attendance","StudyHours","ParentalSupport","SleepHours",
            "ReadingHours","BehaviorScore","PretestScore",
            "HomeworkCompletion","Participation"]
TARGETS = ["AssignmentAvg","TestScore"]

def main():
    df = pd.read_csv(CSV_PATH).copy()

    # === Highly recommended: make targets depend on inputs (if your CSV targets were random) ===
    rng = np.random.default_rng(42)
    if ("AssignmentAvg" in df.columns) and ("TestScore" in df.columns):
        # Always recompute to ensure consistency
        df["AssignmentAvg"] = (
            df["PretestScore"] * 0.5
            + df["StudyHours"] * 3
            + df["HomeworkCompletion"] * 0.20
            + df["Participation"] * 2
            + rng.integers(-5, 6, size=len(df))
        ).clip(0, 100).round(2)

        df["TestScore"] = (
            df["PretestScore"] * 0.6
            + df["Attendance"] * 0.20
            + df["ParentalSupport"] * 3
            + df["SleepHours"] * 2
            + df["ReadingHours"] * 2
            + df["BehaviorScore"] * 2
            + rng.integers(-5, 6, size=len(df))
        ).clip(0, 100).round(2)

    X = df[FEATURES]
    y = df[TARGETS]

    Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.2, random_state=42)
    model = MultiOutputRegressor(RandomForestRegressor(n_estimators=200, random_state=42)).fit(Xtr, ytr)
    mae = mean_absolute_error(yte, model.predict(Xte))
    print("MAE:", round(mae, 3))

    # Save feature bounds so app can clip
    feature_mins = X.min().to_dict()
    feature_maxs = X.max().to_dict()

    with open("student_model.pkl", "wb") as f:
        pickle.dump({
            "model": model,
            "features": FEATURES,
            "targets": TARGETS,
            "feature_mins": feature_mins,
            "feature_maxs": feature_maxs
        }, f)

    print("Saved student_model.pkl with bounds.")

if __name__ == "__main__":
    main()