Update app.py
Browse files419 unmodified lines42042142242342342442512 unmodified lines4384394404424434414454424434444454464474514484494504514554524534544554564574584594604614624634674684694704714644654664673 unmodified lines471472473474475476477419 unmodified lines return train_test_split(X, y, test_size=0.3, random_state=42)
def train_model(_): try: wandb.login(key=os.environ.get("WANDB_API_KEY"))12 unmodified lines } model = RandomForestClassifier(**params) score = cross_val_score(model, X_train, y_train, cv=3).mean() if wandb.run is None: wandb.init(project="model_optimization", name=f"optuna_trial_{trial.number}", reinit=True) wandb.log({**params, "cv_score": score}) return score return score # ✅ Must be returned here
study = optuna.create_study(direction="maximize") study.optimize(objective, n_trials=15)
best_params = study.best_params model = RandomForestClassifier() model = RandomForestClassifier(**best_params) model.fit(X_train, y_train) y_pred = model.predict(X_test)
metrics = { "accuracy": accuracy_score(y_test, y_pred), "precision": precision_score(y_test, y_pred, average="weighted", zero_division=0), "recall": recall_score(y_test, y_pred, average="weighted", zero_division=0), "f1_score": f1_score(y_test, y_pred, average="weighted", zero_division=0), }
wandb.log(metrics) wandb_run.finish()
# Top 7 trials top_trials = sorted(study.trials, key=lambda x: x.value, reverse=True)[:7] trial_rows = [] for t in top_trials: row = t.params.copy() row["score"] = t.value trial_rows.append(row) trial_rows = [dict(**t.params, score=t.value) for t in top_trials] trials_df = pd.DataFrame(trial_rows)
return metrics, trials_df3 unmodified lines return {}, pd.DataFrame()
def explainability(_): import warnings warnings.filterwarnings("ignore")app.py+5-11