Spaces:
Sleeping
Sleeping
File size: 19,802 Bytes
6bb1489 37ea271 6bb1489 37ea271 6bb1489 37ea271 6bb1489 37ea271 6bb1489 37ea271 6bb1489 37ea271 6bb1489 37ea271 6bb1489 37ea271 6bb1489 37ea271 6bb1489 37ea271 6bb1489 37ea271 6bb1489 37ea271 6bb1489 37ea271 6bb1489 37ea271 6bb1489 37ea271 6bb1489 37ea271 6bb1489 37ea271 6bb1489 37ea271 6bb1489 37ea271 6bb1489 37ea271 6bb1489 37ea271 6bb1489 37ea271 6bb1489 37ea271 6bb1489 37ea271 6bb1489 37ea271 6bb1489 37ea271 6bb1489 37ea271 6bb1489 37ea271 6bb1489 37ea271 6bb1489 37ea271 6bb1489 cda6fb2 6bb1489 37ea271 6bb1489 37ea271 6bb1489 37ea271 6bb1489 37ea271 162340c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 | import warnings
warnings.filterwarnings("ignore")
import gradio as gr
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.impute import SimpleImputer
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.metrics import (
accuracy_score,
precision_score,
recall_score,
f1_score,
classification_report,
confusion_matrix,
ConfusionMatrixDisplay,
roc_curve,
auc
)
# =========================
# 基本工具函式
# =========================
def load_data(file_obj):
if file_obj is None:
raise ValueError("請先上傳 CSV 或 Excel 檔案。")
file_path = file_obj.name
lower_name = file_path.lower()
if lower_name.endswith(".csv"):
return pd.read_csv(file_path)
if lower_name.endswith(".xlsx") or lower_name.endswith(".xls"):
return pd.read_excel(file_path)
raise ValueError("目前只支援 .csv、.xlsx、.xls 檔案。")
def build_model(
model_name,
knn_k,
dt_criterion,
dt_max_depth,
rf_estimators,
rf_max_depth,
lr_c,
svm_kernel,
svm_c
):
if model_name == "KNN":
return KNeighborsClassifier(n_neighbors=int(knn_k))
if model_name == "Decision Tree":
max_depth = None if int(dt_max_depth) == 0 else int(dt_max_depth)
return DecisionTreeClassifier(
criterion=dt_criterion,
max_depth=max_depth,
random_state=42
)
if model_name == "Random Forest":
max_depth = None if int(rf_max_depth) == 0 else int(rf_max_depth)
return RandomForestClassifier(
n_estimators=int(rf_estimators),
max_depth=max_depth,
random_state=42
)
if model_name == "Logistic Regression":
return LogisticRegression(
C=float(lr_c),
max_iter=2000,
random_state=42
)
if model_name == "SVM":
return SVC(
kernel=svm_kernel,
C=float(svm_c),
probability=True,
random_state=42
)
raise ValueError("不支援的模型。")
def preprocess_features(df, target_column):
df = df.copy().dropna(how="all")
y = df[target_column]
X = df.drop(columns=[target_column])
numeric_cols = X.select_dtypes(include=[np.number]).columns.tolist()
categorical_cols = X.select_dtypes(exclude=[np.number]).columns.tolist()
if numeric_cols:
num_imputer = SimpleImputer(strategy="median")
X[numeric_cols] = num_imputer.fit_transform(X[numeric_cols])
if categorical_cols:
cat_imputer = SimpleImputer(strategy="most_frequent")
X[categorical_cols] = cat_imputer.fit_transform(X[categorical_cols])
X = pd.get_dummies(X, columns=categorical_cols, drop_first=True)
return X, y
def prepare_target(df, target_column, use_count_as_target):
df = df.copy()
if use_count_as_target:
if "count" not in df.columns:
raise ValueError("你勾選了 count 二元分類,但資料中沒有 count 欄位。")
median_value = df["count"].median()
df["label"] = (df["count"] > median_value).astype(int)
target_column = "label"
if target_column is None or target_column not in df.columns:
raise ValueError("請選擇正確的目標欄位。")
return df, target_column
def encode_target(y):
if y.dtype == "object":
encoder = LabelEncoder()
y = encoder.fit_transform(y)
return y
# =========================
# 視覺化函式
# =========================
def plot_target_distribution(y_series, title="Label Distribution"):
fig, ax = plt.subplots(figsize=(6, 4))
counts = pd.Series(y_series).value_counts().sort_index()
ax.bar(counts.index.astype(str), counts.values)
ax.set_title(title)
ax.set_xlabel("Class")
ax.set_ylabel("Count")
plt.tight_layout()
return fig
def plot_confusion(y_true, y_pred):
fig, ax = plt.subplots(figsize=(5, 4))
disp = ConfusionMatrixDisplay(confusion_matrix=confusion_matrix(y_true, y_pred))
disp.plot(ax=ax)
ax.set_title("Confusion Matrix")
plt.tight_layout()
return fig
def plot_roc_curve(y_true, y_prob):
fpr, tpr, _ = roc_curve(y_true, y_prob)
roc_auc = auc(fpr, tpr)
fig, ax = plt.subplots(figsize=(6, 4))
ax.plot(fpr, tpr, label=f"AUC = {roc_auc:.4f}")
ax.plot([0, 1], [0, 1], linestyle="--")
ax.set_title("ROC Curve")
ax.set_xlabel("False Positive Rate")
ax.set_ylabel("True Positive Rate")
ax.legend(loc="lower right")
plt.tight_layout()
return fig, roc_auc
def plot_model_comparison(result_df):
fig, ax = plt.subplots(figsize=(8, 4))
ax.bar(result_df["Model"], result_df["Accuracy"])
ax.set_title("Model Accuracy Comparison")
ax.set_xlabel("Model")
ax.set_ylabel("Accuracy")
ax.set_ylim(0, 1)
plt.xticks(rotation=15)
plt.tight_layout()
return fig
# =========================
# 資料分析
# =========================
def analyze_file(file_obj):
try:
df = load_data(file_obj)
preview_df = df.head(10)
info_df = pd.DataFrame({
"欄位名稱": df.columns,
"資料型態": [str(dtype) for dtype in df.dtypes]
})
missing_df = pd.DataFrame({
"欄位名稱": df.columns,
"缺失值數量": df.isnull().sum().values,
"缺失比例(%)": (df.isnull().mean().values * 100).round(2)
})
summary = []
summary.append(f"資料筆數:{df.shape[0]}")
summary.append(f"資料欄數:{df.shape[1]}")
summary.append(f"數值欄位數:{len(df.select_dtypes(include=[np.number]).columns)}")
summary.append(f"類別欄位數:{len(df.select_dtypes(exclude=[np.number]).columns)}")
summary.append(f"總缺失值數:{int(df.isnull().sum().sum())}")
columns = list(df.columns)
if len(columns) > 0:
default_target = "count" if "count" in columns else columns[-1]
else:
default_target = None
has_count_message = "有偵測到 count 欄位,可直接轉成二元分類。" if "count" in df.columns else "未偵測到 count 欄位。"
empty_fig = plt.figure()
plt.close(empty_fig)
return (
preview_df,
info_df,
missing_df,
"\n".join(summary) + f"\n{has_count_message}",
gr.update(choices=columns, value=default_target),
)
except Exception as e:
empty_df = pd.DataFrame()
return (
empty_df,
empty_df,
empty_df,
f"資料分析失敗:{e}",
gr.update(choices=[], value=None),
)
def target_distribution(file_obj, target_column, use_count_as_target):
try:
df = load_data(file_obj)
df, target_column = prepare_target(df, target_column, use_count_as_target)
fig = plot_target_distribution(df[target_column], title=f"{target_column} Distribution")
return fig
except Exception as e:
fig, ax = plt.subplots(figsize=(6, 3))
ax.text(0.5, 0.5, f"無法產生分布圖:\n{e}", ha="center", va="center")
ax.axis("off")
plt.tight_layout()
return fig
# =========================
# 單一模型訓練
# =========================
def train_single_model(
file_obj,
target_column,
use_count_as_target,
test_size,
use_scaling,
model_name,
knn_k,
dt_criterion,
dt_max_depth,
rf_estimators,
rf_max_depth,
lr_c,
svm_kernel,
svm_c
):
try:
df = load_data(file_obj)
df, target_column = prepare_target(df, target_column, use_count_as_target)
X, y = preprocess_features(df, target_column)
y = encode_target(y)
unique_classes = np.unique(y)
if len(unique_classes) != 2:
raise ValueError("目前版本只支援二元分類,因為需要輸出 ROC/AUC。")
X_train, X_test, y_train, y_test = train_test_split(
X, y,
test_size=float(test_size),
random_state=42,
stratify=y
)
if use_scaling:
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
else:
X_train = X_train.values
X_test = X_test.values
model = build_model(
model_name=model_name,
knn_k=knn_k,
dt_criterion=dt_criterion,
dt_max_depth=dt_max_depth,
rf_estimators=rf_estimators,
rf_max_depth=rf_max_depth,
lr_c=lr_c,
svm_kernel=svm_kernel,
svm_c=svm_c
)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
y_prob = None
if hasattr(model, "predict_proba"):
y_prob = model.predict_proba(X_test)[:, 1]
acc = accuracy_score(y_test, y_pred)
pre = precision_score(y_test, y_pred, zero_division=0)
rec = recall_score(y_test, y_pred, zero_division=0)
f1 = f1_score(y_test, y_pred, zero_division=0)
auc_text = "無法計算"
roc_fig = None
if y_prob is not None:
roc_fig, roc_auc = plot_roc_curve(y_test, y_prob)
auc_text = f"{roc_auc:.4f}"
result_text = (
f"模型名稱:{model_name}\n"
f"Accuracy:{acc:.4f}\n"
f"Precision:{pre:.4f}\n"
f"Recall:{rec:.4f}\n"
f"F1-score:{f1:.4f}\n"
f"AUC:{auc_text}"
)
report_df = pd.DataFrame(classification_report(y_test, y_pred, output_dict=True)).transpose()
cm_fig = plot_confusion(y_test, y_pred)
return result_text, report_df.round(4), cm_fig, roc_fig
except Exception as e:
empty_df = pd.DataFrame()
fig, ax = plt.subplots(figsize=(6, 3))
ax.text(0.5, 0.5, f"錯誤:{e}", ha="center", va="center")
ax.axis("off")
plt.tight_layout()
return f"模型訓練失敗:{e}", empty_df, fig, None
# =========================
# 多模型比較
# =========================
def compare_models(
file_obj,
target_column,
use_count_as_target,
test_size,
use_scaling
):
try:
df = load_data(file_obj)
df, target_column = prepare_target(df, target_column, use_count_as_target)
X, y = preprocess_features(df, target_column)
y = encode_target(y)
unique_classes = np.unique(y)
if len(unique_classes) != 2:
raise ValueError("目前版本只支援二元分類比較。")
X_train, X_test, y_train, y_test = train_test_split(
X, y,
test_size=float(test_size),
random_state=42,
stratify=y
)
if use_scaling:
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
else:
X_train_scaled = X_train.values
X_test_scaled = X_test.values
models = [
("KNN", KNeighborsClassifier(n_neighbors=5)),
("Decision Tree", DecisionTreeClassifier(random_state=42)),
("Random Forest", RandomForestClassifier(n_estimators=100, random_state=42)),
("Logistic Regression", LogisticRegression(max_iter=2000, random_state=42)),
("SVM", SVC(kernel="rbf", probability=True, random_state=42)),
]
rows = []
for name, model in models:
model.fit(X_train_scaled, y_train)
y_pred = model.predict(X_test_scaled)
acc = accuracy_score(y_test, y_pred)
pre = precision_score(y_test, y_pred, zero_division=0)
rec = recall_score(y_test, y_pred, zero_division=0)
f1 = f1_score(y_test, y_pred, zero_division=0)
auc_score = np.nan
if hasattr(model, "predict_proba"):
y_prob = model.predict_proba(X_test_scaled)[:, 1]
auc_score = auc(*roc_curve(y_test, y_prob)[:2])
rows.append({
"Model": name,
"Accuracy": round(acc, 4),
"Precision": round(pre, 4),
"Recall": round(rec, 4),
"F1-score": round(f1, 4),
"AUC": None if pd.isna(auc_score) else round(auc_score, 4)
})
result_df = pd.DataFrame(rows).sort_values(by="Accuracy", ascending=False).reset_index(drop=True)
compare_fig = plot_model_comparison(result_df)
best_model = result_df.iloc[0]
summary = (
f"最佳模型:{best_model['Model']}\n"
f"Accuracy:{best_model['Accuracy']}\n"
f"Precision:{best_model['Precision']}\n"
f"Recall:{best_model['Recall']}\n"
f"F1-score:{best_model['F1-score']}\n"
f"AUC:{best_model['AUC']}"
)
return summary, result_df, compare_fig
except Exception as e:
empty_df = pd.DataFrame()
fig, ax = plt.subplots(figsize=(6, 3))
ax.text(0.5, 0.5, f"錯誤:{e}", ha="center", va="center")
ax.axis("off")
plt.tight_layout()
return f"模型比較失敗:{e}", empty_df, fig
# =========================
# UI
# =========================
custom_css = """
.gradio-container {
max-width: 1200px !important;
}
"""
with gr.Blocks(title="機器學習模型訓練工具", css=custom_css) as demo:
gr.Markdown("""
# 機器學習模型訓練
- 資料上傳與預覽
- 欄位型態與缺失值分析
- `count` 欄位轉二元分類
- KNN / Decision Tree / Random Forest / Logistic Regression / SVM
- Accuracy / Precision / Recall / F1-score / AUC
- Confusion Matrix / ROC Curve
- 多模型比較
""")
with gr.Tab("1. 資料分析"):
with gr.Row():
with gr.Column(scale=1):
file_input = gr.File(
label="上傳 CSV 或 Excel 檔案",
file_types=[".csv", ".xlsx", ".xls"]
)
analyze_btn = gr.Button("分析資料", variant="primary")
target_dropdown = gr.Dropdown(label="目標欄位", choices=[], value=None)
use_count_checkbox = gr.Checkbox(
label="若資料有 count 欄位,將其依中位數轉成二元分類",
value=True
)
dist_btn = gr.Button("顯示類別分布")
with gr.Column(scale=2):
summary_output = gr.Textbox(label="資料摘要", lines=8)
preview_output = gr.Dataframe(label="資料預覽")
info_output = gr.Dataframe(label="欄位型態")
missing_output = gr.Dataframe(label="缺失值統計")
dist_plot = gr.Plot(label="類別分布圖")
with gr.Tab("2. 單一模型訓練"):
with gr.Row():
with gr.Column(scale=1):
test_size_slider = gr.Slider(
label="測試集比例",
minimum=0.1,
maximum=0.5,
step=0.1,
value=0.2
)
use_scaling_checkbox = gr.Checkbox(
label="使用 StandardScaler",
value=True
)
model_dropdown = gr.Dropdown(
label="選擇模型",
choices=[
"KNN",
"Decision Tree",
"Random Forest",
"Logistic Regression",
"SVM"
],
value="KNN"
)
gr.Markdown("## 模型參數")
knn_k = gr.Slider(label="KNN:k 值", minimum=1, maximum=15, value=5, step=1)
dt_criterion = gr.Dropdown(
label="Decision Tree:criterion",
choices=["gini", "entropy"],
value="gini"
)
dt_max_depth = gr.Slider(
label="Decision Tree:max_depth(0 代表不限)",
minimum=0, maximum=20, value=5, step=1
)
rf_estimators = gr.Slider(
label="Random Forest:n_estimators",
minimum=10, maximum=300, value=100, step=10
)
rf_max_depth = gr.Slider(
label="Random Forest:max_depth(0 代表不限)",
minimum=0, maximum=20, value=5, step=1
)
lr_c = gr.Slider(
label="Logistic Regression:C",
minimum=0.01, maximum=10.0, value=1.0, step=0.01
)
svm_kernel = gr.Dropdown(
label="SVM:kernel",
choices=["linear", "rbf"],
value="rbf"
)
svm_c = gr.Slider(
label="SVM:C",
minimum=0.01, maximum=10.0, value=1.0, step=0.01
)
train_btn = gr.Button("開始訓練單一模型", variant="primary")
with gr.Column(scale=2):
single_result_output = gr.Textbox(label="模型結果", lines=8)
report_output = gr.Dataframe(label="Classification Report")
cm_output = gr.Plot(label="Confusion Matrix")
roc_output = gr.Plot(label="ROC Curve")
with gr.Tab("3. 多模型比較"):
with gr.Row():
with gr.Column(scale=1):
compare_btn = gr.Button("比較所有模型", variant="primary")
with gr.Column(scale=2):
compare_summary = gr.Textbox(label="最佳模型摘要", lines=8)
compare_table = gr.Dataframe(label="模型比較表")
compare_plot = gr.Plot(label="模型 Accuracy 比較圖")
analyze_btn.click(
fn=analyze_file,
inputs=[file_input],
outputs=[
preview_output,
info_output,
missing_output,
summary_output,
target_dropdown
]
)
dist_btn.click(
fn=target_distribution,
inputs=[file_input, target_dropdown, use_count_checkbox],
outputs=[dist_plot]
)
train_btn.click(
fn=train_single_model,
inputs=[
file_input,
target_dropdown,
use_count_checkbox,
test_size_slider,
use_scaling_checkbox,
model_dropdown,
knn_k,
dt_criterion,
dt_max_depth,
rf_estimators,
rf_max_depth,
lr_c,
svm_kernel,
svm_c
],
outputs=[
single_result_output,
report_output,
cm_output,
roc_output
]
)
compare_btn.click(
fn=compare_models,
inputs=[
file_input,
target_dropdown,
use_count_checkbox,
test_size_slider,
use_scaling_checkbox
],
outputs=[
compare_summary,
compare_table,
compare_plot
]
)
demo.launch() |