Spaces:
Sleeping
Sleeping
Download app.py from kode24/Usecase_1_DS_workflow: direct link, hf CLI and curl.
- Browser
- Download file 58.3 kB
-
https://huggingface.co/spaces/kode24/Usecase_1_DS_workflow/resolve/main/app.py
- Command line
-
hf download hf://spaces/kode24/Usecase_1_DS_workflow/app.py
-
curl -L -o app.py https://huggingface.co/spaces/kode24/Usecase_1_DS_workflow/resolve/main/app.py
58.3 kB
| # --- Final Workshop Tool Script --- | |
| # Author: Kirsten Odendaal | |
| # 1. IMPORTS AND INITIAL SETUP | |
| import os | |
| import numpy as np | |
| import pandas as pd | |
| import gradio as gr | |
| import plotly.express as px | |
| import plotly.graph_objects as go | |
| from plotly.subplots import make_subplots | |
| import warnings | |
| from sklearn.model_selection import train_test_split, KFold, LeaveOneOut, cross_val_predict | |
| from sklearn.metrics import r2_score, mean_squared_error | |
| from sklearn.preprocessing import StandardScaler, PolynomialFeatures | |
| from sklearn.pipeline import Pipeline | |
| from sklearn.gaussian_process import GaussianProcessRegressor | |
| from sklearn.gaussian_process.kernels import RBF, ConstantKernel as C, WhiteKernel, Matern | |
| from sklearn.linear_model import LinearRegression, Ridge | |
| from sklearn.ensemble import RandomForestRegressor | |
| from sklearn.exceptions import ConvergenceWarning | |
| import pymoo.core.problem | |
| import pymoo.algorithms.soo.nonconvex.ga | |
| import pymoo.algorithms.moo.nsga2 | |
| import pymoo.optimize | |
| import pymoo.termination | |
| # Create DoE_out.csv if it doesn't exist for a self-contained example | |
| csv_data="""feature_diameter_mm,feature_anchorRadius_m,feature_f_ml_length,target_MooringMass_t,target_MaxLoads_norm_by_displ,target_MaxLoads_N, | |
| 103.758,200.0,1.06985,55.679226367011125,2.2659252760953197,2588090.0, | |
| 138.4,114.5,1.1145,59.96641515946571,3.1014955637387516,3542460.0, | |
| 96.0,114.5,1.01285,26.909093685386424,7.5958300720202985,8675790.0, | |
| 136.0,105.0,1.01935,49.071941481057074,9.16030601184754,10462700.0, | |
| 95.2,115.96,1.1449,30.2775373156862,4.4626494294234345,5097140.0, | |
| 60.0,79.35,1.2,9.537089701514653,5.38509759424538,6150740.0, | |
| 60.0,88.85,1.08315,9.455300292295451,5.10598172964284,5831940.0, | |
| 140.0,200.0,1.01,93.77218553313689,7.103717634204126,8113710.0, | |
| 96.0,13.8,1.1145,9.922556647857514,6.753001721272867,7713130.0, | |
| 110.275,200.0,1.2,70.22024421999363,2.6851769163825603,3066950.0, | |
| 140.0,10.0,1.01,18.099511503445846,8.259106724170838,9433370.0, | |
| 60.0,200.0,1.0803,19.866780645747767,3.016342461507751,3445200.0, | |
| 60.0,199.05,1.2,21.966908047813,3.2284197384295616,3687430.0, | |
| 60.0,10.0,1.01,3.585067275508448,5.539521860865819,6327120.0, | |
| 140.0,10.0,1.2,21.504370103103977,9.071615807693721,10361400.0, | |
| 85.4282,178.708,1.1482,36.96140903328846,3.397701584166391,3880780.0, | |
| 111.0,168.0,1.070574221,53.677770995260765,3.2195332076086216,3677280.0, | |
| """ | |
| if not os.path.exists("DoE_out.csv"): | |
| with open("DoE_out.csv", "w") as f: f.write(csv_data) | |
| # 2. CONFIGURATION AND HELPER FUNCTIONS | |
| warnings.filterwarnings("ignore", category=FutureWarning) | |
| warnings.filterwarnings("ignore", category=ConvergenceWarning) | |
| RANDOM_STATE = 42 | |
| DEFAULT_CSV_PATH = "DoE_out.csv" | |
| MAX_PARAMS_FOR_UI = 5 | |
| def generate_empty_fig(message=""): | |
| fig = go.Figure() | |
| fig.add_annotation(text=message, xref="paper", yref="paper", x=0.5, y=0.5, showarrow=False) | |
| fig.update_layout(xaxis={'visible': False}, yaxis={'visible': False}, template="plotly_white") | |
| return fig | |
| def get_hparams(model_type, n_estimators, max_depth, alpha, gp_kernel, gp_alpha, gp_n_restarts): | |
| if model_type == 'RandomForest': return {'n_estimators': n_estimators, 'max_depth': max_depth} | |
| if model_type == 'Ridge': return {'alpha': alpha} | |
| if model_type == 'GaussianProcess': return {'gp_kernel': gp_kernel, 'gp_alpha': gp_alpha, 'gp_n_restarts': gp_n_restarts} | |
| return {} | |
| def get_bounds_and_constraints(bounds_lb, bounds_ub, c_feat, c_type, c_val): | |
| bounds = list(zip(bounds_lb, bounds_ub)) | |
| # constraint = {'feature': c_feat, 'type': c_type, 'value': c_val} if c_feat and c_val is not None else None | |
| constraint = None | |
| if c_feat and c_val is not None: | |
| try: | |
| constraint = {'feature': c_feat, 'type': c_type, 'value': float(c_val)} | |
| except (ValueError, TypeError): | |
| constraint = None # Ignore invalid constraint values | |
| return bounds, constraint | |
| def make_pipeline(n_features, model_type, poly_degree=1, hyperparameters=None): | |
| if hyperparameters is None: hyperparameters = {} | |
| steps = [("scaler", StandardScaler())] | |
| if poly_degree > 1 and model_type != 'GaussianProcess': | |
| steps.append(("poly", PolynomialFeatures(degree=poly_degree, include_bias=False))) | |
| if model_type == 'Linear': model = LinearRegression() | |
| elif model_type == 'Ridge': model = Ridge(random_state=RANDOM_STATE, **hyperparameters) | |
| elif model_type == 'RandomForest': model = RandomForestRegressor(random_state=RANDOM_STATE, n_jobs=-1, **hyperparameters) | |
| elif model_type == 'GaussianProcess': | |
| gp_kernel_type = hyperparameters.get('gp_kernel', 'RBF') | |
| n_restarts = hyperparameters.get('gp_n_restarts', 10) | |
| alpha = hyperparameters.get('gp_alpha', 1e-6) | |
| if gp_kernel_type == 'Matern': | |
| kernel = C(1.0, (1e-3, 1e3)) * Matern(length_scale=1.0, length_scale_bounds=(1e-1, 1e2), nu=1.5) + \ | |
| WhiteKernel(noise_level=1.0, noise_level_bounds=(1e-1, 1e2)) | |
| else: # Default to RBF | |
| kernel = C(1.0, (1e-3, 1e3)) * RBF(length_scale=[1.0]*n_features, length_scale_bounds=(1e-1, 1e2)) + \ | |
| WhiteKernel(noise_level=1.0, noise_level_bounds=(1e-1, 1e2)) | |
| model = GaussianProcessRegressor(kernel=kernel, n_restarts_optimizer=n_restarts, random_state=RANDOM_STATE, alpha=alpha, normalize_y=True) | |
| # steps = [] # GPR handles scaling internally | |
| else: raise ValueError(f"Unknown model_type: {model_type}") | |
| steps.append(("model", model)) | |
| return Pipeline(steps) | |
| # 3. BACKEND LOGIC (REFACTORED FUNCTIONS) | |
| # --- STEP 1: LOAD & EDA --- | |
| def load_and_eda(file_obj, selected_features, selected_targets): | |
| try: | |
| if file_obj is None: | |
| df = pd.read_csv(DEFAULT_CSV_PATH) | |
| info_msg = f"βοΈ Loaded default data from **'{DEFAULT_CSV_PATH}'**." | |
| else: | |
| df = pd.read_csv(file_obj.name) | |
| info_msg = f"βοΈ Loaded data from **'{file_obj.name}'**." | |
| except Exception as e: | |
| return {components['eda_info_output']: f"π΄ **Error:** Could not read the CSV file. {e}", **{c: generate_empty_fig() for c in [components['eda_hist_plot'], components['eda_pair_plot'], components['eda_corr_plot']]}} | |
| all_columns = df.columns.tolist() | |
| if not selected_features or not selected_targets: | |
| info_msg += "\n\n**Next Step:** Select your **feature (X)** and **target (y)** columns." | |
| return { | |
| components['state_dataframe']: df, components['eda_info_output']: info_msg, | |
| components['eda_feature_selector']: gr.update(choices=all_columns, value=selected_features), | |
| components['eda_target_selector']: gr.update(choices=all_columns, value=selected_targets), | |
| } | |
| df_cleaned = df[selected_features + selected_targets].dropna() | |
| info_msg += f"\n\nπ Using **{len(selected_features)} features** and **{len(selected_targets)} target(s)**. Shape: {df_cleaned.shape}." | |
| X, y = df_cleaned[selected_features], df_cleaned[selected_targets] | |
| fig_hist = make_subplots(rows=int(np.ceil(len(df_cleaned.columns)/3)), cols=3, subplot_titles=df_cleaned.columns) | |
| for i, col in enumerate(df_cleaned.columns): | |
| fig_hist.add_trace(go.Histogram(x=df_cleaned[col], name=col), row=i//3+1, col=i%3+1) | |
| fig_hist.update_layout(title_text="<b>Feature & Target Distributions</b>", showlegend=False) | |
| fig_pair = px.scatter_matrix(df_cleaned, dimensions=selected_features, color=selected_targets[0], title="<b>Pairwise Feature Relationships</b>") | |
| fig_corr = px.imshow(df_cleaned.corr(), text_auto=".2f", aspect="auto", title="<b>Correlation Matrix</b>", color_continuous_scale='RdBu_r', zmin=-1, zmax=1) | |
| updates = { | |
| components['state_dataframe']: df_cleaned, components['state_feature_names']: selected_features, components['state_target_names']: selected_targets, | |
| components['eda_info_output']: info_msg, components['eda_hist_plot']: fig_hist, components['eda_pair_plot']: fig_pair, components['eda_corr_plot']: fig_corr, | |
| components['eda_feature_selector']: gr.update(choices=all_columns, value=selected_features), components['eda_target_selector']: gr.update(choices=all_columns, value=selected_targets), | |
| # Update dropdowns in other tabs | |
| components['viz_target_selector']: gr.update(choices=selected_targets, value=selected_targets[0]), | |
| components['viz_feature_selector_1']: gr.update(choices=selected_features, value=selected_features[0] if selected_features else None), | |
| components['viz_feature_selector_2']: gr.update(choices=selected_features, value=selected_features[1] if len(selected_features) > 1 else None), | |
| components['cv_target_selector']: gr.update(choices=selected_targets, value=selected_targets[0]), | |
| components['opt_primary_target_selector']: gr.update(choices=selected_targets, value=selected_targets[0]), | |
| components['opt_secondary_target_selector']: gr.update(choices=selected_targets, value=selected_targets[1] if len(selected_targets) > 1 else None), | |
| components['constraint_feature_dd']: gr.update(choices=selected_features) | |
| } | |
| for i in range(MAX_PARAMS_FOR_UI): | |
| is_visible = i < len(selected_features) | |
| updates[components[f'param_row_{i}']] = gr.update(visible=is_visible) | |
| if is_visible: | |
| feature_name = selected_features[i] | |
| updates[components[f'param_lb_{i}']] = gr.update(label=f"{feature_name} Min", value=X[feature_name].min()) | |
| updates[components[f'param_ub_{i}']] = gr.update(label=f"{feature_name} Max", value=X[feature_name].max()) | |
| else: | |
| # Optionally, reset the non-visible rows to default state | |
| updates[components[f'param_lb_{i}']] = gr.update(label=f"Param {i+1} Min", value=None) | |
| updates[components[f'param_ub_{i}']] = gr.update(label=f"Param {i+1} Max", value=None) | |
| return updates | |
| # --- STEP 2: BUILD SURROGATE --- | |
| def build_surrogate(df, features, targets, model_type, poly_degree, test_split, viz_target, viz_f1, viz_f2, n_estimators, max_depth, ridge_alpha, gp_kernel, gp_alpha, gp_n_restarts): | |
| if df is None or not features or not targets: | |
| return {components['surrogate_info_output']: "π΄ **Error:** Load data in Step 1 first.", **{c: generate_empty_fig("Model not built") for c in [components['surrogate_pa_plot'], components['surrogate_res_plot'], components['surrogate_fit_plot'], components['surrogate_metrics_output']]}} | |
| info_msg = f"π **Building {model_type} model...**" | |
| models = {} | |
| hparams = get_hparams(model_type, n_estimators, max_depth, ridge_alpha, gp_kernel, gp_alpha, gp_n_restarts) | |
| for target in targets: | |
| y = df[target] | |
| pipeline = make_pipeline(len(features), model_type, poly_degree, hyperparameters=hparams) | |
| if test_split > 0: | |
| X_tr, _, y_tr, _ = train_test_split(df[features], y, test_size=test_split, random_state=RANDOM_STATE) | |
| pipeline.fit(X_tr, y_tr) | |
| else: # Use all data for training | |
| pipeline.fit(df[features], y) | |
| models[target] = pipeline | |
| info_msg += "\n\nβ Models built for all targets." | |
| viz_model = models[viz_target] | |
| if test_split > 0: | |
| X_tr, X_te, y_tr, y_te = train_test_split(df[features], df[viz_target], test_size=test_split, random_state=RANDOM_STATE) | |
| y_pred = viz_model.predict(X_te) | |
| plot_title_suffix = "Test Set" | |
| y_actual_for_plot = y_te | |
| else: # Evaluate on training data | |
| X_tr, X_te, y_tr, y_te = df[features], df[features], df[viz_target], df[viz_target] # for consistency in plotting code | |
| y_pred = viz_model.predict(X_te) | |
| plot_title_suffix = "In-Sample (Training Data)" | |
| y_actual_for_plot = y_te | |
| r2 = r2_score(y_actual_for_plot, y_pred) | |
| rmse = np.sqrt(mean_squared_error(y_actual_for_plot, y_pred)) | |
| metrics_md = f""" | |
| ### {plot_title_suffix} Metrics | |
| **Target: {viz_target}** | |
| | Metric | Value | | |
| |:---------|:-------| | |
| | RΒ² Score | {r2:.4f} | | |
| | RMSE | {rmse:.4f} | | |
| """ | |
| fig_pa = px.scatter(x=y_actual_for_plot, y=y_pred, title=f"<b>Predicted vs. Actual ({plot_title_suffix})</b>", labels={'x':'True Value', 'y':'Predicted Value'}) | |
| fig_pa.add_shape(type='line', x0=y_actual_for_plot.min(), y0=y_actual_for_plot.min(), x1=y_actual_for_plot.max(), y1=y_actual_for_plot.max(), line=dict(color='red', dash='dash')) | |
| fig_pa.add_annotation(text="Good models have points<br>close to the red line.", align='left', showarrow=False, xref='paper', yref='paper', x=0.02, y=0.98) | |
| fig_res = px.scatter(x=y_pred, y=y_actual_for_plot - y_pred, title=f"<b>Residuals vs. Predicted ({plot_title_suffix})</b>", labels={'x':'Predicted Value', 'y':'Error (True-Predicted)'}) | |
| fig_res.add_hline(y=0, line_dash='dash', line_color='red') | |
| fig_res.add_annotation(text="Good models show a random<br>scatter around the red line.", align='left', showarrow=False, xref='paper', yref='paper', x=0.02, y=0.98) | |
| fig_fit = generate_empty_fig("Select 1 or 2 features to visualize the fit.") | |
| X = df[features] | |
| if viz_f1 and viz_f1 in features and (viz_f2 is None or viz_f2 not in features): | |
| # 1D plot logic | |
| try: | |
| viz_feature_idx = features.index(viz_f1) | |
| x_min, x_max = X[viz_f1].min(), X[viz_f1].max() | |
| x_plot_values = np.linspace(x_min, x_max, 100) | |
| X_medians = X.median().values | |
| x_plot_points = np.tile(X_medians, (100, 1)) | |
| x_plot_points[:, viz_feature_idx] = x_plot_values | |
| x_plot_df = pd.DataFrame(x_plot_points, columns=features) | |
| y_plot = viz_model.predict(x_plot_df) | |
| fig_fit = go.Figure() | |
| fig_fit.add_trace(go.Scattergl(x=X_tr[viz_f1], y=y_tr, mode='markers', name='Train Data', marker=dict(color='black', opacity=0.6))) | |
| fig_fit.add_trace(go.Scattergl(x=X_te[viz_f1], y=y_te, mode='markers', name='Test Data', marker=dict(color='blue', opacity=0.7))) | |
| fig_fit.add_trace(go.Scattergl(x=x_plot_values, y=y_plot, mode='lines', name='Surrogate Fit', line=dict(color='red'))) | |
| fig_fit.update_layout(title=f"Surrogate Fit: {viz_target} vs {viz_f1}", xaxis_title=viz_f1, yaxis_title=viz_target) | |
| if model_type == 'GaussianProcess': | |
| y_std = viz_model.predict(x_plot_df, return_std=True)[1] | |
| fig_fit.add_trace(go.Scattergl(x=np.concatenate([x_plot_values, x_plot_values[::-1]]), | |
| y=np.concatenate([y_plot - 1.96 * y_std, (y_plot + 1.96 * y_std)[::-1]]), | |
| fill='toself', fillcolor='rgba(255,0,0,0.2)', line=dict(color='rgba(255,255,255,0)'), | |
| name='95% CI')) | |
| except Exception as e: | |
| fig_fit = generate_empty_fig(f"1D Plot Error: {e}") | |
| elif viz_f1 and viz_f2 and viz_f1 in features and viz_f2 in features: | |
| # 2D/3D plot logic | |
| try: | |
| viz_feature_idx1 = features.index(viz_f1) | |
| viz_feature_idx2 = features.index(viz_f2) | |
| n_grid = 40 | |
| x1_range = np.linspace(X[viz_f1].min(), X[viz_f1].max(), n_grid) | |
| x2_range = np.linspace(X[viz_f2].min(), X[viz_f2].max(), n_grid) | |
| Xg, Yg = np.meshgrid(x1_range, x2_range) | |
| X_medians = X.median().values | |
| grid_points = np.tile(X_medians, (n_grid * n_grid, 1)) | |
| flat_grid = np.c_[Xg.ravel(), Yg.ravel()] | |
| grid_points[:, viz_feature_idx1] = flat_grid[:, 0] | |
| grid_points[:, viz_feature_idx2] = flat_grid[:, 1] | |
| grid_df = pd.DataFrame(grid_points, columns=features) | |
| Zg = viz_model.predict(grid_df).reshape(Xg.shape) | |
| fig_fit = go.Figure(data=[ | |
| go.Surface( | |
| x=Xg, y=Yg, z=Zg, | |
| colorscale='viridis', opacity=0.8, name='Surrogate Surface', | |
| colorbar=dict(title=viz_target, len=0.6, thickness=12, x=1.02) | |
| ), | |
| go.Scatter3d(x=X_tr[viz_f1], y=X_tr[viz_f2], z=y_tr, mode='markers', marker=dict(size=3, color='black', opacity=0.7), name='Train Data'), | |
| go.Scatter3d(x=X_te[viz_f1], y=X_te[viz_f2], z=y_te, mode='markers', marker=dict(size=4, color='blue', opacity=0.8), name='Test Data') | |
| ]) | |
| fig_fit.update_layout(title=f"Surrogate Surface: {viz_target}", scene=dict(xaxis_title=viz_f1, yaxis_title=viz_f2, zaxis_title=viz_target), height=600, margin=dict(l=0, r=0, b=0, t=40)) | |
| except Exception as e: | |
| fig_fit = generate_empty_fig(f"3D Plot Error: {e}") | |
| elif len(features) > 2: | |
| if model_type == 'RandomForest': | |
| importances = viz_model.named_steps['model'].feature_importances_ | |
| imp_df = pd.DataFrame({'feature': features, 'importance': importances}).sort_values('importance', ascending=False) | |
| fig_fit = px.bar(imp_df, x='importance', y='feature', orientation='h', title=f"<b>Feature Importances for {viz_target}</b>") | |
| else: | |
| fig_fit = generate_empty_fig("Feature importance only available for RandomForest. For other models with >2 features, no default plot.") | |
| return { | |
| components['state_surrogate_models']: models, | |
| components['surrogate_info_output']: info_msg, | |
| components['surrogate_pa_plot']: fig_pa, | |
| components['surrogate_res_plot']: fig_res, | |
| components['surrogate_fit_plot']: fig_fit, | |
| components['surrogate_metrics_output']: metrics_md | |
| } | |
| # --- STEP 3: CROSS VALIDATE --- | |
| def run_cross_validation(df, features, targets, model_type, poly_degree, cv_type, cv_target, n_estimators, max_depth, ridge_alpha, gp_kernel, gp_alpha, gp_n_restarts): | |
| if df is None or not features or not targets: | |
| return {components['cv_info_output']: "π΄ **Error:** Load data and build a model first.", **{c: generate_empty_fig("CV not run") for c in [components['cv_pa_plot'], components['cv_score_plot']]}} | |
| n_samples = len(df) | |
| if cv_type == "5-Fold": n_splits = min(5, n_samples) | |
| elif cv_type == "10-Fold": n_splits = min(10, n_samples) | |
| else: n_splits = n_samples | |
| cv_strategy = KFold(n_splits=n_splits, shuffle=True, random_state=RANDOM_STATE) if "Fold" in cv_type else LeaveOneOut() | |
| y = df[cv_target].values | |
| hparams = get_hparams(model_type, n_estimators, max_depth, ridge_alpha, gp_kernel, gp_alpha, gp_n_restarts) | |
| pipeline = make_pipeline(len(features), model_type, poly_degree, hyperparameters=hparams) | |
| predictions, true_values, folds, r2_scores, rmse_scores = [], [], [], [], [] | |
| for i, (train_idx, test_idx) in enumerate(cv_strategy.split(df)): | |
| X_tr, X_te = df[features].iloc[train_idx], df[features].iloc[test_idx] | |
| y_tr, y_te = y[train_idx], y[test_idx] | |
| pipeline.fit(X_tr, y_tr) | |
| preds = pipeline.predict(X_te) | |
| predictions.extend(preds); true_values.extend(y_te); folds.extend([f"Fold {i+1}"]*len(y_te)) | |
| r2_scores.append(r2_score(y_te, preds)) | |
| rmse_scores.append(np.sqrt(mean_squared_error(y_te, preds))) | |
| # Overall metrics from all out-of-sample predictions | |
| overall_r2 = r2_score(true_values, predictions) | |
| overall_rmse = np.sqrt(mean_squared_error(true_values, predictions)) | |
| # Per-fold stats | |
| mean_r2, std_r2 = np.mean(r2_scores), np.std(r2_scores) | |
| mean_rmse, std_rmse = np.mean(rmse_scores), np.std(rmse_scores) | |
| info_msg = f""" | |
| ### CV Results for **{cv_target}** | |
| | Metric | Overall (All Folds) | Mean of Folds (Β± std) | | |
| | :--- | :--- | :--- | | |
| | **RΒ² Score** | `{overall_r2:.4f}` | `{mean_r2:.4f} Β± {std_r2:.4f}` | | |
| | **RMSE** | `{overall_rmse:.4f}` | `{mean_rmse:.4f} Β± {std_rmse:.4f}` | | |
| """ | |
| plot_df = pd.DataFrame({'True': true_values, 'Predicted': predictions, 'Fold': folds}) | |
| fig_pa = px.scatter(plot_df, x='True', y='Predicted', color='Fold', title=f"<b>CV Predictions by Fold for {cv_target}</b> (Overall RΒ²: {overall_r2:.3f})") | |
| fig_pa.add_shape(type='line', x0=np.min(true_values), y0=np.min(true_values), x1=np.max(true_values), y1=np.max(true_values), line=dict(color='red', dash='dash')) | |
| fig_scores = make_subplots(rows=1, cols=2, subplot_titles=("RΒ² Score per Fold", "RMSE per Fold")) | |
| fig_scores.add_trace(go.Box(y=r2_scores, name='RΒ²'), row=1, col=1) | |
| fig_scores.add_trace(go.Box(y=rmse_scores, name='RMSE'), row=1, col=2) | |
| fig_scores.update_layout(showlegend=False, title_text=f"<b>Metric Distributions Across {n_splits} Folds</b>") | |
| return { | |
| components['cv_info_output']: info_msg, | |
| components['cv_pa_plot']: fig_pa, | |
| components['cv_score_plot']: fig_scores | |
| } | |
| # --- STEP 4: OPTIMIZE --- | |
| def update_optimization_plot(results_data, features, x_axis, y_axis, color_axis): | |
| """Dynamically redraws the optimization plot based on dropdown selections.""" | |
| if not results_data: | |
| return generate_empty_fig("No optimization data to plot.") | |
| try: | |
| opt_type = results_data.get('type') | |
| p_target = results_data.get('p_target') | |
| fig = go.Figure() | |
| if opt_type == 'moo': | |
| s_target = results_data.get('s_target') | |
| pareto_X, pareto_F = results_data['X'], results_data['F'] | |
| orig_X, orig_F1, orig_F2 = results_data['orig_X'], results_data['orig_F1'], results_data['orig_F2'] | |
| hist_X, hist_F = results_data.get('hist_X'), results_data.get('hist_F') | |
| hist_G = results_data.get('hist_G') | |
| def get_moo_data(selection, feat_names, p_X, p_F, o_X, o_F1, o_F2, h_X, h_F): | |
| p, o, h = (None,)*3; has_h = h_X is not None and h_X.ndim == 2 | |
| if selection == f"Objective: {p_target}": p, o, h = p_F[:, 0], o_F1, h_F[:, 0] if has_h else None | |
| elif selection == f"Objective: {s_target}": p, o, h = p_F[:, 1], o_F2, h_F[:, 1] if has_h else None | |
| elif selection in feat_names: | |
| idx = feat_names.index(selection) | |
| p, o, h = p_X[:, idx], o_X[selection], h_X[:, idx] if has_h else None | |
| return p, o, h | |
| px, ox, hx = get_moo_data(x_axis, features, pareto_X, pareto_F, orig_X, orig_F1, orig_F2, hist_X, hist_F) | |
| py, oy, hy = get_moo_data(y_axis, features, pareto_X, pareto_F, orig_X, orig_F1, orig_F2, hist_X, hist_F) | |
| pc, oc, _ = get_moo_data(color_axis, features, pareto_X, pareto_F, orig_X, orig_F1, orig_F2, hist_X, hist_F) | |
| if hx is not None and hy is not None: | |
| if hist_G is not None and hist_G.ndim == 2 and hist_G.shape[0] == len(hx): | |
| is_feasible = hist_G[:, 0] <= 1e-6 # Use a small tolerance | |
| fig.add_trace(go.Scattergl(x=hx[~is_feasible], y=hy[~is_feasible], mode='markers', marker=dict(color='rgba(255, 100, 100, 0.5)', symbol='x', size=6), name='Infeasible History')) | |
| fig.add_trace(go.Scattergl(x=hx[is_feasible], y=hy[is_feasible], mode='markers', marker=dict(color='lightgrey', size=5, opacity=0.4), name='Feasible History')) | |
| else: # No constraint case | |
| fig.add_trace(go.Scattergl(x=hx, y=hy, mode='markers', marker=dict(color='lightgrey', size=5, opacity=0.4), name='Dominated Population')) | |
| cmin, cmax = min(np.min(oc), np.min(pc)), max(np.max(oc), np.max(pc)) | |
| fig.add_trace(go.Scattergl( | |
| x=ox, y=oy, mode='markers', | |
| marker=dict( | |
| color=oc, colorscale='viridis', showscale=True, | |
| colorbar=dict(title=color_axis, len=0.6, thickness=12, x=1.02), | |
| cmin=cmin, cmax=cmax, size=6, opacity=0.5, symbol='circle-open' | |
| ), | |
| name='Original Designs' | |
| )) | |
| fig.add_trace(go.Scattergl( | |
| x=px, y=py, mode='markers', | |
| marker=dict(color=pc, colorscale='viridis', showscale=False, cmin=cmin, cmax=cmax, size=8, opacity=0.9), | |
| name='Pareto Front' | |
| )) | |
| hover_texts = ["<br>".join([f"{name}: {val:.3f}" for name, val in zip(features, pX)]) for pX in pareto_X] | |
| fig.data[-1].customdata = hover_texts | |
| fig.data[-1].hovertemplate = '<b>Parameters</b><br>%{customdata}<extra></extra>' | |
| fig.update_layout(title="<b>Pareto Front Explorer</b>", xaxis_title=x_axis, yaxis_title=y_axis, template='plotly_white') | |
| elif opt_type == 'soo': | |
| best_X, best_F = results_data['X'], results_data['F'] | |
| pop_X, pop_F = results_data['pop_X'], results_data['pop_F'] | |
| orig_X, orig_F = results_data['orig_X'], results_data['orig_F'] | |
| def get_soo_data(selection, feat_names, b_X, b_F, p_X, p_F, o_X, o_F): | |
| b, p, o = (None,)*3 | |
| if selection == f"Objective: {p_target}": b, p, o = b_F[0], p_F[:, 0], o_F | |
| elif selection in feat_names: | |
| idx = feat_names.index(selection) | |
| b, p, o = b_X[idx], p_X[:, idx], o_X[selection] | |
| return b, p, o | |
| bx, px, ox = get_soo_data(x_axis, features, best_X, best_F, pop_X, pop_F, orig_X, orig_F) | |
| by, py, oy = get_soo_data(y_axis, features, best_X, best_F, pop_X, pop_F, orig_X, orig_F) | |
| bc, pc, oc = get_soo_data(color_axis, features, best_X, best_F, pop_X, pop_F, orig_X, orig_F) | |
| cmin, cmax = min(np.min(oc), np.min(pc), bc), max(np.max(oc), np.max(pc), bc) | |
| fig.add_trace(go.Scattergl( | |
| x=ox, y=oy, mode='markers', | |
| marker=dict( | |
| color=oc, cmin=cmin, cmax=cmax, colorscale='viridis', showscale=True, | |
| colorbar=dict(title=color_axis, len=0.6, thickness=12, x=1.02), | |
| size=6, opacity=0.6, symbol='circle-open' | |
| ), | |
| name='Original Designs' | |
| )) | |
| fig.add_trace(go.Scattergl(x=px, y=py, mode='markers', marker=dict(color=pc, cmin=cmin, cmax=cmax, colorscale='viridis', showscale=False, size=7, opacity=0.7), name='Final Population')) | |
| fig.add_trace(go.Scattergl(x=[bx], y=[by], mode='markers', marker=dict(color=bc, cmin=cmin, cmax=cmax, colorscale='viridis', showscale=False, size=14, symbol='star', line=dict(width=2, color='DarkSlateGrey')), name='Best Solution')) | |
| fig.update_layout(title="<b>Single-Objective Explorer</b>", xaxis_title=x_axis, yaxis_title=y_axis, template='plotly_white') | |
| else: return generate_empty_fig("Unknown optimization type.") | |
| return fig | |
| except Exception as e: | |
| return generate_empty_fig(f"Plotting Error: {e}") | |
| def reset_bounds(df, features): | |
| """Resets the parameter bounds in the UI to their original min/max values from the dataframe.""" | |
| if df is None or not features: | |
| # If no data is loaded, we can't do anything, so return non-updating updates. | |
| return [gr.update(value=None)] * (MAX_PARAMS_FOR_UI * 2) | |
| updates = [] | |
| # Create updates for lower bounds | |
| for i in range(MAX_PARAMS_FOR_UI): | |
| if i < len(features): | |
| min_val = df[features[i]].min() | |
| updates.append(gr.update(value=min_val)) | |
| else: | |
| updates.append(gr.update(value=None)) | |
| # Create updates for upper bounds | |
| for i in range(MAX_PARAMS_FOR_UI): | |
| if i < len(features): | |
| max_val = df[features[i]].max() | |
| updates.append(gr.update(value=max_val)) | |
| else: | |
| updates.append(gr.update(value=None)) | |
| return updates | |
| class PymooProblem(pymoo.core.problem.Problem): | |
| def __init__(self, models, features, xl, xu, constraint_info=None): | |
| self.models, self.features, self.constraint = models, features, constraint_info | |
| super().__init__(n_var=len(features), n_obj=len(models), n_constr=1 if constraint_info else 0, xl=xl, xu=xu) | |
| def _evaluate(self, x, out, *args, **kwargs): | |
| x_df = pd.DataFrame(x, columns=self.features) | |
| out["F"] = np.column_stack([model.predict(x_df) for model in self.models.values()]) | |
| if self.constraint: | |
| vals = x_df[self.constraint['feature']].values | |
| out["G"] = vals - self.constraint['value'] if self.constraint['type'] == "<=" else self.constraint['value'] - vals | |
| def run_optimization(models, features, df, opt_type, p_target, s_target, pop, gen, c_feat, c_type, c_val, *param_bounds): | |
| if not models or not features or df is None: | |
| return {components['opt_info_output']: "π΄ **Error:** Load data and build a model in Step 1 & 2 first.", **{k: v for k,v in {components['opt_plot_output']: generate_empty_fig("Opt not run"), components['state_opt_res']: None, components['moo_dynamic_row']: gr.update(visible=False)}.items()}} | |
| is_moo = opt_type == "Multi-Objective" and p_target and s_target and p_target != s_target | |
| opt_models = {p_target: models[p_target]} | |
| if is_moo: | |
| if s_target in models: | |
| opt_models[s_target] = models[s_target] | |
| else: # Fallback if second target is invalid | |
| is_moo = False | |
| # We receive param_bounds as a flat list from Gradio, so we reconstruct the pairs | |
| num_params = len(features) | |
| all_lb_values = param_bounds[:MAX_PARAMS_FOR_UI] | |
| all_ub_values = param_bounds[MAX_PARAMS_FOR_UI:] | |
| param_lb_values = all_lb_values[:num_params] | |
| param_ub_values = all_ub_values[:num_params] | |
| # Convert to float and validate bounds | |
| try: | |
| param_lb_values = [float(val) if val is not None else 0.0 for val in param_lb_values] | |
| param_ub_values = [float(val) if val is not None else 1.0 for val in param_ub_values] | |
| except (ValueError, TypeError) as e: | |
| return {components['opt_info_output']: f"π΄ **Error:** Invalid bounds values. Please ensure all bounds are numeric. {e}", **{k: v for k,v in {components['opt_plot_output']: generate_empty_fig("Bounds Error"), components['state_opt_res']: None, components['moo_dynamic_row']: gr.update(visible=False)}.items()}} | |
| bounds, constraint = get_bounds_and_constraints(param_lb_values, param_ub_values, c_feat, c_type, c_val) | |
| if len(bounds) != num_params: | |
| return {components['opt_info_output']: "π΄ **Error:** Number of bounds does not match number of features.", **{k: v for k,v in {components['opt_plot_output']: generate_empty_fig("Bounds Error"), components['state_opt_res']: None, components['moo_dynamic_row']: gr.update(visible=False)}.items()}} | |
| problem = PymooProblem(opt_models, features, [b[0] for b in bounds], [b[1] for b in bounds], constraint) | |
| algorithm = pymoo.algorithms.moo.nsga2.NSGA2(pop_size=pop) if is_moo else pymoo.algorithms.soo.nonconvex.ga.GA(pop_size=pop) | |
| res = pymoo.optimize.minimize(problem, algorithm, ("n_gen", gen), seed=RANDOM_STATE, save_history=True, return_pop=True) | |
| info_msg = "β **Optimization Complete!**\n\n" | |
| if constraint: | |
| info_msg += f"- **Constraint Applied:** `{c_feat} {c_type} {c_val}`\n" | |
| if not is_moo: | |
| opt_params_str = ", ".join([f"**{name}**: {val:.4f}" for name, val in zip(features, res.X)]) | |
| info_msg += f"- **Best `{p_target}` found:** {res.F[0]:.4f}\n- **Optimal Parameters:**\n {opt_params_str}" | |
| results_data = { | |
| 'type': 'soo', 'p_target': p_target, | |
| 'X': res.X, 'F': res.F, | |
| 'pop_X': res.pop.get("X"), 'pop_F': res.pop.get("F"), | |
| 'orig_X': df[features], 'orig_F': models[p_target].predict(df[features]) | |
| } | |
| plot_choices = [f"Objective: {p_target}"] + features | |
| default_x = features[0] if features else f"Objective: {p_target}" | |
| default_y = f"Objective: {p_target}" | |
| default_color = features[1] if len(features) > 1 else default_x | |
| fig = update_optimization_plot(results_data, features, default_x, default_y, default_color) | |
| return { | |
| components['opt_info_output']: info_msg, | |
| components['opt_plot_output']: fig, | |
| components['state_opt_res']: results_data, | |
| components['moo_dynamic_row']: gr.update(visible=True), | |
| components['moo_plot_x']: gr.update(choices=plot_choices, value=default_x), | |
| components['moo_plot_y']: gr.update(choices=plot_choices, value=default_y), | |
| components['moo_plot_color']: gr.update(choices=plot_choices, value=default_color), | |
| } | |
| else: # Multi-objective | |
| info_msg += f"- Found **{len(res.F)}** Pareto-optimal solutions for **{p_target}** and **{s_target}**." | |
| plot_choices = [f"Objective: {p_target}", f"Objective: {s_target}"] + features | |
| # Extract history data | |
| all_hist_X, all_hist_F, all_hist_G = [], [], [] | |
| if res.history: | |
| for algo in res.history: | |
| if algo.pop is not None and len(algo.pop) > 0: | |
| all_hist_X.append(algo.pop.get("X")) | |
| all_hist_F.append(algo.pop.get("F")) | |
| if constraint: | |
| all_hist_G.append(algo.pop.get("G")) | |
| all_hist_X = np.vstack(all_hist_X) if all_hist_X else np.array([[]]) | |
| all_hist_F = np.vstack(all_hist_F) if all_hist_F else np.array([[]]) | |
| all_hist_G = np.vstack(all_hist_G) if all_hist_G and constraint else None | |
| # Evaluate surrogate on original data for comparison plotting | |
| orig_F1 = models[p_target].predict(df[features]) | |
| orig_F2 = models[s_target].predict(df[features]) | |
| results_data = {'type': 'moo', 'p_target': p_target, 's_target': s_target, 'X': res.X, 'F': res.F, 'orig_X': df[features], 'orig_F1': orig_F1, 'orig_F2': orig_F2, 'hist_X': all_hist_X, 'hist_F': all_hist_F, 'hist_G': all_hist_G, 'constraint': constraint} | |
| # Create initial plot | |
| default_color = features[0] if features else f"Objective: {p_target}" | |
| fig = update_optimization_plot(results_data, features, f"Objective: {p_target}", f"Objective: {s_target}", default_color) | |
| return { | |
| components['opt_info_output']: info_msg, | |
| components['opt_plot_output']: fig, | |
| components['state_opt_res']: results_data, | |
| components['moo_dynamic_row']: gr.update(visible=True), | |
| components['moo_plot_x']: gr.update(choices=plot_choices, value=f"Objective: {p_target}"), | |
| components['moo_plot_y']: gr.update(choices=plot_choices, value=f"Objective: {s_target}"), | |
| components['moo_plot_color']: gr.update(choices=plot_choices, value=default_color), | |
| } | |
| # 4. GRADIO UI DEFINITION | |
| with gr.Blocks(title="Data Science Workflow Tool") as demo: # theme=gr.themes.Soft(), | |
| with gr.Row(): | |
| with gr.Column(scale=1): # 1/4 of the row | |
| gr.Image( | |
| "marin_logo.png", | |
| show_label=False, | |
| show_download_button=False, | |
| show_fullscreen_button=False, | |
| height=100, # you can tweak this | |
| elem_id="app-logo" | |
| ) | |
| with gr.Column(scale=3): # 3/4 of the row | |
| gr.Markdown("# A Visual & Interactive Data Science Workflow") | |
| with gr.Row(): | |
| gr.Markdown(""" | |
| This tool demonstrates the **end-to-end process** of building and using surrogate models: | |
| 1. **π Data Exploration** - Understand your data before modeling | |
| 2. **π€ Model Building** - Train surrogate models with different algorithms | |
| 3. **β Validation** - Cross-validate to ensure reliability | |
| 4. **π― Optimization** - Use the surrogate to find optimal designs | |
| """) | |
| # --- State Variables --- | |
| state_dataframe = gr.State(None) | |
| state_feature_names = gr.State([]) | |
| state_target_names = gr.State([]) | |
| state_surrogate_models = gr.State(None) | |
| state_opt_res = gr.State(None) # To store optimization results for dynamic plotting | |
| with gr.Tabs(): | |
| # --- TAB 1: LOAD & EDA --- | |
| with gr.TabItem("1. Load & Explore Data", id=0): | |
| with gr.Accordion("π Step 1: Exploratory Data Analysis (EDA)", open=False): | |
| gr.Markdown(""" | |
| ### **What is EDA?** | |
| Exploratory Data Analysis is the **crucial first step** in any data science project. Before building any model, you must understand your data's characteristics, patterns, and potential issues. | |
| ### **Key EDA Objectives:** | |
| - π **Data Quality**: Identify missing values, outliers, and inconsistencies | |
| - π **Distributions**: Understand how your variables are distributed | |
| - π **Relationships**: Discover correlations and dependencies between variables | |
| - β οΈ **Assumptions**: Check if your data meets modeling assumptions | |
| ### **What You'll See Here:** | |
| - **Histograms**: Distribution shapes for each variable | |
| - **Pair Plots**: Scatter matrix showing relationships between features | |
| - **Correlation Matrix**: Heatmap showing linear relationships | |
| - **Data Summary**: Basic statistics and data quality metrics | |
| ### **π‘ Pro Tip:** | |
| Good EDA can reveal whether your data is suitable for surrogate modeling and help you choose the right modeling approach! | |
| """) | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| gr.Markdown("#### Data Input") | |
| eda_file_input = gr.File(label="Upload CSV", type="filepath", file_count="single") | |
| eda_feature_selector = gr.Dropdown(label="Select Feature Columns (X)", multiselect=True, interactive=True) | |
| eda_target_selector = gr.Dropdown(label="Select Target Column(s) (y)", multiselect=True, interactive=True) | |
| eda_load_button = gr.Button("Load Data & Run EDA", variant="primary") | |
| eda_info_output = gr.Markdown(label="Log & Info") | |
| with gr.Column(scale=2): | |
| eda_hist_plot = gr.Plot(label="Distributions") | |
| # with gr.Row(): | |
| eda_pair_plot = gr.Plot(label="Pair Plot") | |
| eda_corr_plot = gr.Plot(label="Correlation Heatmap") | |
| # --- TAB 2: BUILD SURROGATE --- | |
| with gr.TabItem("2. Build Surrogate Model", id=1): | |
| with gr.Accordion("π€ Step 2: Surrogate Model Building", open=False): | |
| gr.Markdown(""" | |
| ### **What is a Surrogate Model?** | |
| A **surrogate model** is a fast, data-driven approximation of a slow or expensive simulation. Think of it as a "digital twin" that learns from your simulation data and can predict approximate outcomes quickly. Instead of running computationally intensive simulations every time you need a prediction, you train a surrogate model on a limited set of simulation results and use it to make instant predictions. | |
| ### **Why Use Surrogate Models?** | |
| - β‘ **Speed**: Get predictions in milliseconds instead of hours | |
| - π° **Cost**: Reduce computational expenses dramatically | |
| - π **Exploration**: Enable extensive parameter studies and optimization | |
| - π **Analysis**: Understand relationships between inputs and outputs | |
| ### **Available Model Types:** | |
| #### **π΅ Linear Regression** | |
| - **Best for**: Linear relationships, simple problems | |
| - **Pros**: Fast, interpretable, no hyperparameters | |
| - **Cons**: Limited to linear patterns | |
| #### **π’ Ridge Regression** | |
| - **Best for**: Linear relationships with regularization | |
| - **Pros**: Handles multicollinearity, prevents overfitting | |
| - **Cons**: Still limited to linear patterns | |
| #### **π‘ Random Forest** | |
| - **Best for**: Non-linear relationships, feature interactions | |
| - **Pros**: Handles non-linearity, feature importance, robust | |
| - **Cons**: Less smooth predictions, more hyperparameters | |
| #### **π£ Gaussian Process** | |
| - **Best for**: Smooth functions, uncertainty quantification | |
| - **Pros**: Provides uncertainty estimates, very flexible | |
| - **Cons**: Computationally expensive, sensitive to hyperparameters | |
| ### **Model Evaluation:** | |
| - **RΒ² Score**: Proportion of variance explained (closer to 1.0 is better) | |
| - **RMSE**: Root Mean Square Error (lower is better) | |
| - **Residuals**: Should be randomly scattered around zero | |
| - **Predicted vs Actual**: Points should lie close to the diagonal line | |
| ### **π‘ Pro Tip:** | |
| Start with simpler models (Linear/Ridge) and progress to more complex ones (Random Forest/Gaussian Process) if needed! | |
| """) | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| gr.Markdown("#### Model Configuration") | |
| surrogate_model_type = gr.Dropdown(['Linear', 'Ridge', 'RandomForest', 'GaussianProcess'], label="Model Type", value='Linear') | |
| surrogate_poly_degree = gr.Slider(1, 4, step=1, label="Polynomial Degree (for Linear/Ridge)", value=1) | |
| surrogate_test_split = gr.Slider(0.0, 0.5, step=0.05, label="Test Set Ratio (0.0 = use all data for training)", value=0.0) | |
| with gr.Accordion("Model Hyperparameters", open=True): | |
| with gr.Row(visible=False) as rf_hparams_row: | |
| rf_n_estimators = gr.Slider(10, 500, step=10, label="Number of Trees (n_estimators)", value=100) | |
| rf_max_depth = gr.Slider(2, 20, step=1, label="Max Tree Depth (max_depth)", value=10) | |
| with gr.Row(visible=False) as ridge_hparams_row: | |
| ridge_alpha = gr.Slider(0.01, 10.0, step=0.01, label="Regularization (alpha)", value=1.0) | |
| with gr.Row(visible=False) as gp_hparams_row: | |
| gp_kernel_dd = gr.Dropdown(['RBF', 'Matern'], label="GP Kernel", value='Matern') | |
| gp_alpha_slider = gr.Slider(1e-10, 2, value=1e-2, label="GP Alpha (Regularization)", step=1e-10) | |
| gp_restarts_slider = gr.Slider(0, 20, step=1, label="GP Optimizer Restarts", value=10) | |
| gr.Markdown("#### Visualization Settings") | |
| viz_target_selector = gr.Dropdown(label="Target to Visualize", interactive=True) | |
| viz_feature_selector_1 = gr.Dropdown(label="X-Axis Feature (for 1D/2D plot)", interactive=True) | |
| viz_feature_selector_2 = gr.Dropdown(label="Y-Axis Feature (for 2D plot)", interactive=True) | |
| surrogate_build_button = gr.Button("Build & Evaluate Surrogate", variant="primary") | |
| surrogate_info_output = gr.Markdown(label="Log & Info") | |
| surrogate_metrics_output = gr.Markdown(label="Test Set Metrics") | |
| with gr.Column(scale=2): | |
| with gr.Row(): | |
| surrogate_pa_plot = gr.Plot(label="Predicted vs. True") | |
| surrogate_res_plot = gr.Plot(label="Residuals vs. Predicted") | |
| surrogate_fit_plot = gr.Plot(label="Surrogate Visualization") | |
| # --- TAB 3: CROSS-VALIDATE --- | |
| with gr.TabItem("3. Cross-Validate Model", id=2): | |
| with gr.Accordion("β Step 3: Cross-Validation", open=False): | |
| gr.Markdown(""" | |
| ### **What is Cross-Validation?** | |
| Cross-validation is a **critical validation technique** that provides a more robust estimate of model performance by training and testing on multiple different subsets of the data. It helps ensure your model will generalize well to new, unseen data. | |
| ### **Why Cross-Validation Matters:** | |
| - π― **Realistic Performance**: Estimates how well your model will perform on new data | |
| - β οΈ **Overfitting Detection**: Identifies if your model memorizes training data | |
| - π **Robustness Testing**: Tests performance across different data splits | |
| - π **Confidence Intervals**: Provides uncertainty estimates for performance metrics | |
| ### **Available CV Strategies:** | |
| #### **π K-Fold Cross-Validation** | |
| - **5-Fold**: Divides data into 5 equal parts, trains on 4, tests on 1 | |
| - **10-Fold**: More robust but computationally expensive | |
| - **Best for**: Most situations, good balance of robustness and speed | |
| #### **π― Leave-One-Out Cross-Validation (LOOCV)** | |
| - Uses all data except one point for training, tests on that point | |
| - **Best for**: Small datasets, maximum use of available data | |
| - **Warning**: Can be very slow for large datasets | |
| ### **What to Look For:** | |
| - **Consistent Performance**: Low standard deviation across folds | |
| - **Reasonable RΒ²**: Should be similar to training performance | |
| - **Random Residuals**: No patterns in prediction errors | |
| - **Stable Metrics**: Similar performance across all folds | |
| ### **π‘ Pro Tip:** | |
| If CV performance is much worse than training performance, your model is likely overfitting! | |
| """) | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| gr.Markdown("#### CV Setup") | |
| cv_target_selector = gr.Dropdown(label="Select Target to Visualize", interactive=True) | |
| cv_type_selector = gr.Dropdown(["5-Fold", "10-Fold", "LOOCV"], label="CV Strategy", value="5-Fold") | |
| cv_run_button = gr.Button("Run Cross-Validation", variant="primary") | |
| cv_info_output = gr.Markdown(label="Log & Info") | |
| cv_metrics_output = gr.Markdown(label="CV Metrics Summary") | |
| with gr.Column(scale=2): | |
| cv_pa_plot = gr.Plot(label="CV Predictions vs. True (Colored by Fold)") | |
| cv_score_plot = gr.Plot(label="Performance Distribution Across Folds") | |
| # --- TAB 4: OPTIMIZE --- | |
| with gr.TabItem("4. Optimize with Surrogate", id=3): | |
| with gr.Accordion("π― Step 4: Surrogate-Based Optimization", open=False): | |
| gr.Markdown(""" | |
| ### **What is Surrogate-Based Optimization?** | |
| Once you have a reliable surrogate model, you can use it to **efficiently search for optimal designs** without running expensive simulations. This is where the real value of surrogate modeling becomes apparent! | |
| ### **Optimization Concepts:** | |
| #### **π― Single-Objective Optimization** | |
| - **Goal**: Find the design that minimizes (or maximizes) one target variable | |
| - **Example**: Minimize cost while maximizing performance | |
| - **Algorithm**: Genetic Algorithm (GA) with population-based search | |
| - **Output**: Single best solution with optimal parameters | |
| #### **βοΈ Multi-Objective Optimization** | |
| - **Goal**: Find trade-offs between competing objectives | |
| - **Example**: Minimize both cost AND maximize performance simultaneously | |
| - **Algorithm**: NSGA-II (Non-dominated Sorting Genetic Algorithm) | |
| - **Output**: Pareto front showing optimal trade-offs | |
| ### **Key Components:** | |
| #### **π Search Space Definition** | |
| - **Parameter Bounds**: Define min/max values for each design variable | |
| - **Constraints**: Optional limits on parameter combinations | |
| - **Discrete vs Continuous**: Handle different parameter types | |
| #### **𧬠Genetic Algorithm Parameters** | |
| - **Population Size**: Number of candidate solutions per generation | |
| - **Generations**: Number of evolutionary iterations | |
| - **Mutation/Crossover**: How solutions evolve and combine | |
| #### **π Visualization & Analysis** | |
| - **Pareto Front**: Shows optimal trade-offs between objectives | |
| - **Parameter Sensitivity**: Which parameters matter most | |
| - **Convergence**: How optimization progresses over time | |
| ### **π‘ Pro Tips:** | |
| - Start with **single-objective** to understand the problem | |
| - Use **multi-objective** when you have competing goals | |
| - **Constraints** help focus the search on feasible designs | |
| - **Larger populations** explore more but take longer | |
| """) | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| gr.Markdown("#### 1. Define Objectives") | |
| opt_type_radio = gr.Radio(["Single-Objective", "Multi-Objective"], label="Optimization Type", value="Multi-Objective") | |
| opt_primary_target_selector = gr.Dropdown(label="π― Primary Objective (to minimize)", interactive=True) | |
| with gr.Row() as mo_row: | |
| opt_secondary_target_selector = gr.Dropdown(label="π― Secondary Objective (to minimize)", interactive=True) | |
| gr.Markdown("#### 2. Configure Algorithm") | |
| opt_pop_size_slider = gr.Slider(20, 200, step=10, label="Population Size", value=50) | |
| opt_num_gen_slider = gr.Slider(20, 500, step=10, label="Number of Generations", value=100) | |
| gr.Markdown("#### 3. Define Constraints (Optional)") | |
| with gr.Row(): | |
| constraint_feature_dd = gr.Dropdown(label="Constrain Feature...", interactive=True) | |
| constraint_type_dd = gr.Dropdown(choices=["<=", ">="], label="Type", value="<=") | |
| constraint_value_num = gr.Number(label="Value") | |
| with gr.Accordion("4. Define Parameter Search Space", open=True): | |
| # gr.Markdown("#### 4. Define Parameter Search Space") | |
| param_lb_inputs, param_ub_inputs, param_rows = [], [], [] | |
| for i in range(MAX_PARAMS_FOR_UI): | |
| with gr.Row(visible=False) as row: | |
| param_rows.append(row) | |
| lb = gr.Number(label=f"P{i+1} Min", scale=1) | |
| ub = gr.Number(label=f"P{i+1} Max", scale=1) | |
| param_lb_inputs.append(lb); param_ub_inputs.append(ub) | |
| with gr.Row(): | |
| opt_run_button = gr.Button("Run Optimization", variant="primary", scale=3) | |
| opt_reset_button = gr.Button("Reset Bounds", scale=1) | |
| with gr.Column(scale=2): | |
| opt_plot_output = gr.Plot(label="Optimization Visualization") | |
| opt_info_output = gr.Markdown(label="Results Summary") | |
| with gr.Row(visible=False) as moo_dynamic_row: | |
| gr.Markdown("--- \n#### Explore Pareto Front") | |
| with gr.Row(): | |
| moo_plot_x = gr.Dropdown(label="X-Axis", interactive=True) | |
| moo_plot_y = gr.Dropdown(label="Y-Axis", interactive=True) | |
| moo_plot_color = gr.Dropdown(label="Color By", interactive=True) | |
| # 5. COMPONENT DICTIONARY & EVENT HANDLING | |
| # This dictionary is the key to clean updates | |
| components = { | |
| # State | |
| "state_dataframe": state_dataframe, "state_feature_names": state_feature_names, "state_target_names": state_target_names, "state_surrogate_models": state_surrogate_models, "state_opt_res": state_opt_res, | |
| # Tab 1 | |
| "eda_file_input": eda_file_input, "eda_feature_selector": eda_feature_selector, "eda_target_selector": eda_target_selector, "eda_load_button": eda_load_button, | |
| "eda_info_output": eda_info_output, "eda_hist_plot": eda_hist_plot, "eda_pair_plot": eda_pair_plot, "eda_corr_plot": eda_corr_plot, | |
| # Tab 2 | |
| "surrogate_model_type": surrogate_model_type, "surrogate_poly_degree": surrogate_poly_degree, "surrogate_test_split": surrogate_test_split, | |
| "rf_hparams_row": rf_hparams_row, "rf_n_estimators": rf_n_estimators, "rf_max_depth": rf_max_depth, | |
| "ridge_hparams_row": ridge_hparams_row, "ridge_alpha": ridge_alpha, | |
| "gp_hparams_row": gp_hparams_row, "gp_kernel_dd": gp_kernel_dd, "gp_alpha_slider": gp_alpha_slider, "gp_restarts_slider": gp_restarts_slider, | |
| "viz_target_selector": viz_target_selector, "viz_feature_selector_1": viz_feature_selector_1, "viz_feature_selector_2": viz_feature_selector_2, | |
| "surrogate_build_button": surrogate_build_button, "surrogate_info_output": surrogate_info_output, "surrogate_metrics_output": surrogate_metrics_output, | |
| "surrogate_pa_plot": surrogate_pa_plot, "surrogate_res_plot": surrogate_res_plot, "surrogate_fit_plot": surrogate_fit_plot, | |
| # Tab 3 | |
| "cv_target_selector": cv_target_selector, "cv_type_selector": cv_type_selector, "cv_run_button": cv_run_button, | |
| "cv_info_output": cv_info_output, "cv_metrics_output": cv_metrics_output, "cv_pa_plot": cv_pa_plot, "cv_score_plot": cv_score_plot, | |
| # Tab 4 | |
| "opt_type_radio": opt_type_radio, "mo_row": mo_row, "opt_primary_target_selector": opt_primary_target_selector, "opt_secondary_target_selector": opt_secondary_target_selector, | |
| "constraint_feature_dd": constraint_feature_dd, "constraint_type_dd": constraint_type_dd, "constraint_value_num": constraint_value_num, | |
| "opt_pop_size_slider": opt_pop_size_slider, "opt_num_gen_slider": opt_num_gen_slider, "opt_run_button": opt_run_button, "opt_reset_button": opt_reset_button, | |
| "opt_plot_output": opt_plot_output, "opt_info_output": opt_info_output, | |
| "moo_dynamic_row": moo_dynamic_row, "moo_plot_x": moo_plot_x, "moo_plot_y": moo_plot_y, "moo_plot_color": moo_plot_color | |
| } | |
| for i in range(MAX_PARAMS_FOR_UI): | |
| components[f'param_row_{i}'] = param_rows[i] | |
| components[f'param_lb_{i}'] = param_lb_inputs[i] | |
| components[f'param_ub_{i}'] = param_ub_inputs[i] | |
| # --- Event Listeners --- | |
| eda_load_button.click( | |
| fn=load_and_eda, | |
| inputs=[eda_file_input, eda_feature_selector, eda_target_selector], | |
| outputs=list(components.values()) | |
| ) | |
| surrogate_build_button.click( | |
| fn=build_surrogate, | |
| inputs=[state_dataframe, state_feature_names, state_target_names, surrogate_model_type, surrogate_poly_degree, surrogate_test_split, | |
| viz_target_selector, viz_feature_selector_1, viz_feature_selector_2, | |
| rf_n_estimators, rf_max_depth, ridge_alpha, | |
| gp_kernel_dd, gp_alpha_slider, gp_restarts_slider], | |
| outputs=list(components.values()) | |
| ) | |
| cv_run_button.click( | |
| fn=run_cross_validation, | |
| inputs=[state_dataframe, state_feature_names, state_target_names, surrogate_model_type, surrogate_poly_degree, cv_type_selector, cv_target_selector, | |
| rf_n_estimators, rf_max_depth, ridge_alpha, | |
| gp_kernel_dd, gp_alpha_slider, gp_restarts_slider], | |
| outputs=list(components.values()) | |
| ) | |
| opt_run_button.click( | |
| fn=run_optimization, | |
| inputs=[state_surrogate_models, state_feature_names, state_dataframe, opt_type_radio, opt_primary_target_selector, opt_secondary_target_selector, | |
| opt_pop_size_slider, opt_num_gen_slider, | |
| constraint_feature_dd, constraint_type_dd, constraint_value_num, | |
| *param_lb_inputs, *param_ub_inputs], | |
| outputs=[components['opt_info_output'], components['opt_plot_output'], components['state_opt_res'], components['moo_dynamic_row'], components['moo_plot_x'], components['moo_plot_y'], components['moo_plot_color']] | |
| ) | |
| opt_reset_button.click( | |
| fn=reset_bounds, | |
| inputs=[state_dataframe, state_feature_names], | |
| outputs=[*param_lb_inputs, *param_ub_inputs] | |
| ) | |
| # --- Interactive UI Logic --- | |
| def toggle_hparam_visibility(model_type): | |
| return { | |
| rf_hparams_row: gr.update(visible=model_type == 'RandomForest'), | |
| ridge_hparams_row: gr.update(visible=model_type == 'Ridge'), | |
| gp_hparams_row: gr.update(visible=model_type == 'GaussianProcess') | |
| } | |
| surrogate_model_type.change(toggle_hparam_visibility, inputs=surrogate_model_type, outputs=[rf_hparams_row, ridge_hparams_row, gp_hparams_row]) | |
| opt_type_radio.change(lambda x: gr.update(visible=x == 'Multi-Objective'), inputs=opt_type_radio, outputs=mo_row) | |
| # Listeners for dynamic M-O plot | |
| moo_plot_inputs = [state_opt_res, state_feature_names, moo_plot_x, moo_plot_y, moo_plot_color] | |
| moo_plot_x.change(update_optimization_plot, inputs=moo_plot_inputs, outputs=opt_plot_output) | |
| moo_plot_y.change(update_optimization_plot, inputs=moo_plot_inputs, outputs=opt_plot_output) | |
| moo_plot_color.change(update_optimization_plot, inputs=moo_plot_inputs, outputs=opt_plot_output) | |
| # 6. LAUNCH THE APP | |
| if __name__ == "__main__": | |
| demo.launch(debug=True, share=False) |