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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import numpy as np
|
| 4 |
+
import matplotlib.pyplot as plt
|
| 5 |
+
import seaborn as sns
|
| 6 |
+
from sklearn.model_selection import train_test_split
|
| 7 |
+
from sklearn.preprocessing import StandardScaler
|
| 8 |
+
from sklearn.tree import DecisionTreeClassifier
|
| 9 |
+
from sklearn.svm import SVC
|
| 10 |
+
import xgboost as xgb
|
| 11 |
+
import statsmodels.api as sm
|
| 12 |
+
from sklearn.metrics import confusion_matrix, classification_report, roc_auc_score, accuracy_score
|
| 13 |
+
import warnings
|
| 14 |
+
import json
|
| 15 |
+
|
| 16 |
+
# --- 初始設定與資料載入 ---
|
| 17 |
+
warnings.filterwarnings("ignore", category=UserWarning)
|
| 18 |
+
warnings.filterwarnings("ignore", category=FutureWarning)
|
| 19 |
+
plt.rcParams['font.family'] = ['Microsoft JhengHei']
|
| 20 |
+
plt.rcParams['axes.unicode_minus'] = False
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
# 參考 gemini 的建議,再來調整
|
| 24 |
+
|
| 25 |
+
def load_data():
|
| 26 |
+
"""
|
| 27 |
+
載入並對資料進行固定的預處理。
|
| 28 |
+
此函式只在應用程式啟動時執行一次。
|
| 29 |
+
"""
|
| 30 |
+
df = pd.read_csv('sampled_data.csv')
|
| 31 |
+
df_processed = df.copy()
|
| 32 |
+
df_processed = df_processed.drop('id', axis=1)
|
| 33 |
+
df_processed['Gender'] = df_processed['Gender'].apply(lambda x: 1 if x == 'Male' else 0)
|
| 34 |
+
age_mapping = {'< 1 Year': 0, '1-2 Year': 1, '> 2 Years': 2}
|
| 35 |
+
df_processed['Vehicle_Age'] = df_processed['Vehicle_Age'].map(age_mapping)
|
| 36 |
+
df_processed['Vehicle_Damage'] = df_processed['Vehicle_Damage'].apply(lambda x: 1 if x == 'Yes' else 0)
|
| 37 |
+
return df, df_processed
|
| 38 |
+
|
| 39 |
+
df_original, df_processed = load_data()
|
| 40 |
+
ALL_FEATURES = [col for col in df_processed.columns if col != 'Response']
|
| 41 |
+
NUMERICAL_FEATURES = [f for f in df_original.select_dtypes(include=np.number).columns.tolist() if f in ALL_FEATURES]
|
| 42 |
+
|
| 43 |
+
# --- EDA 相關函式 ---
|
| 44 |
+
def update_eda_section(selected_features):
|
| 45 |
+
if not selected_features:
|
| 46 |
+
return pd.DataFrame(), pd.DataFrame(), gr.update(choices=[], value=None), None
|
| 47 |
+
stats = df_processed[selected_features].describe().T.reset_index().rename(columns={'index': 'Feature'})
|
| 48 |
+
corrs = df_processed[selected_features + ['Response']].corr(numeric_only=True)['Response'].drop('Response').to_frame().reset_index()
|
| 49 |
+
corrs.columns = ['Feature', 'Correlation with Response']
|
| 50 |
+
first_feature_plot = generate_feature_plot(selected_features[0])
|
| 51 |
+
plot_selector_update = gr.update(choices=selected_features, value=selected_features[0])
|
| 52 |
+
return stats, corrs, plot_selector_update, first_feature_plot
|
| 53 |
+
|
| 54 |
+
def generate_feature_plot(feature):
|
| 55 |
+
if not feature: return None
|
| 56 |
+
fig, ax = plt.subplots()
|
| 57 |
+
if feature in NUMERICAL_FEATURES:
|
| 58 |
+
sns.histplot(data=df_processed, x=feature, hue='Response', kde=True, ax=ax, palette='viridis', multiple="stack")
|
| 59 |
+
ax.set_title(f'"{feature}" 的直方圖 (依 Response 分色)')
|
| 60 |
+
else:
|
| 61 |
+
sns.countplot(data=df_processed, x=feature, hue='Response', ax=ax, palette='viridis')
|
| 62 |
+
ax.set_title(f'"{feature}" 的計數長條圖 (依 Response 分色)')
|
| 63 |
+
plt.tight_layout()
|
| 64 |
+
return fig
|
| 65 |
+
|
| 66 |
+
# --- 核心訓練與評估函式 ---
|
| 67 |
+
def train_and_evaluate(history_log, model_name, features, lr_c, lr_solver, dt_criterion, dt_max_depth, xgb_n_estimators, xgb_max_depth, xgb_learning_rate, svm_c, svm_kernel):
|
| 68 |
+
"""
|
| 69 |
+
當使用者點擊 "執行模型訓練" 按鈕時觸發。
|
| 70 |
+
整合了資料準備、模型訓練、評估、結果視覺化以及紀錄日誌的完整流程。
|
| 71 |
+
"""
|
| 72 |
+
if not features:
|
| 73 |
+
# 如果沒有選擇特徵,只回傳錯誤訊息和空的日誌
|
| 74 |
+
return "錯誤:請至少選擇一個特徵!", None, None, None, pd.DataFrame(history_log, columns=LOG_COLUMNS), history_log
|
| 75 |
+
|
| 76 |
+
# --- 1. 資料準備 ---
|
| 77 |
+
X = df_processed[features]
|
| 78 |
+
y = df_processed['Response']
|
| 79 |
+
X_scaled = X.copy()
|
| 80 |
+
numerical_cols_in_x = [f for f in NUMERICAL_FEATURES if f in X_scaled.columns]
|
| 81 |
+
if numerical_cols_in_x:
|
| 82 |
+
scaler = StandardScaler()
|
| 83 |
+
X_scaled[numerical_cols_in_x] = scaler.fit_transform(X_scaled[numerical_cols_in_x])
|
| 84 |
+
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.3, random_state=42, stratify=y)
|
| 85 |
+
|
| 86 |
+
# --- 2. 模型選擇與訓練 ---
|
| 87 |
+
params = {}
|
| 88 |
+
if model_name == '羅吉斯回歸':
|
| 89 |
+
params = {'C': lr_c, 'solver': lr_solver}
|
| 90 |
+
X_train_sm = sm.add_constant(X_train); X_test_sm = sm.add_constant(X_test)
|
| 91 |
+
logit_model = sm.Logit(y_train, X_train_sm)
|
| 92 |
+
result = logit_model.fit(disp=0)
|
| 93 |
+
y_pred_proba = result.predict(X_test_sm); y_pred = (y_pred_proba > 0.5).astype(int)
|
| 94 |
+
importances, title = result.tvalues.drop('const', errors='ignore'), '特徵 t-值 (Feature t-values)'
|
| 95 |
+
else:
|
| 96 |
+
if model_name == '決策樹':
|
| 97 |
+
params = {'criterion': dt_criterion, 'max_depth': dt_max_depth}
|
| 98 |
+
model = DecisionTreeClassifier(**params, random_state=42, class_weight='balanced')
|
| 99 |
+
elif model_name == 'XGBoost':
|
| 100 |
+
params = {'n_estimators': int(xgb_n_estimators), 'max_depth': int(xgb_max_depth), 'learning_rate': xgb_learning_rate}
|
| 101 |
+
scale_pos_weight = y_train.value_counts()[0] / y_train.value_counts()[1]
|
| 102 |
+
model = xgb.XGBClassifier(**params, scale_pos_weight=scale_pos_weight, use_label_encoder=False, eval_metric='logloss', random_state=42)
|
| 103 |
+
elif model_name == 'SVM':
|
| 104 |
+
params = {'C': svm_c, 'kernel': svm_kernel}
|
| 105 |
+
model = SVC(**params, probability=True, random_state=42, class_weight='balanced')
|
| 106 |
+
|
| 107 |
+
model.fit(X_train, y_train)
|
| 108 |
+
y_pred = model.predict(X_test); y_pred_proba = model.predict_proba(X_test)[:, 1]
|
| 109 |
+
|
| 110 |
+
if model_name == 'SVM' and svm_kernel == 'linear': importances, title = model.coef_[0], '特徵係數 (Feature Coefficients)'
|
| 111 |
+
elif model_name in ['決策樹', 'XGBoost']: importances, title = model.feature_importances_, '特徵重要性 (Feature Importance)'
|
| 112 |
+
else: importances, title = None, '特徵重要性'
|
| 113 |
+
|
| 114 |
+
# --- 3. 評估與繪圖 ---
|
| 115 |
+
accuracy = accuracy_score(y_test, y_pred)
|
| 116 |
+
report = classification_report(y_test, y_pred, target_names=['不感興趣 (0)', '感興趣 (1)'])
|
| 117 |
+
auc_score = f"ROC-AUC 分數: {roc_auc_score(y_test, y_pred_proba):.4f}"
|
| 118 |
+
cm = confusion_matrix(y_test, y_pred)
|
| 119 |
+
fig_cm, ax_cm = plt.subplots(); sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', ax=ax_cm, xticklabels=['預測為 0', '預測為 1'], yticklabels=['實際為 0', '實際為 1']); ax_cm.set_title('混淆矩陣'); ax_cm.set_xlabel('預測標籤'); ax_cm.set_ylabel('實際標籤'); plt.tight_layout()
|
| 120 |
+
|
| 121 |
+
fig_imp, ax_imp = plt.subplots()
|
| 122 |
+
if importances is not None:
|
| 123 |
+
feature_imp = pd.Series(importances, index=features).sort_values(ascending=False)
|
| 124 |
+
sns.barplot(x=feature_imp, y=feature_imp.index, ax=ax_imp); ax_imp.set_title(title)
|
| 125 |
+
else:
|
| 126 |
+
ax_imp.text(0.5, 0.5, '此模型/核心無法直接顯示特徵重要性', ha='center', va='center'); ax_imp.set_title(title)
|
| 127 |
+
plt.tight_layout()
|
| 128 |
+
|
| 129 |
+
# --- 4. 紀錄日誌 ---
|
| 130 |
+
new_log_entry = [
|
| 131 |
+
pd.Timestamp.now().strftime('%Y-%m-%d %H:%M:%S'),
|
| 132 |
+
model_name,
|
| 133 |
+
', '.join(features),
|
| 134 |
+
json.dumps(params),
|
| 135 |
+
f"{accuracy:.4f}"
|
| 136 |
+
]
|
| 137 |
+
# 將新紀錄加到歷史紀錄的開頭
|
| 138 |
+
updated_log = [new_log_entry] + history_log
|
| 139 |
+
log_df = pd.DataFrame(updated_log, columns=LOG_COLUMNS)
|
| 140 |
+
|
| 141 |
+
return report, auc_score, fig_cm, fig_imp, log_df, updated_log
|
| 142 |
+
|
| 143 |
+
# --- Gradio 介面設計 ---
|
| 144 |
+
LOG_COLUMNS = ["時間", "模型", "特徵", "參數", "準確率"]
|
| 145 |
+
|
| 146 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 147 |
+
# 用於儲存日誌的隱藏狀態元件
|
| 148 |
+
log_state = gr.State([])
|
| 149 |
+
|
| 150 |
+
gr.Markdown("# 互動式投保預測模型分析器")
|
| 151 |
+
gr.Markdown("在左側選擇特徵並點擊按鈕進行探索,或調整參數後點擊按鈕以訓練模型。")
|
| 152 |
+
with gr.Row():
|
| 153 |
+
with gr.Column(scale=1):
|
| 154 |
+
gr.Markdown("## 1. 特徵選擇與探索")
|
| 155 |
+
feature_selector = gr.CheckboxGroup(ALL_FEATURES, label="選擇特徵", value=['Previously_Insured', 'Vehicle_Damage', 'Policy_Sales_Channel', 'Vehicle_Age', 'Age'])
|
| 156 |
+
with gr.Row():
|
| 157 |
+
select_all_btn = gr.Button("全部選取"); deselect_all_btn = gr.Button("全部清除")
|
| 158 |
+
with gr.Accordion("特徵探索 (EDA)", open=True):
|
| 159 |
+
eda_run_btn = gr.Button("執行資料探索", variant="secondary")
|
| 160 |
+
eda_stats = gr.DataFrame(label="敘述性統計")
|
| 161 |
+
eda_corr = gr.DataFrame(label="與目標 'Response' 的相關係數")
|
| 162 |
+
eda_plot_selector = gr.Dropdown(label="選擇要視覺化的特徵")
|
| 163 |
+
eda_plot = gr.Plot(label="視覺化")
|
| 164 |
+
gr.Markdown("## 2. 模型選擇與超參數調整")
|
| 165 |
+
model_selector = gr.Dropdown(['羅吉斯回歸', '決策樹', 'XGBoost', 'SVM'], label="選擇模型", value='決策樹')
|
| 166 |
+
with gr.Group(visible=False) as lr_box:
|
| 167 |
+
gr.Markdown("#### 羅吉斯回歸"); lr_c = gr.Slider(0.01, 10.0, value=1.0, step=0.01, label="C (正規化強度, statsmodels中未使用)"); lr_solver = gr.Dropdown(['lbfgs', 'liblinear', 'saga'], value='lbfgs', label="優化演算法 (statsmodels中未使用)")
|
| 168 |
+
with gr.Group(visible=True) as dt_box:
|
| 169 |
+
gr.Markdown("#### 決策樹"); dt_criterion = gr.Radio(['gini', 'entropy'], value='gini', label="評估標準"); dt_max_depth = gr.Slider(3, 30, value=8, step=1, label="最大深度")
|
| 170 |
+
with gr.Group(visible=False) as xgb_box:
|
| 171 |
+
gr.Markdown("#### XGBoost"); xgb_n_estimators = gr.Slider(50, 500, value=100, step=10, label="樹的數量"); xgb_max_depth = gr.Slider(3, 15, value=5, step=1, label="最大深度"); xgb_learning_rate = gr.Slider(0.01, 0.3, value=0.1, step=0.01, label="學習率")
|
| 172 |
+
with gr.Group(visible=False) as svm_box:
|
| 173 |
+
gr.Markdown("#### SVM"); svm_c = gr.Slider(0.01, 10.0, value=1.0, step=0.01, label="C (懲罰參數)"); svm_kernel = gr.Radio(['linear', 'rbf', 'poly'], value='linear', label="核心")
|
| 174 |
+
run_btn = gr.Button("🚀 執行模型訓練", variant="primary")
|
| 175 |
+
with gr.Column(scale=2):
|
| 176 |
+
gr.Markdown("## 3. 模型評估��果")
|
| 177 |
+
model_output_report = gr.Textbox(label="分類報告", lines=10)
|
| 178 |
+
model_output_auc = gr.Textbox(label="AUC 分數")
|
| 179 |
+
model_plot_cm = gr.Plot(label="混淆矩陣")
|
| 180 |
+
model_plot_importance = gr.Plot(label="特徵重要性/係數")
|
| 181 |
+
|
| 182 |
+
with gr.Accordion("操作紀錄 (History Log)", open=False):
|
| 183 |
+
log_df_display = gr.DataFrame(headers=LOG_COLUMNS, datatype=["str", "str", "str", "str", "str"])
|
| 184 |
+
|
| 185 |
+
# --- 事件處理 ---
|
| 186 |
+
eda_run_btn.click(update_eda_section, inputs=feature_selector, outputs=[eda_stats, eda_corr, eda_plot_selector, eda_plot])
|
| 187 |
+
eda_plot_selector.change(generate_feature_plot, inputs=eda_plot_selector, outputs=eda_plot)
|
| 188 |
+
def show_hyperparameters(model_name): return {lr_box: gr.update(visible=model_name == '羅吉斯回歸'), dt_box: gr.update(visible=model_name == '決策樹'), xgb_box: gr.update(visible=model_name == 'XGBoost'), svm_box: gr.update(visible=model_name == 'SVM')}
|
| 189 |
+
model_selector.change(show_hyperparameters, inputs=model_selector, outputs=[lr_box, dt_box, xgb_box, svm_box])
|
| 190 |
+
def select_all_features(): return gr.update(value=ALL_FEATURES)
|
| 191 |
+
def deselect_all_features(): return gr.update(value=[])
|
| 192 |
+
select_all_btn.click(select_all_features, None, feature_selector)
|
| 193 |
+
deselect_all_btn.click(deselect_all_features, None, feature_selector)
|
| 194 |
+
|
| 195 |
+
run_btn.click(
|
| 196 |
+
train_and_evaluate,
|
| 197 |
+
inputs=[log_state, model_selector, feature_selector, lr_c, lr_solver, dt_criterion, dt_max_depth, xgb_n_estimators, xgb_max_depth, xgb_learning_rate, svm_c, svm_kernel],
|
| 198 |
+
outputs=[model_output_report, model_output_auc, model_plot_cm, model_plot_importance, log_df_display, log_state]
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
if __name__ == "__main__":
|
| 202 |
+
demo.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
pandas
|
| 3 |
+
numpy
|
| 4 |
+
matplotlib
|
| 5 |
+
seaborn
|
| 6 |
+
scikit-learn
|
| 7 |
+
xgboost
|
| 8 |
+
statsmodels
|
sampled_data.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|