# [Gradio 基本UI] import gradio as gr # [數據處理/科學計算] import numpy as np import pandas as pd import itertools # [DoE設計/取樣法] from pyDOE3 import lhs, sobol_sequence, halton_sequence, random_uniform from pyDOE3.doe_optimal.algorithms import detmax # [可視化/統計分析] from ydata_profiling import ProfileReport import plotly.express as px import plotly.graph_objects as go import matplotlib.pyplot as plt # [AI/ML建模] from sklearn.model_selection import train_test_split, cross_val_score, KFold from sklearn.linear_model import LassoCV, RidgeCV, ElasticNetCV from sklearn.gaussian_process import GaussianProcessRegressor from sklearn.gaussian_process.kernels import RBF, WhiteKernel from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error, make_scorer from sklearn.multioutput import MultiOutputRegressor from flaml import AutoML import shap # [雜項工具/暫存檔] import tempfile import warnings warnings.filterwarnings("ignore") import io import os import pickle # [互動頁面樣式] custom_css = """ /* 主卡片 */ /* 用於主要內容區塊(如自動摘要卡片、資訊框)美化,圓角+陰影 */ .gr-card { background: #f7fafd; border-radius: 18px; box-shadow: 0 2px 8px #0002; } /* 按鈕樣式 */ /* 主要操作按鈕樣式:漸層、圓角、陰影、字體放大,滑鼠懸停有亮度與色調變化 */ .main-btn { font-size: 1.14em; padding: 10px 28px 11px 28px; border-radius: 999px; margin: 14px 0 8px 0; background: linear-gradient(90deg, #5b8cff, #76e7ff 70%); color: #fff; font-weight: 600; box-shadow: 0 2px 12px #3976d855; border: none; transition: .2s; } .main-btn:hover { filter: brightness(1.08); box-shadow: 0 2px 18px #5b8cff33; background: linear-gradient(90deg, #2259c9 55%, #4fa7d9); } /* 全平台字體 */ /* 全域字型套用 Noto Sans JP(優先日系風格),備用 Segoe UI 和 Arial,維持專案一致性 */ .gradio-container { font-family: 'Noto Sans JP', 'Segoe UI', Arial, sans-serif; } /* 區塊標題 */ /* 區塊或章節標題顯眼化,藍色、字重加粗 */ .section-title { font-size: 1.26em; font-weight: 700; color: #3976d8; margin-bottom: 6px; } /* Tab & Row 區塊間距 */ /* Tab、列區塊加上下間距,避免UI太擁擠 */ .tab-pane, .gr-row { padding: 8px 0; } /* 推薦小卡 */ /* 固定右下角推薦訊息小卡,用於快速提醒或建議,帶有柔和背景、陰影 */ #recommend-card { position: fixed; right: 28px; bottom: 28px; max-width: 360px; background: #f8fbffde; border-radius: 13px; box-shadow: 0 2px 14px #5ab2fa29; border-left: 5px solid #88a3e6; padding: 12px 18px 10px 14px; font-size: 1.07em; z-index: 9999; color: #285078; } /* 分隔線 */ /* 水平線設計:加厚、色彩淡藍灰,分隔內容用 */ hr { border: 0; border-bottom: 2.5px solid #e4e8f0; margin: 28px 0 22px 0; } /* Accordion 動畫 */ /* 摺疊區塊 summary 動畫與配色,展開時加上陰影強調 */ .accordion > summary { transition: .25s; background: #f4f8ff; } .accordion[open] > summary { background: #cfeaff; } .accordion[open] { box-shadow: 0 8px 24px #1ca7ec25; } /* Tab高亮 */ /* 當前選中 Tab 標籤高亮顯示,底色、字色、粗體 */ div[role="tab"][aria-selected="true"] { background: #e3f1ff !important; font-weight: bold; color: #2675ff; } /* 頁腳 */ /* Footer字體顏色與大小(淡灰、較小字) */ #footer { color: #888; font-size: 0.98em; } """ # = 產生HTML卡片說明 = def make_card(title, tips): return f"""
{title}
""" # = 根據圖形類型產生分圖說明卡片 = def get_viz_desc(name): idx = { "DoE Main": ("DoE設計分布圖", [ "檢查設計點分布是否均勻覆蓋整個空間", "若集中/離散,代表參數區間或設計法可優化", "高維會以降維(PCA)檢視主變異結構" ]) } return make_card(*idx.get(name, ("", []))) # ======================== 主要功能函式 ======================== # 1️⃣ 標準DoE設計分布 # = 檢查輸入參數列是否有效 = def is_valid_row(row): if not isinstance(row, (list, tuple)) or len(row) < 4: return False try: if str(row[0]).strip() == "": return False float(row[1]) float(row[2]) float(row[3]) return True except Exception: return False # = 產生指定類型的標準DoE設計點(LHS/Sobol/Halton/Uniform)= def gen_design(design_type, n_params, n_samples, param_lows, param_highs, param_steps, seed): if seed is not None and str(seed).strip() != "" and int(seed) != 0: my_seed = int(seed) else: my_seed = None if design_type == "LHS": design = lhs(n_params, samples=n_samples, criterion='maximin',random_state=my_seed) elif design_type == "Sobol": design = sobol_sequence(n=n_samples, d=n_params, scramble=True, seed=seed) elif design_type == "Halton": design = halton_sequence(num_points=n_samples, dimension=n_params) elif design_type == "Uniform": design = random_uniform(num_points=n_samples, dimension=n_params) elif design_type == "D-optimal": # Generate levels for every experimental variables combinations = [] for min_val, max_val, step_val in zip(param_lows,param_highs,param_steps): levels_list = list(np.arange(min_val, max_val+step_val, step_val)) combinations.append(levels_list) candidates = np.array(list(itertools.product(*combinations))) # Calculate D-optimal and find n samples using detmax design = detmax(candidates=candidates,n_points=n_samples,degree=n_params,criterion="D",max_iter = 200) return pd.DataFrame(design) #this method doesn't need re-sacling real_samples = np.zeros_like(design) for idx, (low, high, step) in enumerate(zip(param_lows, param_highs, param_steps)): real_samples[:, idx] = design[:, idx] * (high - low) + low if step > 0: real_samples[:, idx] = np.round((real_samples[:, idx] - low) / step) * step + low else: decimals = str(step)[::-1].find('.') real_samples[:, idx] = np.round(real_samples[:, idx], decimals) real_samples[:, idx] = np.clip(real_samples[:, idx], low, high) return pd.DataFrame(real_samples) # = 2D參數分布圖(Plotly)= def plot_scatter_2d(df, title): fig = px.scatter(df, x=df.columns[0], y=df.columns[1], title=title) return fig # = 3D參數分布圖(Plotly)= def plot_scatter_3d(df, title): fig = px.scatter_3d(df, x=df.columns[0], y=df.columns[1], z=df.columns[2], title=title) return fig # = 多維參數成對散點圖(Plotly)= def plot_pairplot(df, title): return px.scatter_matrix(df, title=title) # = PCA主成分降維分布圖(Plotly)= def plot_pca(df, title): X = df.values pca = PCA(n_components=2) X_pca = pca.fit_transform(X) df_pca = pd.DataFrame(X_pca, columns=['PCA1', 'PCA2']) return px.scatter(df_pca, x='PCA1', y='PCA2', title=title + " (PCA降維)") # = 依參數設定產生所有主流程設計法(四種)並比較分布 = def compare_all_designs(param_table, n_samples, seed): all_types = ["LHS", "Sobol", "Halton", "Uniform","D-optimal"] outs = [] if isinstance(param_table, pd.DataFrame): param_table = param_table.values.tolist() param_names, param_lows, param_highs, param_steps = [], [], [], [] for row in param_table: if not is_valid_row(row): continue try: param_names.append(str(row[0]).strip()) param_lows.append(float(row[1])) param_highs.append(float(row[2])) param_steps.append(float(row[3])) except Exception: continue n_params = len(param_names) if n_params == 0: return pd.DataFrame({"提醒": ["請正確輸入至少一列參數"]}), None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None for des in all_types: df = gen_design(des, n_params, int(n_samples), param_lows, param_highs, param_steps, seed) df.columns = param_names # 主分布圖 if n_params == 2: mainfig = plot_scatter_2d(df, des + " 分布圖") elif n_params == 3: mainfig = plot_scatter_3d(df, des + " 分布圖") elif n_params >= 4 and n_params <= 8: mainfig = plot_pairplot(df, des + " Pairplot") else: mainfig = plot_pca(df, des + " PCA") with tempfile.NamedTemporaryFile(delete=False, suffix=f'_{des}_design.csv', mode='w', encoding='utf-8-sig') as tmpfile: df.to_csv(tmpfile, index=False) outs.extend([df, mainfig, tmpfile.name, get_viz_desc("DoE Main")]) return outs # 2️⃣ 數據可視化/統計分析 def generate_profile_report(csv_file): # Read the uploaded CSV file df = pd.read_csv(csv_file) # Generate the profiling report profile = ProfileReport( df, title="Data Profiling Report", explorative=True, minimal=False ) # Create a temporary file to save the HTML report report_path = os.path.join(tempfile.gettempdir(), 'profiling_report.html') profile.to_file(report_path) # Read HTML content for preview with open(report_path, 'r', encoding='utf-8') as f: html_content = f.read() # Create iframe for preview iframe_html = f""" """ return iframe_html, report_path # 3️⃣ AI建模/特徵重要性 # Global variable to store data current_data = None trained_models = {} X_train_global = None X_test_global = None feature_names_global = None y_train_global = None y_test_global = None search_range = None is_multioutput = False y_column_all = None def load_csv(file): """Load CSV file and return dataframe""" global current_data if file is None: return None, "Please upload a CSV file", None, None try: current_data = pd.read_csv(file.name) columns = current_data.columns.tolist() preview = current_data.head(5).to_html() return ( gr.update(choices=columns, value=None), gr.update(choices=columns, value=None), f"✓ File loaded successfully! Shape: {current_data.shape}", preview ) except Exception as e: return None, None, f"Error loading file: {str(e)}", None def _create_model(method, random_state, time_budget, X_train, y_train, is_multioutput=False): """Helper function to create and train a model""" estimator_map = { "Random Forest": "rf", "XGBoost": "xgboost", "LightGBM": "lgbm", "Extra Trees": "extra_tree", "CatBoost": "catboost" } if method == "Lasso": model = LassoCV(cv=5, random_state=random_state) elif method == "Ridge": model = RidgeCV(cv=5) elif method == "ElasticNet": model = ElasticNetCV(cv=5, random_state=random_state) elif method == "Gaussian Process": kernel = RBF() + WhiteKernel() model = GaussianProcessRegressor(kernel=kernel, random_state=random_state) else: # FLAML AutoML methods model = AutoML() settings = { "time_budget": time_budget, # total time in seconds "metric": 'rmse', "task": 'regression', "estimator_list":[estimator_map[method]], "verbose":0 } # Wrap in MultiOutputRegressor if needed if is_multioutput: model = MultiOutputRegressor(model) if method in list(estimator_map): model.fit(X_train, y_train, **settings) else: model.fit(X_train, y_train) return model def train_models(x_cols, y_col, methods_sklearn, methods_automl, validation_method, test_size, n_folds, random_state, time_budget): """Train selected models and compare performance""" global current_data, trained_models, X_train_global, X_test_global, feature_names_global, y_train_global, y_test_global, is_multioutput if current_data is None: return "Please load a CSV file first", None, None if not x_cols or not y_col: return "Please select X and Y variables", None, None # Combine both method lists methods = (methods_sklearn or []) + (methods_automl or []) if not methods: return "Please select at least one ML method", None, None try: # Prepare data X = current_data[x_cols].values # Handle single or multiple outputs if isinstance(y_col, list): y = current_data[y_col].values is_multioutput = len(y_col) > 1 y_col_names = y_col if is_multioutput else [y_col[0]] else: y = current_data[[y_col]].values if isinstance(y_col, str) else current_data[y_col].values is_multioutput = y.shape[1] > 1 if len(y.shape) > 1 else False y_col_names = [y_col] if not is_multioutput else [f"Output_{i+1}" for i in range(y.shape[1])] # Flatten y if single output if not is_multioutput and len(y.shape) > 1: y = y.ravel() feature_names_global = x_cols results = [] trained_models = {} # Choose validation method if validation_method == "Train-Test Split": X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=test_size/100, random_state=random_state ) # Store for SHAP analysis and Bayesian optimization X_train_global = X_train X_test_global = X_test y_train_global = y_train y_test_global = y_test # Train each selected model with train-test split for method in methods: try: model = _create_model(method, random_state, time_budget, X_train, y_train, is_multioutput) # Make predictions y_pred = model.predict(X_test) # Calculate metrics if is_multioutput: # Calculate metrics for each output separately result_dict = {"Method": method} for i, output_name in enumerate(y_col_names): mse_i = mean_squared_error(y_test[:, i], y_pred[:, i]) rmse_i = np.sqrt(mse_i) r2_i = r2_score(y_test[:, i], y_pred[:, i]) result_dict[f"RMSE_{output_name}"] = f"{rmse_i:.4f}" result_dict[f"R²_{output_name}"] = f"{r2_i:.4f}" results.append(result_dict) else: mse = mean_squared_error(y_test, y_pred) rmse = np.sqrt(mse) r2 = r2_score(y_test, y_pred) results.append({ "Method": method, "RMSE": f"{rmse:.4f}", "R²": f"{r2:.4f}" }) trained_models[method] = model except Exception as e: if is_multioutput: result_dict = {"Method": method} for output_name in y_col_names: result_dict[f"RMSE_{output_name}"] = "Error" result_dict[f"R²_{output_name}"] = "Error" results.append(result_dict) else: results.append({ "Method": method, "RMSE": "Error", "R²": "Error" }) else: # K-Fold Cross-Validation # Store full dataset for SHAP and BO (use all data for training) X_train_global = X X_test_global = X[:min(100, len(X))] # Sample for SHAP y_train_global = y y_test_global = y[:min(100, len(y))] kfold = KFold(n_splits=n_folds, shuffle=True, random_state=random_state) # Train each selected model with k-fold CV for method in methods: try: model = _create_model(method, random_state, time_budget, X, y, is_multioutput) # Use manual k-fold for evaluation if is_multioutput: result_dict = {"Method": method} for i, output_name in enumerate(y_col_names): fold_mse, fold_r2 = [], [] for train_idx, val_idx in kfold.split(X): X_fold_train, X_fold_val = X[train_idx], X[val_idx] y_fold_train, y_fold_val = y[train_idx], y[val_idx] fold_model = _create_model(method, random_state, time_budget, X_fold_train, y_fold_train, is_multioutput) y_fold_pred = fold_model.predict(X_fold_val) fold_mse.append(mean_squared_error(y_fold_val[:, i], y_fold_pred[:, i])) fold_r2.append(r2_score(y_fold_val[:, i], y_fold_pred[:, i])) cv_mse = np.mean(fold_mse) cv_r2 = np.mean(fold_r2) cv_rmse = np.sqrt(cv_mse) result_dict[f"RMSE_{output_name}"] = f"{cv_rmse:.4f}" result_dict[f"R²_{output_name}"] = f"{cv_r2:.4f}" results.append(result_dict) else: fold_mse, fold_r2 = [], [] for train_idx, val_idx in kfold.split(X): X_fold_train, X_fold_val = X[train_idx], X[val_idx] y_fold_train, y_fold_val = y[train_idx], y[val_idx] fold_model = _create_model(method, random_state, time_budget, X_fold_train, y_fold_train, is_multioutput) y_fold_pred = fold_model.predict(X_fold_val) fold_mse.append(mean_squared_error(y_fold_val, y_fold_pred)) fold_r2.append(r2_score(y_fold_val, y_fold_pred)) cv_mse = np.mean(fold_mse) cv_r2 = np.mean(fold_r2) cv_rmse = np.sqrt(cv_mse) results.append({ "Method": method, "RMSE": f"{cv_rmse:.4f}", "R²": f"{cv_r2:.4f}" }) trained_models[method] = model except Exception as e: if is_multioutput: result_dict = {"Method": method} for output_name in y_col_names: result_dict[f"RMSE_{output_name}"] = "Error" result_dict[f"R²_{output_name}"] = "Error" results.append(result_dict) else: results.append({ "Method": method, "RMSE": "Error", "R²": "Error" }) # Create results dataframe results_df = pd.DataFrame(results) validation_note = f"Train-Test Split (Test: {test_size}%)" if validation_method == "Train-Test Split" else f"K-Fold Cross-Validation (K={n_folds})" output_note = f" (Multi-output: {', '.join(y_col_names)})" if is_multioutput else "" return ( f"✓ Training completed successfully using {validation_note}{output_note}!", results_df ) except Exception as e: return f"Error during training: {str(e)}", None, None def generate_shap_plot(selected_model,y_col,show_features): """Generate SHAP summary plot for selected model""" global trained_models, X_train_global, X_test_global, feature_names_global, is_multioutput if not trained_models: return None, "Please train models first" if selected_model not in trained_models: return None, f"Model '{selected_model}' not found in trained models" if X_test_global is None or feature_names_global is None: return None, "Training data not available" show_features = int(show_features) try: model = trained_models[selected_model] sample_size = min(100, len(X_test_global)) X_sample = X_test_global[:sample_size] if is_multioutput: models = model.estimators_ else: models = [model] num_plots = len(y_col) fig_width = 10 fig_height = num_plots * 6 fig, axes = plt.subplots(num_plots, 1, figsize=(fig_width, fig_height)) for i,model_ in enumerate(models): # Get the actual model for FLAML AutoML if isinstance(model_, AutoML): model_ = model_.model.estimator # Create SHAP explainer based on model type if selected_model in ["Linear Regression", "Lasso", "Ridge", "ElasticNet"]: explainer = shap.LinearExplainer(model_, X_train_global) elif selected_model == "Gaussian Process": # Use Kernel explainer for Gaussian Process explainer = shap.KernelExplainer(model_.predict, shap.sample(X_train_global, 50)) else: # Tree-based models (Random Forest, XGBoost, LightGBM, Extra Trees) try: explainer = shap.TreeExplainer(model_) except: # Fallback to Kernel explainer explainer = shap.KernelExplainer(model_.predict, shap.sample(X_train_global, 50)) shap_v = pd.DataFrame(explainer.shap_values(X_sample)) shap_v.columns = feature_names_global df_v = pd.DataFrame(X_sample) df_v.columns = feature_names_global corr_list = list() for j in feature_names_global: b = np.corrcoef(shap_v[j],df_v[j])[1][0] corr_list.append(b) corr_df = pd.concat([pd.Series(feature_names_global),pd.Series(corr_list)],axis=1).fillna(0) # Make a data frame. Column 1 is the feature, and Column 2 is the correlation coefficient corr_df.columns = ['Variable','Corr'] shap_v_abs = pd.DataFrame(np.abs(shap_v).mean()).reset_index() shap_v_abs.columns = ['Variable','SHAP_abs'] shap_v_abs["SHAP_corr"] = corr_df["Corr"]*shap_v_abs["SHAP_abs"] shap_v_abs["Sign"] = np.where(corr_df['Corr']<0,'red',"#0451c4") shap_v_abs = shap_v_abs.sort_values(by='SHAP_abs',ascending = True) shap_v_abs = shap_v_abs.tail(show_features) colorlist = shap_v_abs['Sign'] if is_multioutput: shap_v_abs.plot.barh(x='Variable',y='SHAP_corr', color = colorlist, ax = axes[i] ,legend=False, fontsize = 12) axes[i].set_xlabel("SHAP Value with correlation", fontsize = 12) axes[i].set_ylabel("Features", fontsize = 12) axes[i].axvline(x=0, color='black', linestyle='--', linewidth=1) axes[i].set_title(y_col[i],fontsize = 16) else: shap_v_abs.plot.barh(x='Variable',y='SHAP_corr', color = colorlist, ax = axes ,legend=False, fontsize = 12) axes.set_xlabel("Feature Impact", fontsize = 12) axes.set_ylabel("Features", fontsize = 12) axes.axvline(x=0, color='black', linestyle='--', linewidth=1) axes.set_title(y_col[i],fontsize = 16) plt.tight_layout() plt.close() return fig, f"✓ SHAP plot generated successfully for {selected_model}" except Exception as e: return None, f"Error generating SHAP plot: {str(e)}" def save_model_pickle(selected_model,y_col): """ Save the trained model to a pickle file for download """ global trained_models, y_column_all, is_multioutput if is_multioutput: model = trained_models[selected_model].estimators_[y_column_all.index(y_col)] else: model = trained_models[selected_model] try: # Save to temporary file file_name = f"{selected_model}_{y_col}.pkl" model_path = os.path.join(tempfile.gettempdir(), file_name) with open(model_path, 'wb') as f: pickle.dump(model, f) info = f""" ✅ **Model saved successfully!** - Format: Pickle (.pkl) - File: {file_name} - Size: {os.path.getsize(model_path) / 1024:.2f} KB """ return model_path, info except Exception as e: return None, f"Error saving model: {str(e)}" # 4️⃣ AI自動推薦新實驗點 def create_range_dataframe(): """Create initial dataframe for variable ranges""" global feature_names_global, current_data if feature_names_global is None or len(feature_names_global) == 0: return pd.DataFrame(columns=["Variable", "Minimum", "Maximum", "Interval"]) # Create dataframe with feature names and default interval of 1 df = pd.DataFrame({ "Variable": feature_names_global, "Maximum": [current_data[name].max() for name in feature_names_global], "Minimum": [current_data[name].min() for name in feature_names_global], "Interval": [1 for _ in feature_names_global] }) return df def run_experiment_recommendation(selected_model, strategy_f, strategy_b, n_points, target_value, range_df): """Run experiment recommendation to find optimal input values""" global trained_models, feature_names_global, is_multioutput, search_range if not trained_models: return None, "Please train models first", None if selected_model not in trained_models: return None, f"Model '{selected_model}' not found", None if feature_names_global is None: return None, "Feature names not available", None if is_multioutput: return None, "Experiment recommendation is not supported for multi-output models. Please select a single output variable.", None search_range = range_df model = trained_models[selected_model] is_gp = (selected_model == "Gaussian Process") # Parse range values (min, max, interval for each feature) n_features = len(feature_names_global) # Generate all possible candidates using uniform n_samples = 10000 #generate 10000 candidates design = random_uniform(num_points=n_samples, dimension=n_features) real_samples = np.zeros_like(design) param_lows = list(range_df["Minimum"]) param_highs = list(range_df["Maximum"]) param_steps = list(range_df["Interval"]) for idx, (low, high, step) in enumerate(zip(param_lows, param_highs, param_steps)): real_samples[:, idx] = design[:, idx] * (high - low) + low if step > 0: real_samples[:, idx] = np.round((real_samples[:, idx] - low) / step) * step + low else: decimals = str(step)[::-1].find('.') real_samples[:, idx] = np.round(real_samples[:, idx], decimals) real_samples[:, idx] = np.clip(real_samples[:, idx], low, high) grid_combinations = pd.DataFrame(real_samples) # Bayesian Approach (Gaussian Process only) if is_gp and strategy_b in ["Maximum(EI)", "Minimum(EI)", "Maximum(PI)", "Minimum(PI)", "Assigned Value(PI)"]: from scipy.stats import norm # Get predictions with uncertainty y_pred, y_std = model.predict(grid_combinations, return_std=True) # Current best observation if strategy_b.startswith("Maximum"): current_best = np.max(y_pred) maximize = True elif strategy_b.startswith("Minimum"): current_best = np.min(y_pred) maximize = False else: # Assigned Value current_best = float(target_value) maximize = None # Calculate acquisition function if "EI" in strategy_b: # Expected Improvement if maximize: improvement = y_pred - current_best else: improvement = current_best - y_pred Z = improvement / (y_std + 1e-9) ei = improvement * norm.cdf(Z) + y_std * norm.pdf(Z) ei[y_std == 0.0] = 0.0 acquisition_values = ei else: # Probability of Improvement (PI) if maximize: improvement = y_pred - current_best else: improvement = current_best - y_pred Z = improvement / (y_std + 1e-9) pi = norm.cdf(Z) acquisition_values = pi # Select top n_points based on acquisition function top_indices = np.argsort(acquisition_values)[-n_points:][::-1] recommended_X = grid_combinations.loc[top_indices] recommended_y = y_pred[top_indices] recommended_std = y_std[top_indices] recommended_acq = acquisition_values[top_indices] # Create results dataframe results_df = recommended_X results_df.columns = feature_names_global results_df["Predicted Y"] = recommended_y results_df["Std Dev"] = recommended_std results_df["Acquisition"] = recommended_acq # Frequentist Approach (for other models) else: # Get predictions y_pred = model.predict(grid_combinations) if strategy_f == "Maximum": # Find points with highest predicted values top_indices = np.argsort(y_pred)[-n_points:][::-1] elif strategy_f == "Minimum": # Find points with lowest predicted values top_indices = np.argsort(y_pred)[:n_points] else: # Assigned Value # Find points closest to target value try: target = float(target_value) distances = np.abs(y_pred - target) top_indices = np.argsort(distances)[:n_points] except ValueError: return None, "Please enter a valid target value for 'Assigned Value' strategy_f", None recommended_X = grid_combinations.loc[top_indices] results_df.columns = feature_names_global recommended_y = y_pred[top_indices] # Create results dataframe results_df = recommended_X results_df["Predicted Y"] = recommended_y return results_df # ======================== Gradio 多分頁主UI ======================== with gr.Blocks(css=custom_css) as demo: gr.Markdown("## AI化實驗設計與數據分析平台 ") with gr.Tabs(): # 1️⃣ 標準DoE設計分布 with gr.Tab("1️⃣ 標準DoE "): gr.Markdown(""" ### 🧪 標準DoE設計分布 - 支援自動產生參數空間內的多種經典DoE設計法(LHS, Sobol, Halton, Uniform) - 可視覺化設計點分布、產生對應的設計參數表 - 支援下載CSV檔、表格內容可複製 **如何使用:** - 1️⃣ 填寫參數名稱、範圍及步進 - 2️⃣ 設定要產生的組數與亂數種子(可選) - 3️⃣ 點選「產生設計+分布圖」 - 4️⃣ 下方各分頁可檢視不同設計法的結果、分布圖與自動摘要 **注意事項:** - 所有參數名稱需唯一、不得重複 - 組數愈大,運算與繪圖所需時間會增加 - 請檢查參數範圍、步進格式是否正確 """) with gr.Row(): with gr.Column(scale=1, min_width=240): with gr.Accordion("參數設定", open=True): param_table = gr.Dataframe( headers=["名稱", "最小值", "最大值", "間隔(step)"], datatype=["str", "number", "number", "number"], row_count=(3, "dynamic"), col_count=(4, "fixed"), value=[["A", 10, 20, 2], ["B", 100, 200, 25], ["C", 1, 2, 0.5]], label="參數設定" ) n_samples = gr.Number(label="組數", value=8, precision=0) seed = gr.Number(label="亂數種子(留空或0為隨機)", value=42, precision=0) btn = gr.Button("🪄 產生設計與分布圖", elem_classes=["main-btn"]) with gr.Column(scale=2): with gr.Accordion("分布結果/圖表/摘要", open=True): tabs = [] for name in ["LHS", "Sobol", "Halton", "Uniform","D-optimal"]: with gr.Tab(name): df = gr.Dataframe(label=f"{name} 設計點表格") fig = gr.Plot(label=f"{name} 設計分布") csv = gr.File(label="下載CSV📥") desc = gr.Markdown() summary = gr.Markdown() tabs.extend([df, fig, csv, desc]) btn.click(compare_all_designs, inputs=[param_table, n_samples, seed], outputs=tabs) # 2️⃣ 數據可視化/統計分析 with gr.Tab("2️⃣ 數據可視化/統計分析"): gr.Markdown( """ ### 📊 數據可視化/統計分析 - 全方位報告: 自動計算描述性統計、相關係數、缺失值分析及重複資料。 - 互動視覺化: 生成包含直方圖、散佈圖與關聯矩陣的互動式 HTML 報告。 - 異常偵測: 自動標示資料問題,如:高相關性、常數值、極端值或資料不平衡。 **如何使用:** - 1️⃣ 上傳資料CSV,選擇要產生的視覺化圖種類 - 2️⃣ 一鍵生成報告 - 3️⃣ 檢閱互動式報告 """ ) with gr.Row(): with gr.Column(): csv_input = gr.File( label="上傳資料CSV", file_types=[".csv"], type="filepath" ) generate_btn = gr.Button( "🚀 生成報告", variant="primary", size="lg" ) download_output = gr.File(label="下載報告(html檔)") gr.Markdown("👁️預覽報告") preview_output = gr.HTML(label="預覽報告") # Connect button to function generate_btn.click( fn=generate_profile_report, inputs=csv_input, outputs=[preview_output, download_output] ) # 3️⃣ AI建模/特徵重要性 with gr.Tab("3️⃣ AI建模/特徵重要性"): gr.Markdown(""" ### 🧠 AI建模/特徵重要性/SHAP - 支援多種基礎統計回歸模型、進階AI回歸模型,自動化訓練與模型評估 - 一鍵產生預測結果、模型效能指標、特徵重要性圖 - 輕鬆檢視哪些參數對y預測最關鍵 **如何使用:** - 1️⃣ 上傳實驗數據CSV - 2️⃣ 選擇變數x欄位,選擇目標y欄位(可多選) - 3️⃣ 勾選需比較的AI模型(可多選) - 基礎統計回歸模型:適合小數據,計算時間短 - 進階AI回歸模型(AutoML):適合大數據,計算時間長 - 4️⃣ 選擇精度檢證方法 - Train-Test Split:適合大數據、進階AI回歸模型 - K-Fold Cross-Validation:適合小數據、基礎統計回歸模型 - 5️⃣ 點選「一鍵訓練」,比較建模結果 - 6️⃣ 選擇一個模型,點選「重要度分析」計算特徵重要性 **注意事項:** - 資料需為數值型且無遺漏值 - 資料量太小時,部分模型可能無法有效學習 """) with gr.Row(): with gr.Column(scale=1): gr.Markdown("### 1️⃣ 上傳實驗數據CSV") file_input = gr.File(label="Upload CSV File", file_types=[".csv"]) load_status = gr.Textbox(label="Status", interactive=False) data_preview = gr.HTML(label="Data Preview") gr.Markdown("### 2️⃣ 選擇變數x欄位,選擇目標y欄位(可多選)") x_columns = gr.Dropdown(label="Select X Variables (Features)", multiselect=True, choices=[]) y_column = gr.Dropdown(label="Select Y Variable (Target)", multiselect=True, choices=[]) gr.Markdown("### 3️⃣ 勾選需比較的AI模型(可多選)") gr.Markdown("**基礎統計模型:**") method_choices_1 = [ "Lasso", "Ridge", "ElasticNet", "Gaussian Process" ] methods_sklearn = gr.CheckboxGroup( label="適合小數據,計算時間短", choices=method_choices_1, value=[] ) gr.Markdown("**進階AI回歸模型(AutoML):**") method_choices_2 = [ "Random Forest", "XGBoost", "LightGBM", "Extra Trees", "CatBoost" ] methods_automl = gr.CheckboxGroup( label="適合大數據,計算時間長", choices=method_choices_2, value=[] ) gr.Markdown("### 4️⃣ 選擇精度檢證方法") validation_method = gr.Radio( choices=["Train-Test Split", "K-Fold Cross-Validation"], value="Train-Test Split" ) with gr.Row(): test_size = gr.Slider( label="Test Size (%)", minimum=10, maximum=50, value=20, step=5, visible=True ) n_folds = gr.Slider( label="Number of Folds (K)", minimum=2, maximum=10, value=5, step=1, visible=False ) with gr.Row(): random_state = gr.Number( label="Random State", value=42, precision=0 ) time_budget = gr.Slider( label="Time Budget for AutoML (seconds)", minimum=10, maximum=300, value=60, step=10 ) train_button = gr.Button("🚀 一鍵訓練", variant="primary", size="lg") with gr.Column(scale=1): gr.Markdown("### 5️⃣ 建模結果比較") train_status = gr.Textbox(label="Training Status", interactive=False) results_table = gr.Dataframe(label="Performance Comparison") gr.Markdown("### 6️⃣ 特徵重要性分析") with gr.Row(): shap_model_select = gr.Dropdown( label="選擇一個模型計算特徵重要性", choices=[], interactive=True ) show_features = gr.Textbox( label="想查看的前 K 個重要特徵", value="10" ) shap_button = gr.Button("📊 重要性分析", variant="primary") shap_status = gr.Textbox(label="Status", interactive=False) shap_plot = gr.Plot(label="特徵重要性圖") gr.Markdown("### 7️⃣ 下載預測模型") with gr.Row(): download_model_select = gr.Dropdown( label="選擇一個模型要下載的模型", choices=[], interactive=True ) y_col_select = gr.Dropdown( label="選擇目標y欄位", choices=[], interactive=True ) save_pickle_btn = gr.Button("🗃️打包模型", variant="primary") model_pickle = gr.File(label="📥下載模型") pickle_info = gr.Textbox(label="Status", lines=5 ,interactive=False) save_pickle_btn.click( fn=save_model_pickle, inputs=[download_model_select,y_col_select], outputs=[model_pickle, pickle_info] ) # 4️⃣ AI自動推薦新實驗點 with gr.Tab("4️⃣ AI自動推薦新實驗點 (WIP)"): with gr.Row(): with gr.Column(scale=1): gr.Markdown("### 1️⃣ Model Selection") er_model_select = gr.Dropdown( label="Select Model for Recommendation", choices=[], interactive=True ) gr.Markdown("### 2️⃣ Choose One target") target_select = gr.Dropdown( label="Experiment recommendation is not supported for multi-output models. Please select a single output variable.", choices=[], interactive=True ) gr.Markdown("### 3️⃣ Recommendation Strategy") recommend_approach = gr.Radio( label="Select Recommendation Approach", choices=["Frequentist", "Bayesian"], value="Frequentist", info="Bayesian approach only works with Gaussian Process", interactive=False ) with gr.Row(): strategy_select_b = gr.Radio( label="Select Strategy(Bayesian)", choices=[ "Maximum(EI)", "Minimum(EI)", "Maximum(PI)", "Minimum(PI)", "Assigned Value(PI)" ], value="Maximum(EI)", interactive=True, visible=False ) strategy_select_f = gr.Radio( label="Select Strategy(Frequentist)", choices=[ "Maximum", "Minimum", "Assigned Value" ], value="Maximum", interactive=True ) with gr.Row(): n_recommendations = gr.Slider( label="Number of Recommendation Points", minimum=1, maximum=50, value=5, step=1 ) target_value_input = gr.Textbox( label="Target Value (for 'Assigned Value' strategies)", value="0", placeholder="Enter target Y value" ) gr.Markdown("### 4️⃣ Variable Ranges") gr.Markdown("*Edit the table below to specify ranges for each variable:*") range_dataframe = gr.Dataframe( label="Variable Ranges", headers=["Variable", "Minimum", "Maximum", "Interval"], datatype=["str", "number", "number", "number"], col_count=(4, "fixed"), interactive=True, value=pd.DataFrame(columns=["Variable", "Minimum", "Maximum", "Interval"]) ) recommend_button = gr.Button("🎯 Generate Recommendations", variant="primary", size="lg") with gr.Column(scale=1): gr.Markdown("### 5️⃣ Recommendation Results") er_results_table = gr.Dataframe(label="Recommended Experiments") gr.Markdown("### 6️⃣ Recommendation Reason") recom_shap_status = gr.Textbox(label="SHAP Status", interactive=False) # Event handlers file_input.change( fn=load_csv, inputs=[file_input], outputs=[x_columns, y_column, load_status, data_preview] ) def toggle_selection_inputs(method): """Toggle visibility of validation method inputs""" if method == "Train-Test Split": return gr.update(visible=True), gr.update(visible=False) elif method == "Frequentist": return gr.update(visible=True), gr.update(visible=False) else: return gr.update(visible=False), gr.update(visible=True) #validation toggle validation_method.change( fn=toggle_selection_inputs, inputs=[validation_method], outputs=[test_size, n_folds] ) #recommendation strategy toggle recommend_approach.change( fn=toggle_selection_inputs, inputs=[recommend_approach], outputs=[strategy_select_f, strategy_select_b] ) #recommendation strategy restrictions def bo_restriction(select_model): """Make sure only GP can use Bayeisan approach""" if select_model == "Gaussian Process": return gr.update(interactive=True) else: return gr.update(value="Frequentist",interactive=False) er_model_select.change( fn=bo_restriction, inputs=[er_model_select], outputs=[recommend_approach] ) #Update SHAP and recommendation model dropdowns with trained model names def update_dropdowns(status, results): if results is not None and not results.empty: model_names = results['Method'].tolist() return ( gr.update(choices=model_names, value=model_names[0] if model_names else None), gr.update(choices=model_names, value=model_names[0] if model_names else None), gr.update(choices=model_names, value=model_names[0] if model_names else None) ) return gr.update(choices=[], value=None) , gr.update(choices=[], value=None), gr.update(choices=[], value=None) def update_dropdowns_target(y_col): if y_col is not None: target_names = y_col return ( gr.update(choices=target_names, value=target_names[0] if target_names else None), gr.update(choices=target_names, value=target_names[0] if target_names else None) ) return gr.update(choices=[], value=None), gr.update(choices=[], value=None) def update_range_inputs_er(): """Update range input fields for experiment recommendation""" global feature_names_global if feature_names_global is None: return [gr.update(visible=False)] * 30 updates = [] n_features = len(feature_names_global) for i in range(10): if i < n_features: updates.append(gr.update(visible=True, label=f"{feature_names_global[i]} - Min")) updates.append(gr.update(visible=True, label=f"{feature_names_global[i]} - Max")) updates.append(gr.update(visible=True, label=f"{feature_names_global[i]} - Interval")) else: updates.append(gr.update(visible=False)) updates.append(gr.update(visible=False)) updates.append(gr.update(visible=False)) return updates #model training train_button.click( fn=train_models, inputs=[x_columns, y_column, methods_sklearn, methods_automl, validation_method, test_size, n_folds, random_state, time_budget], outputs=[train_status, results_table] ).then( fn=update_dropdowns, inputs=[train_status, results_table], outputs=[shap_model_select, download_model_select, er_model_select] ).then( fn=create_range_dataframe, outputs=[range_dataframe] ).then( fn=update_dropdowns_target, inputs=[y_column], outputs=[target_select,y_col_select] ) #shap calculation shap_button.click( fn=generate_shap_plot, inputs=[shap_model_select,y_column,show_features], outputs=[shap_plot, shap_status] ) recommend_button.click( fn=run_experiment_recommendation, inputs=[er_model_select, strategy_select_f, strategy_select_b, n_recommendations, target_value_input, range_dataframe], outputs=[er_results_table] ) gr.Markdown("") demo.launch()