Spaces:
Sleeping
Sleeping
File size: 31,770 Bytes
1ba6c1c 66e4bca 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 66e4bca 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c 5f6dd05 1ba6c1c | 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 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 | import streamlit as st
import pandas as pd
import numpy as np
import joblib
import json
import os
import time
from datetime import datetime
import plotly.express as px
from PIL import Image
# ---------------------------------------------------------
# Smart Base Path Detection
# ---------------------------------------------------------
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
# Case 1: files are in root of Hugging Face Space
if os.path.exists(os.path.join(APP_ROOT, "models")):
BASE_DIR = APP_ROOT
# Case 2: user uploaded whole WiGuard_App folder into the Space
elif os.path.exists(os.path.join(APP_ROOT, "WiGuard_App", "models")):
BASE_DIR = os.path.join(APP_ROOT, "WiGuard_App")
else:
BASE_DIR = APP_ROOT
def P(*parts):
return os.path.join(BASE_DIR, *parts)
# ---------------------------------------------------------
# File Paths
# ---------------------------------------------------------
CICIOT_MODEL_PATH = P("models", "xgboost_wiguard_full.pkl")
COMBINED_MODEL_PATH = P("models", "xgboost_combined_ciciot_unsw_binary.pkl")
FEATURES_PATH = P("models", "selected_features.pkl")
RESULTS_PATH = P("models", "model_results.json")
RF_RESULTS_PATH = P("models", "random_forest_results.json")
DASHBOARD_DATA_PATH = P("dashboard_data", "dashboard_sample_traffic.csv")
# Original CICIoT SHAP outputs
SHAP_IMPORTANCE_PATH = P("shap_outputs", "global_shap_feature_importance.csv")
SHAP_LOCAL_PATH = P("shap_outputs", "sample_local_explanation.json")
SHAP_BAR_IMAGE = P("shap_outputs", "shap_global_bar.png")
SHAP_SUMMARY_IMAGE = P("shap_outputs", "shap_summary_beeswarm.png")
# Experiment 05 outputs
EXP05_COMPARISON_PATH = P("experiment_outputs", "experiment_05_comparison_table.csv")
EXP05_SUMMARY_PATH = P("experiment_outputs", "experiment_05c_combined_model_summary.json")
UNSW_BINARY_IMBALANCE_PATH = P("experiment_outputs", "unsw_binary_imbalance_summary.csv")
UNSW_ATTACK_IMBALANCE_PATH = P("experiment_outputs", "unsw_attack_category_imbalance_summary.csv")
EXP05_GRAPH_DIR = P("experiment_outputs", "graphs")
EXP05_GRAPHS = {
"Experiment 05 Metrics Comparison": os.path.join(EXP05_GRAPH_DIR, "experiment_05_metrics_comparison.png"),
"Experiment 05 Accuracy Comparison": os.path.join(EXP05_GRAPH_DIR, "experiment_05_accuracy_comparison.png"),
"Direct Transfer vs Combined Model on UNSW-NB15": os.path.join(EXP05_GRAPH_DIR, "experiment_05_direct_transfer_vs_combined_unsw.png"),
"Combined Model Confusion Matrix on UNSW-NB15": os.path.join(EXP05_GRAPH_DIR, "experiment_05c_combined_model_unsw_confusion_matrix.png"),
"Combined Model Confusion Matrix on CICIoT2023": os.path.join(EXP05_GRAPH_DIR, "experiment_05c_combined_model_ciciot_confusion_matrix.png"),
}
# Combined model SHAP outputs
COMBINED_SHAP_DIR = P("shap_outputs", "combined_model")
COMBINED_SHAP_GRAPH_DIR = os.path.join(COMBINED_SHAP_DIR, "graphs")
COMBINED_SHAP_UNSW_PATH = os.path.join(COMBINED_SHAP_DIR, "shap_importance_unsw_combined_model.csv")
COMBINED_SHAP_CICIOT_PATH = os.path.join(COMBINED_SHAP_DIR, "shap_importance_ciciot_combined_model.csv")
COMBINED_SHAP_COMPARE_PATH = os.path.join(COMBINED_SHAP_DIR, "shap_top_feature_comparison_unsw_vs_ciciot.csv")
COMBINED_LOCAL_UNSW_PATH = os.path.join(COMBINED_SHAP_DIR, "local_explanation_unsw_sample.json")
COMBINED_LOCAL_CICIOT_PATH = os.path.join(COMBINED_SHAP_DIR, "local_explanation_ciciot_sample.json")
COMBINED_SHAP_GRAPHS = {
"UNSW-NB15 SHAP Bar Plot": os.path.join(COMBINED_SHAP_GRAPH_DIR, "shap_bar_unsw_combined_model.png"),
"CICIoT2023 SHAP Bar Plot": os.path.join(COMBINED_SHAP_GRAPH_DIR, "shap_bar_ciciot_combined_model.png"),
"UNSW-NB15 SHAP Beeswarm Plot": os.path.join(COMBINED_SHAP_GRAPH_DIR, "shap_beeswarm_unsw_combined_model.png"),
"CICIoT2023 SHAP Beeswarm Plot": os.path.join(COMBINED_SHAP_GRAPH_DIR, "shap_beeswarm_ciciot_combined_model.png"),
}
# ---------------------------------------------------------
# Page Configuration
# ---------------------------------------------------------
st.set_page_config(
page_title="WiGuard | Explainable AI IDS",
page_icon="π‘οΈ",
layout="wide"
)
# ---------------------------------------------------------
# File Paths
# ---------------------------------------------------------
CICIOT_MODEL_PATH = "models/xgboost_wiguard_full.pkl"
COMBINED_MODEL_PATH = "models/xgboost_combined_ciciot_unsw_binary.pkl"
FEATURES_PATH = "models/selected_features.pkl"
RESULTS_PATH = "models/model_results.json"
RF_RESULTS_PATH = "models/random_forest_results.json"
DASHBOARD_DATA_PATH = "dashboard_data/dashboard_sample_traffic.csv"
# Original CICIoT SHAP outputs
SHAP_IMPORTANCE_PATH = "shap_outputs/global_shap_feature_importance.csv"
SHAP_LOCAL_PATH = "shap_outputs/sample_local_explanation.json"
SHAP_BAR_IMAGE = "shap_outputs/shap_global_bar.png"
SHAP_SUMMARY_IMAGE = "shap_outputs/shap_summary_beeswarm.png"
# Experiment 05 outputs
EXP05_COMPARISON_PATH = "experiment_outputs/experiment_05_comparison_table.csv"
EXP05_SUMMARY_PATH = "experiment_outputs/experiment_05c_combined_model_summary.json"
UNSW_BINARY_IMBALANCE_PATH = "experiment_outputs/unsw_binary_imbalance_summary.csv"
UNSW_ATTACK_IMBALANCE_PATH = "experiment_outputs/unsw_attack_category_imbalance_summary.csv"
EXP05_GRAPH_DIR = "experiment_outputs/graphs"
EXP05_GRAPHS = {
"Experiment 05 Metrics Comparison": f"{EXP05_GRAPH_DIR}/experiment_05_metrics_comparison.png",
"Experiment 05 Accuracy Comparison": f"{EXP05_GRAPH_DIR}/experiment_05_accuracy_comparison.png",
"Direct Transfer vs Combined Model on UNSW-NB15": f"{EXP05_GRAPH_DIR}/experiment_05_direct_transfer_vs_combined_unsw.png",
"Combined Model Confusion Matrix on UNSW-NB15": f"{EXP05_GRAPH_DIR}/experiment_05c_combined_model_unsw_confusion_matrix.png",
"Combined Model Confusion Matrix on CICIoT2023": f"{EXP05_GRAPH_DIR}/experiment_05c_combined_model_ciciot_confusion_matrix.png",
}
# Combined model SHAP outputs
COMBINED_SHAP_DIR = "shap_outputs/combined_model"
COMBINED_SHAP_GRAPH_DIR = f"{COMBINED_SHAP_DIR}/graphs"
COMBINED_SHAP_UNSW_PATH = f"{COMBINED_SHAP_DIR}/shap_importance_unsw_combined_model.csv"
COMBINED_SHAP_CICIOT_PATH = f"{COMBINED_SHAP_DIR}/shap_importance_ciciot_combined_model.csv"
COMBINED_SHAP_COMPARE_PATH = f"{COMBINED_SHAP_DIR}/shap_top_feature_comparison_unsw_vs_ciciot.csv"
COMBINED_LOCAL_UNSW_PATH = f"{COMBINED_SHAP_DIR}/local_explanation_unsw_sample.json"
COMBINED_LOCAL_CICIOT_PATH = f"{COMBINED_SHAP_DIR}/local_explanation_ciciot_sample.json"
COMBINED_SHAP_GRAPHS = {
"UNSW-NB15 SHAP Bar Plot": f"{COMBINED_SHAP_GRAPH_DIR}/shap_bar_unsw_combined_model.png",
"CICIoT2023 SHAP Bar Plot": f"{COMBINED_SHAP_GRAPH_DIR}/shap_bar_ciciot_combined_model.png",
"UNSW-NB15 SHAP Beeswarm Plot": f"{COMBINED_SHAP_GRAPH_DIR}/shap_beeswarm_unsw_combined_model.png",
"CICIoT2023 SHAP Beeswarm Plot": f"{COMBINED_SHAP_GRAPH_DIR}/shap_beeswarm_ciciot_combined_model.png",
}
# ---------------------------------------------------------
# Safe Loading Helpers
# ---------------------------------------------------------
def file_exists(path):
return os.path.exists(path)
@st.cache_resource
def load_model(path):
if os.path.exists(path):
return joblib.load(path)
return None
@st.cache_data
def load_pickle_file(path):
if os.path.exists(path):
return joblib.load(path)
return None
@st.cache_data
def load_json_file(path):
if os.path.exists(path):
with open(path, "r") as f:
return json.load(f)
return None
@st.cache_data
def load_csv_file(path):
if os.path.exists(path):
return pd.read_csv(path)
return None
@st.cache_data
def load_dashboard_data():
if os.path.exists(DASHBOARD_DATA_PATH):
return pd.read_csv(DASHBOARD_DATA_PATH)
return pd.DataFrame()
# ---------------------------------------------------------
# Load Assets
# ---------------------------------------------------------
ciciot_model = load_model(CICIOT_MODEL_PATH)
combined_model = load_model(COMBINED_MODEL_PATH)
selected_features = load_pickle_file(FEATURES_PATH)
results = load_json_file(RESULTS_PATH)
rf_results = load_json_file(RF_RESULTS_PATH)
traffic_df = load_dashboard_data()
shap_importance_df = load_csv_file(SHAP_IMPORTANCE_PATH)
local_explanation = load_json_file(SHAP_LOCAL_PATH)
exp05_comparison_df = load_csv_file(EXP05_COMPARISON_PATH)
exp05_summary = load_json_file(EXP05_SUMMARY_PATH)
unsw_binary_imbalance_df = load_csv_file(UNSW_BINARY_IMBALANCE_PATH)
unsw_attack_imbalance_df = load_csv_file(UNSW_ATTACK_IMBALANCE_PATH)
combined_shap_unsw_df = load_csv_file(COMBINED_SHAP_UNSW_PATH)
combined_shap_ciciot_df = load_csv_file(COMBINED_SHAP_CICIOT_PATH)
combined_shap_compare_df = load_csv_file(COMBINED_SHAP_COMPARE_PATH)
combined_local_unsw = load_json_file(COMBINED_LOCAL_UNSW_PATH)
combined_local_ciciot = load_json_file(COMBINED_LOCAL_CICIOT_PATH)
if selected_features is None:
selected_features = []
# ---------------------------------------------------------
# Helper Functions
# ---------------------------------------------------------
def get_severity(probability):
if probability < 0.25:
return "Low", "π’"
elif probability < 0.50:
return "Medium", "π‘"
elif probability < 0.75:
return "High", "π "
else:
return "Critical", "π΄"
def format_percent(x):
try:
return f"{float(x) * 100:.3f}%"
except Exception:
return "N/A"
def show_image_if_exists(path, caption=None):
if os.path.exists(path):
st.image(Image.open(path), caption=caption, use_container_width=True)
else:
st.warning(f"Image not found: {path}")
def show_csv_if_exists(df, title=None):
if title:
st.markdown(title)
if df is not None and not df.empty:
st.dataframe(df, use_container_width=True)
else:
st.info("File not found or empty.")
def predict_single(row, active_model):
if active_model is None:
return "Model Missing", 0.0, "Unknown", "βͺ"
if len(selected_features) == 0:
return "Features Missing", 0.0, "Unknown", "βͺ"
X = pd.DataFrame([row[selected_features].to_dict()])
for col in selected_features:
X[col] = pd.to_numeric(X[col], errors="coerce")
X = X.fillna(0)
X = X[selected_features]
X = X.astype(float)
prediction = int(active_model.predict(X)[0])
if hasattr(active_model, "predict_proba"):
probability = float(active_model.predict_proba(X)[0][1])
else:
probability = float(prediction)
severity, icon = get_severity(probability)
label = "Attack" if prediction == 1 else "Benign"
return label, probability, severity, icon
def display_confusion_matrix(cm, title, labels=("Benign", "Attack")):
fig = px.imshow(
cm,
text_auto=True,
labels=dict(x="Predicted Label", y="Actual Label", color="Count"),
x=list(labels),
y=list(labels),
title=title
)
st.plotly_chart(fig, use_container_width=True)
# ---------------------------------------------------------
# Sidebar
# ---------------------------------------------------------
st.sidebar.title("π‘οΈ WiGuard")
st.sidebar.caption("Explainable AI-Based Intrusion Detection System")
page = st.sidebar.radio(
"Navigation",
[
"Home",
"Model Performance",
"Live Traffic Simulation",
"Explainability",
"Dataset & Features",
"Attack Logs"
]
)
st.sidebar.markdown("---")
st.sidebar.write("**Models:** XGBoost")
st.sidebar.write("**XAI:** SHAP")
st.sidebar.write("**Datasets:** CICIoT2023 + UNSW-NB15")
st.sidebar.write("**Mode:** Benchmark Traffic Simulation")
with st.sidebar.expander("π File Check"):
files_to_check = {
"CICIoT model": CICIOT_MODEL_PATH,
"Combined model": COMBINED_MODEL_PATH,
"Selected features": FEATURES_PATH,
"Dashboard data": DASHBOARD_DATA_PATH,
"Experiment 05 table": EXP05_COMPARISON_PATH,
"Experiment 05 summary": EXP05_SUMMARY_PATH,
"Experiment 05 graph folder": EXP05_GRAPH_DIR,
"Combined SHAP folder": COMBINED_SHAP_DIR,
}
st.write("Base directory:")
st.code(BASE_DIR)
for name, path in files_to_check.items():
if os.path.exists(path):
st.success(f"{name}: found")
else:
st.error(f"{name}: missing")
st.code(path)
# ---------------------------------------------------------
# Home Page
# ---------------------------------------------------------
if page == "Home":
st.title("π‘οΈ WiGuard")
st.subheader("Explainable AI-Based Network / IoT Intrusion Detection System")
st.markdown("""
**WiGuard** is an explainable intrusion detection framework designed to classify
network-flow traffic as **Benign** or **Attack** using XGBoost models.
The system now includes both the original **CICIoT2023-based model** and a newer
**combined CICIoT2023 + UNSW-NB15 model** trained using a shared 44-feature WiGuard representation.
SHAP explainability is used to explain model behavior globally and locally.
""")
col1, col2, col3, col4 = st.columns(4)
col1.info("Datasets: CICIoT2023 + UNSW-NB15")
col2.info("Models: XGBoost")
col3.info("Explainability: SHAP")
col4.info("Feature Space: 44 WiGuard Features")
st.markdown("### Updated WiGuard Pipeline")
st.markdown("""
1. Load CICIoT2023 and UNSW-NB15 network traffic datasets
2. Clean and preprocess both datasets
3. Map UNSW-NB15 into WiGuard's 44-feature format
4. Train and evaluate CICIoT2023-only, UNSW-specific, and combined models
5. Analyze cross-dataset generalization and domain shift
6. Generate SHAP explanations for original and combined models
7. Display predictions, performance, feature mapping, and explanations in Streamlit
""")
st.success("""
The combined WiGuard model was trained using samples from both CICIoT2023 and UNSW-NB15.
This improves robustness compared to direct zero-shot transfer from one dataset to another.
""")
st.warning("""
This deployed version uses benchmark test records to simulate real-time traffic.
Live Wireshark/tshark packet capture remains a future local extension because raw packets
must first be converted into WiGuard-style flow features.
""")
# ---------------------------------------------------------
# Model Performance Page
# ---------------------------------------------------------
elif page == "Model Performance":
st.title("π Model Performance")
st.markdown("## 1. Original CICIoT2023 Binary Model")
if results is not None and "test" in results:
test_results = results["test"]
col1, col2, col3, col4, col5 = st.columns(5)
col1.metric("Accuracy", format_percent(test_results.get("accuracy")))
col2.metric("Precision", format_percent(test_results.get("precision")))
col3.metric("Recall", format_percent(test_results.get("recall")))
col4.metric("F1 Score", format_percent(test_results.get("f1_score")))
col5.metric("ROC-AUC", format_percent(test_results.get("roc_auc")))
st.markdown("### CICIoT2023 Confusion Matrix")
cm = np.array(test_results["confusion_matrix"])
display_confusion_matrix(cm, "Original CICIoT2023 XGBoost Confusion Matrix")
st.markdown(f"""
- **True Benign:** {cm[0][0]:,}
- **False Attack Alerts:** {cm[0][1]:,}
- **Missed Attacks:** {cm[1][0]:,}
- **Correctly Detected Attacks:** {cm[1][1]:,}
""")
else:
st.warning("Original model results file not found.")
st.markdown("---")
st.markdown("## 2. Experiment 05: Cross-Dataset and Combined Model Results")
if exp05_comparison_df is not None and not exp05_comparison_df.empty:
st.dataframe(exp05_comparison_df, use_container_width=True)
st.markdown("### Key Interpretation")
st.markdown("""
- **05-A Direct Transfer** showed poor generalization because the CICIoT2023-trained model predicted all UNSW-NB15 samples as attacks.
- **05-B UNSW-specific model** proved that the mapped UNSW-NB15 44-feature representation is learnable.
- **05-C Combined model** performed strongly on both CICIoT2023 and UNSW-NB15, supporting the common feature-space training strategy.
""")
else:
st.warning("Experiment 05 comparison table not found.")
st.markdown("### Experiment 05 Graphs")
for title, path in EXP05_GRAPHS.items():
with st.expander(title, expanded=False):
show_image_if_exists(path, title)
st.markdown("---")
st.markdown("## 3. Combined Model Summary")
if exp05_summary is not None:
col1, col2 = st.columns(2)
with col1:
st.markdown("### Tested on UNSW-NB15")
unsw_results = exp05_summary.get("unsw_test_results", {})
st.metric("Accuracy", format_percent(unsw_results.get("accuracy", 0)))
st.metric("F1 Score", format_percent(unsw_results.get("f1_score", 0)))
st.metric("ROC-AUC", format_percent(unsw_results.get("roc_auc", 0)))
with col2:
st.markdown("### Tested on CICIoT2023")
ciciot_results = exp05_summary.get("ciciot_test_results", {})
st.metric("Accuracy", format_percent(ciciot_results.get("accuracy", 0)))
st.metric("F1 Score", format_percent(ciciot_results.get("f1_score", 0)))
st.metric("ROC-AUC", format_percent(ciciot_results.get("roc_auc", 0)))
with st.expander("View Full Experiment 05-C Summary JSON"):
st.json(exp05_summary)
else:
st.info("Combined model summary JSON not found.")
# ---------------------------------------------------------
# Live Traffic Simulation Page
# ---------------------------------------------------------
elif page == "Live Traffic Simulation":
st.title("π‘ Live Traffic Simulation")
st.markdown("""
This page simulates incoming network-flow records using benchmark test samples.
You can choose between the original CICIoT2023 model and the combined CICIoT2023 + UNSW-NB15 model.
""")
available_models = {
"Original CICIoT2023 Binary Model": ciciot_model,
"Combined CICIoT2023 + UNSW-NB15 Binary Model": combined_model,
}
model_choice = st.selectbox(
"Select model for prediction",
list(available_models.keys())
)
active_model = available_models[model_choice]
if active_model is None:
st.error(f"Selected model file is missing for: {model_choice}")
if traffic_df.empty:
st.error("Dashboard sample traffic file not found.")
st.stop()
max_index = len(traffic_df) - 1
selected_index = st.slider(
"Select traffic record index",
min_value=0,
max_value=max_index,
value=0,
step=1
)
row = traffic_df.iloc[selected_index]
label, probability, severity, icon = predict_single(row, active_model)
col1, col2, col3, col4, col5 = st.columns(5)
col1.metric("Prediction", label)
col2.metric("Attack Probability", f"{probability * 100:.3f}%")
col3.metric("Threat Severity", f"{icon} {severity}")
col4.metric("Actual Category", str(row.get("attack_category", "Unknown")))
col5.metric("Model Used", model_choice.split(" Binary")[0])
st.markdown("### Traffic Record Features")
st.dataframe(row[selected_features].to_frame(name="Value"), use_container_width=True)
st.markdown("### Manual Simulation")
if st.button("Run Next 10 Records"):
logs = []
progress = st.progress(0)
total_to_run = min(10, len(traffic_df) - selected_index)
for offset, i in enumerate(range(selected_index, selected_index + total_to_run)):
current_row = traffic_df.iloc[i]
pred_label, prob, sev, sev_icon = predict_single(current_row, active_model)
logs.append({
"time": datetime.now().strftime("%H:%M:%S"),
"index": i,
"model_used": model_choice,
"prediction": pred_label,
"attack_probability": round(prob * 100, 3),
"severity": sev,
"actual_category": current_row.get("attack_category", "Unknown")
})
progress.progress((offset + 1) / total_to_run)
time.sleep(0.1)
st.dataframe(pd.DataFrame(logs), use_container_width=True)
# ---------------------------------------------------------
# Explainability Page
# ---------------------------------------------------------
elif page == "Explainability":
st.title("π§ SHAP Explainability")
st.markdown("""
SHAP is used to explain how each feature contributes to model predictions.
Positive SHAP values generally push predictions toward **Attack**, while negative SHAP values
push predictions toward **Benign**.
""")
tab1, tab2 = st.tabs([
"Original CICIoT2023 Model SHAP",
"Combined Model SHAP"
])
with tab1:
st.markdown("## Original CICIoT2023 Model Explainability")
if shap_importance_df is not None and not shap_importance_df.empty:
top_n = st.slider("Number of top original-model features", 5, 20, 10, key="orig_shap_slider")
top_shap = shap_importance_df.head(top_n)
fig = px.bar(
top_shap.sort_values("mean_abs_shap"),
x="mean_abs_shap",
y="feature",
orientation="h",
title="Top Global SHAP Features - Original CICIoT2023 Model"
)
st.plotly_chart(fig, use_container_width=True)
else:
st.info("Original SHAP importance CSV not found.")
st.markdown("### Saved Original SHAP Plots")
col1, col2 = st.columns(2)
with col1:
show_image_if_exists(SHAP_BAR_IMAGE, "Original Global SHAP Bar Plot")
with col2:
show_image_if_exists(SHAP_SUMMARY_IMAGE, "Original SHAP Beeswarm Plot")
st.markdown("### Original Sample Local Explanation")
if local_explanation is not None:
st.json(local_explanation)
else:
st.info("Original local explanation JSON not found.")
with tab2:
st.markdown("## Combined CICIoT2023 + UNSW-NB15 Model Explainability")
st.markdown("""
The combined model was explained separately on CICIoT2023 and UNSW-NB15 samples.
This helps show how feature importance changes across datasets.
""")
subtab1, subtab2, subtab3, subtab4 = st.tabs([
"UNSW SHAP",
"CICIoT SHAP",
"Feature Comparison",
"Local Explanations"
])
with subtab1:
st.markdown("### UNSW-NB15 Global SHAP Importance")
if combined_shap_unsw_df is not None and not combined_shap_unsw_df.empty:
top_n_unsw = st.slider("Top UNSW SHAP features", 5, 20, 10, key="unsw_shap_slider")
top_unsw = combined_shap_unsw_df.head(top_n_unsw)
fig = px.bar(
top_unsw.sort_values("mean_abs_shap"),
x="mean_abs_shap",
y="feature",
orientation="h",
title="Combined Model SHAP Importance on UNSW-NB15"
)
st.plotly_chart(fig, use_container_width=True)
st.dataframe(combined_shap_unsw_df.head(20), use_container_width=True)
else:
st.info("UNSW combined SHAP CSV not found.")
show_image_if_exists(COMBINED_SHAP_GRAPHS["UNSW-NB15 SHAP Bar Plot"], "UNSW-NB15 SHAP Bar Plot")
show_image_if_exists(COMBINED_SHAP_GRAPHS["UNSW-NB15 SHAP Beeswarm Plot"], "UNSW-NB15 SHAP Beeswarm Plot")
with subtab2:
st.markdown("### CICIoT2023 Global SHAP Importance")
if combined_shap_ciciot_df is not None and not combined_shap_ciciot_df.empty:
top_n_ciciot = st.slider("Top CICIoT SHAP features", 5, 20, 10, key="ciciot_shap_slider")
top_ciciot = combined_shap_ciciot_df.head(top_n_ciciot)
fig = px.bar(
top_ciciot.sort_values("mean_abs_shap"),
x="mean_abs_shap",
y="feature",
orientation="h",
title="Combined Model SHAP Importance on CICIoT2023"
)
st.plotly_chart(fig, use_container_width=True)
st.dataframe(combined_shap_ciciot_df.head(20), use_container_width=True)
else:
st.info("CICIoT combined SHAP CSV not found.")
show_image_if_exists(COMBINED_SHAP_GRAPHS["CICIoT2023 SHAP Bar Plot"], "CICIoT2023 SHAP Bar Plot")
show_image_if_exists(COMBINED_SHAP_GRAPHS["CICIoT2023 SHAP Beeswarm Plot"], "CICIoT2023 SHAP Beeswarm Plot")
with subtab3:
st.markdown("### Top Feature Comparison: UNSW-NB15 vs CICIoT2023")
if combined_shap_compare_df is not None and not combined_shap_compare_df.empty:
st.dataframe(combined_shap_compare_df, use_container_width=True)
st.markdown("""
This comparison shows that some features are important across both datasets,
while others are dataset-specific. This supports the domain-shift finding from
Experiment 05-A.
""")
else:
st.info("Combined SHAP comparison CSV not found.")
with subtab4:
st.markdown("### Local Explanation: UNSW-NB15 Sample")
if combined_local_unsw is not None:
st.json(combined_local_unsw)
else:
st.info("UNSW local explanation JSON not found.")
st.markdown("### Local Explanation: CICIoT2023 Sample")
if combined_local_ciciot is not None:
st.json(combined_local_ciciot)
else:
st.info("CICIoT local explanation JSON not found.")
# ---------------------------------------------------------
# Dataset & Features Page
# ---------------------------------------------------------
elif page == "Dataset & Features":
st.title("π§Ύ Dataset & Features")
st.markdown("""
WiGuard uses a shared **44-feature representation** for model training and prediction.
CICIoT2023 already contains these selected features, while UNSW-NB15 was mapped into this
format for cross-dataset and combined training.
""")
st.markdown("## Final Selected WiGuard Features")
feature_df = pd.DataFrame({"Feature": selected_features})
st.dataframe(feature_df, use_container_width=True)
st.markdown("---")
st.markdown("## UNSW-NB15 Feature Mapping")
mapping_df = pd.DataFrame([
{"WiGuard Feature": "flow_duration", "UNSW-NB15 Mapping": "dur", "Mapping Type": "Direct"},
{"WiGuard Feature": "duration", "UNSW-NB15 Mapping": "dur", "Mapping Type": "Direct"},
{"WiGuard Feature": "rate", "UNSW-NB15 Mapping": "rate", "Mapping Type": "Direct"},
{"WiGuard Feature": "srate", "UNSW-NB15 Mapping": "sload", "Mapping Type": "Approximate"},
{"WiGuard Feature": "drate", "UNSW-NB15 Mapping": "dload", "Mapping Type": "Approximate"},
{"WiGuard Feature": "protocol_type", "UNSW-NB15 Mapping": "encoded proto", "Mapping Type": "Derived"},
{"WiGuard Feature": "tcp", "UNSW-NB15 Mapping": "proto == tcp", "Mapping Type": "Derived"},
{"WiGuard Feature": "udp", "UNSW-NB15 Mapping": "proto == udp", "Mapping Type": "Derived"},
{"WiGuard Feature": "icmp", "UNSW-NB15 Mapping": "proto == icmp", "Mapping Type": "Derived"},
{"WiGuard Feature": "http", "UNSW-NB15 Mapping": "service == http", "Mapping Type": "Derived"},
{"WiGuard Feature": "dns", "UNSW-NB15 Mapping": "service == dns", "Mapping Type": "Derived"},
{"WiGuard Feature": "smtp", "UNSW-NB15 Mapping": "service == smtp", "Mapping Type": "Derived"},
{"WiGuard Feature": "ssh", "UNSW-NB15 Mapping": "service == ssh", "Mapping Type": "Derived"},
{"WiGuard Feature": "tot_sum", "UNSW-NB15 Mapping": "sbytes + dbytes", "Mapping Type": "Derived"},
{"WiGuard Feature": "tot_size", "UNSW-NB15 Mapping": "sbytes + dbytes", "Mapping Type": "Derived"},
{"WiGuard Feature": "number", "UNSW-NB15 Mapping": "spkts + dpkts", "Mapping Type": "Derived"},
{"WiGuard Feature": "avg", "UNSW-NB15 Mapping": "(sbytes + dbytes) / (spkts + dpkts)", "Mapping Type": "Derived"},
{"WiGuard Feature": "iat", "UNSW-NB15 Mapping": "mean(sinpkt, dinpkt)", "Mapping Type": "Approximate"},
{"WiGuard Feature": "header_length", "UNSW-NB15 Mapping": "(spkts + dpkts) Γ 20", "Mapping Type": "Approximate"},
])
st.dataframe(mapping_df, use_container_width=True)
st.info("""
Some CICIoT2023-style features do not have exact equivalents in UNSW-NB15.
These were either approximated using similar UNSW-NB15 fields or filled with zero.
This is why direct zero-shot transfer performed poorly, while combined training worked better.
""")
st.markdown("---")
st.markdown("## UNSW-NB15 Imbalance Analysis")
show_csv_if_exists(unsw_binary_imbalance_df, "### Binary Class Imbalance")
show_csv_if_exists(unsw_attack_imbalance_df, "### Attack Category Imbalance")
st.markdown("---")
st.markdown("## Dashboard Sample Data")
if not traffic_df.empty:
st.write("Shape:", traffic_df.shape)
st.dataframe(traffic_df.head(20), use_container_width=True)
else:
st.warning("Dashboard sample traffic data not found.")
# ---------------------------------------------------------
# Attack Logs Page
# ---------------------------------------------------------
elif page == "Attack Logs":
st.title("π Attack Logs")
st.markdown("""
This page generates prediction logs from a batch of simulated traffic samples.
The logs now include the selected model name.
""")
available_models = {
"Original CICIoT2023 Binary Model": ciciot_model,
"Combined CICIoT2023 + UNSW-NB15 Binary Model": combined_model,
}
model_choice = st.selectbox(
"Select model for log generation",
list(available_models.keys()),
key="logs_model_choice"
)
active_model = available_models[model_choice]
if traffic_df.empty:
st.error("Dashboard sample traffic file not found.")
st.stop()
batch_size = st.slider("Number of records to process", 10, 500, 50)
if st.button("Generate Logs"):
sample_batch = traffic_df.sample(n=min(batch_size, len(traffic_df)), random_state=42)
logs = []
for idx, row in sample_batch.iterrows():
pred_label, prob, sev, sev_icon = predict_single(row, active_model)
logs.append({
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"record_index": idx,
"model_used": model_choice,
"prediction": pred_label,
"attack_probability": round(prob * 100, 3),
"severity": sev,
"actual_category": row.get("attack_category", "Unknown")
})
logs_df = pd.DataFrame(logs)
st.dataframe(logs_df, use_container_width=True)
csv = logs_df.to_csv(index=False).encode("utf-8")
st.download_button(
label="Download Logs as CSV",
data=csv,
file_name="wiguard_attack_logs.csv",
mime="text/csv"
)
|