Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,3 @@
|
|
| 1 |
-
|
| 2 |
import streamlit as st
|
| 3 |
import pandas as pd
|
| 4 |
import numpy as np
|
|
@@ -8,7 +7,6 @@ import os
|
|
| 8 |
import time
|
| 9 |
from datetime import datetime
|
| 10 |
import plotly.express as px
|
| 11 |
-
import plotly.graph_objects as go
|
| 12 |
from PIL import Image
|
| 13 |
|
| 14 |
# ---------------------------------------------------------
|
|
@@ -23,63 +21,119 @@ st.set_page_config(
|
|
| 23 |
# ---------------------------------------------------------
|
| 24 |
# File Paths
|
| 25 |
# ---------------------------------------------------------
|
| 26 |
-
|
|
|
|
| 27 |
FEATURES_PATH = "models/selected_features.pkl"
|
|
|
|
| 28 |
RESULTS_PATH = "models/model_results.json"
|
| 29 |
RF_RESULTS_PATH = "models/random_forest_results.json"
|
| 30 |
|
| 31 |
DASHBOARD_DATA_PATH = "dashboard_data/dashboard_sample_traffic.csv"
|
| 32 |
|
|
|
|
| 33 |
SHAP_IMPORTANCE_PATH = "shap_outputs/global_shap_feature_importance.csv"
|
| 34 |
SHAP_LOCAL_PATH = "shap_outputs/sample_local_explanation.json"
|
| 35 |
SHAP_BAR_IMAGE = "shap_outputs/shap_global_bar.png"
|
| 36 |
SHAP_SUMMARY_IMAGE = "shap_outputs/shap_summary_beeswarm.png"
|
| 37 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
# ---------------------------------------------------------
|
| 39 |
-
#
|
| 40 |
# ---------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
| 41 |
@st.cache_resource
|
| 42 |
-
def load_model():
|
| 43 |
-
|
|
|
|
|
|
|
| 44 |
|
| 45 |
@st.cache_data
|
| 46 |
-
def
|
| 47 |
-
|
|
|
|
|
|
|
| 48 |
|
| 49 |
@st.cache_data
|
| 50 |
-
def
|
| 51 |
-
|
| 52 |
-
|
|
|
|
|
|
|
| 53 |
|
| 54 |
@st.cache_data
|
| 55 |
-
def
|
| 56 |
-
if os.path.exists(
|
| 57 |
-
|
| 58 |
-
return json.load(f)
|
| 59 |
return None
|
| 60 |
|
| 61 |
@st.cache_data
|
| 62 |
def load_dashboard_data():
|
| 63 |
-
|
|
|
|
|
|
|
| 64 |
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
|
|
|
|
|
|
| 68 |
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
with open(SHAP_LOCAL_PATH, "r") as f:
|
| 73 |
-
return json.load(f)
|
| 74 |
-
return None
|
| 75 |
|
| 76 |
-
model = load_model()
|
| 77 |
-
selected_features = load_features()
|
| 78 |
-
results = load_results()
|
| 79 |
-
rf_results = load_rf_results()
|
| 80 |
traffic_df = load_dashboard_data()
|
| 81 |
-
|
| 82 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
|
| 84 |
# ---------------------------------------------------------
|
| 85 |
# Helper Functions
|
|
@@ -94,35 +148,64 @@ def get_severity(probability):
|
|
| 94 |
else:
|
| 95 |
return "Critical", "🔴"
|
| 96 |
|
| 97 |
-
def
|
| 98 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
X = pd.DataFrame([row[selected_features].to_dict()])
|
| 100 |
|
| 101 |
-
# Force all model features to numeric because Streamlit/pandas row selection
|
| 102 |
-
# can sometimes convert numeric values into object/string dtype.
|
| 103 |
for col in selected_features:
|
| 104 |
X[col] = pd.to_numeric(X[col], errors="coerce")
|
| 105 |
|
| 106 |
-
# Replace any unexpected missing values with 0
|
| 107 |
X = X.fillna(0)
|
| 108 |
-
|
| 109 |
-
# Keep exact feature order used during training
|
| 110 |
X = X[selected_features]
|
| 111 |
-
|
| 112 |
-
# Convert to float for XGBoost
|
| 113 |
X = X.astype(float)
|
| 114 |
|
| 115 |
-
prediction = int(
|
| 116 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
severity, icon = get_severity(probability)
|
| 118 |
label = "Attack" if prediction == 1 else "Benign"
|
| 119 |
-
return label, probability, severity, icon
|
| 120 |
|
| 121 |
-
|
| 122 |
-
st.metric(title, value)
|
| 123 |
|
| 124 |
-
def
|
| 125 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
|
| 127 |
# ---------------------------------------------------------
|
| 128 |
# Sidebar
|
|
@@ -143,9 +226,9 @@ page = st.sidebar.radio(
|
|
| 143 |
)
|
| 144 |
|
| 145 |
st.sidebar.markdown("---")
|
| 146 |
-
st.sidebar.write("**
|
| 147 |
st.sidebar.write("**XAI:** SHAP")
|
| 148 |
-
st.sidebar.write("**
|
| 149 |
st.sidebar.write("**Mode:** Benchmark Traffic Simulation")
|
| 150 |
|
| 151 |
# ---------------------------------------------------------
|
|
@@ -153,39 +236,43 @@ st.sidebar.write("**Mode:** Benchmark Traffic Simulation")
|
|
| 153 |
# ---------------------------------------------------------
|
| 154 |
if page == "Home":
|
| 155 |
st.title("🛡️ WiGuard")
|
| 156 |
-
st.subheader("Explainable AI-Based Network Intrusion Detection System")
|
| 157 |
|
| 158 |
st.markdown("""
|
| 159 |
**WiGuard** is an explainable intrusion detection framework designed to classify
|
| 160 |
-
|
| 161 |
|
| 162 |
-
The system
|
| 163 |
-
|
| 164 |
-
|
| 165 |
""")
|
| 166 |
|
| 167 |
-
col1, col2, col3 = st.columns(
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
with col3:
|
| 173 |
-
st.info("Explainability: SHAP")
|
| 174 |
|
| 175 |
-
st.markdown("###
|
| 176 |
st.markdown("""
|
| 177 |
-
1. Load CICIoT2023 traffic
|
| 178 |
-
2. Clean and preprocess
|
| 179 |
-
3.
|
| 180 |
-
4.
|
| 181 |
-
5.
|
| 182 |
-
6.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 183 |
""")
|
| 184 |
|
| 185 |
st.warning("""
|
| 186 |
-
This deployed version uses
|
| 187 |
-
Live Wireshark/tshark packet capture
|
| 188 |
-
|
| 189 |
""")
|
| 190 |
|
| 191 |
# ---------------------------------------------------------
|
|
@@ -194,65 +281,77 @@ if page == "Home":
|
|
| 194 |
elif page == "Model Performance":
|
| 195 |
st.title("📊 Model Performance")
|
| 196 |
|
| 197 |
-
|
| 198 |
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
col2.metric("Precision", format_percent(test_results["precision"]))
|
| 202 |
-
col3.metric("Recall", format_percent(test_results["recall"]))
|
| 203 |
-
col4.metric("F1 Score", format_percent(test_results["f1_score"]))
|
| 204 |
-
col5.metric("ROC-AUC", format_percent(test_results["roc_auc"]))
|
| 205 |
|
| 206 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 207 |
|
| 208 |
-
|
| 209 |
|
| 210 |
-
|
| 211 |
-
cm,
|
| 212 |
-
text_auto=True,
|
| 213 |
-
labels=dict(x="Predicted Label", y="Actual Label", color="Count"),
|
| 214 |
-
x=["Benign", "Attack"],
|
| 215 |
-
y=["Benign", "Attack"],
|
| 216 |
-
title="XGBoost Confusion Matrix on Test Set"
|
| 217 |
-
)
|
| 218 |
-
st.plotly_chart(fig, use_container_width=True)
|
| 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 |
-
if
|
| 245 |
-
|
| 246 |
-
"Model": "Random Forest Baseline",
|
| 247 |
-
"Accuracy": rf_results["accuracy"],
|
| 248 |
-
"Precision": rf_results["precision"],
|
| 249 |
-
"Recall": rf_results["recall"],
|
| 250 |
-
"F1 Score": rf_results["f1_score"],
|
| 251 |
-
"ROC-AUC": rf_results["roc_auc"]
|
| 252 |
-
})
|
| 253 |
|
| 254 |
-
|
| 255 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 256 |
|
| 257 |
# ---------------------------------------------------------
|
| 258 |
# Live Traffic Simulation Page
|
|
@@ -261,10 +360,29 @@ elif page == "Live Traffic Simulation":
|
|
| 261 |
st.title("📡 Live Traffic Simulation")
|
| 262 |
|
| 263 |
st.markdown("""
|
| 264 |
-
This page simulates incoming network-flow records using
|
| 265 |
-
|
| 266 |
""")
|
| 267 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 268 |
max_index = len(traffic_df) - 1
|
| 269 |
|
| 270 |
selected_index = st.slider(
|
|
@@ -277,37 +395,42 @@ elif page == "Live Traffic Simulation":
|
|
| 277 |
|
| 278 |
row = traffic_df.iloc[selected_index]
|
| 279 |
|
| 280 |
-
label, probability, severity, icon = predict_single(row)
|
| 281 |
|
| 282 |
-
col1, col2, col3, col4 = st.columns(
|
| 283 |
col1.metric("Prediction", label)
|
| 284 |
col2.metric("Attack Probability", f"{probability * 100:.3f}%")
|
| 285 |
col3.metric("Threat Severity", f"{icon} {severity}")
|
| 286 |
col4.metric("Actual Category", str(row.get("attack_category", "Unknown")))
|
|
|
|
| 287 |
|
| 288 |
st.markdown("### Traffic Record Features")
|
| 289 |
st.dataframe(row[selected_features].to_frame(name="Value"), use_container_width=True)
|
| 290 |
|
| 291 |
st.markdown("### Manual Simulation")
|
|
|
|
| 292 |
if st.button("Run Next 10 Records"):
|
| 293 |
logs = []
|
| 294 |
progress = st.progress(0)
|
| 295 |
|
| 296 |
-
|
|
|
|
|
|
|
| 297 |
current_row = traffic_df.iloc[i]
|
| 298 |
-
pred_label, prob, sev, sev_icon = predict_single(current_row)
|
| 299 |
|
| 300 |
logs.append({
|
| 301 |
"time": datetime.now().strftime("%H:%M:%S"),
|
| 302 |
"index": i,
|
|
|
|
| 303 |
"prediction": pred_label,
|
| 304 |
"attack_probability": round(prob * 100, 3),
|
| 305 |
"severity": sev,
|
| 306 |
"actual_category": current_row.get("attack_category", "Unknown")
|
| 307 |
})
|
| 308 |
|
| 309 |
-
progress.progress((
|
| 310 |
-
time.sleep(0.
|
| 311 |
|
| 312 |
st.dataframe(pd.DataFrame(logs), use_container_width=True)
|
| 313 |
|
|
@@ -318,44 +441,129 @@ elif page == "Explainability":
|
|
| 318 |
st.title("🧠 SHAP Explainability")
|
| 319 |
|
| 320 |
st.markdown("""
|
| 321 |
-
SHAP is used to explain how each feature contributes to
|
| 322 |
-
Positive SHAP
|
| 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 |
-
st.
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
st.
|
| 357 |
-
|
| 358 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 359 |
|
| 360 |
# ---------------------------------------------------------
|
| 361 |
# Dataset & Features Page
|
|
@@ -364,26 +572,64 @@ elif page == "Dataset & Features":
|
|
| 364 |
st.title("🧾 Dataset & Features")
|
| 365 |
|
| 366 |
st.markdown("""
|
| 367 |
-
|
| 368 |
-
|
|
|
|
| 369 |
""")
|
| 370 |
|
| 371 |
-
st.markdown("##
|
|
|
|
| 372 |
feature_df = pd.DataFrame({"Feature": selected_features})
|
| 373 |
st.dataframe(feature_df, use_container_width=True)
|
| 374 |
|
| 375 |
-
st.markdown("
|
| 376 |
-
st.
|
| 377 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 378 |
|
| 379 |
-
st.markdown("### Notes")
|
| 380 |
st.info("""
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
module is implemented.
|
| 385 |
""")
|
| 386 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 387 |
# ---------------------------------------------------------
|
| 388 |
# Attack Logs Page
|
| 389 |
# ---------------------------------------------------------
|
|
@@ -391,22 +637,41 @@ elif page == "Attack Logs":
|
|
| 391 |
st.title("📜 Attack Logs")
|
| 392 |
|
| 393 |
st.markdown("""
|
| 394 |
-
This page generates prediction logs from a batch of traffic samples.
|
|
|
|
| 395 |
""")
|
| 396 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 397 |
batch_size = st.slider("Number of records to process", 10, 500, 50)
|
| 398 |
|
| 399 |
if st.button("Generate Logs"):
|
| 400 |
-
sample_batch = traffic_df.sample(n=batch_size, random_state=42)
|
| 401 |
|
| 402 |
logs = []
|
| 403 |
|
| 404 |
for idx, row in sample_batch.iterrows():
|
| 405 |
-
pred_label, prob, sev, sev_icon = predict_single(row)
|
| 406 |
|
| 407 |
logs.append({
|
| 408 |
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
| 409 |
"record_index": idx,
|
|
|
|
| 410 |
"prediction": pred_label,
|
| 411 |
"attack_probability": round(prob * 100, 3),
|
| 412 |
"severity": sev,
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
import pandas as pd
|
| 3 |
import numpy as np
|
|
|
|
| 7 |
import time
|
| 8 |
from datetime import datetime
|
| 9 |
import plotly.express as px
|
|
|
|
| 10 |
from PIL import Image
|
| 11 |
|
| 12 |
# ---------------------------------------------------------
|
|
|
|
| 21 |
# ---------------------------------------------------------
|
| 22 |
# File Paths
|
| 23 |
# ---------------------------------------------------------
|
| 24 |
+
CICIOT_MODEL_PATH = "models/xgboost_wiguard_full.pkl"
|
| 25 |
+
COMBINED_MODEL_PATH = "models/xgboost_combined_ciciot_unsw_binary.pkl"
|
| 26 |
FEATURES_PATH = "models/selected_features.pkl"
|
| 27 |
+
|
| 28 |
RESULTS_PATH = "models/model_results.json"
|
| 29 |
RF_RESULTS_PATH = "models/random_forest_results.json"
|
| 30 |
|
| 31 |
DASHBOARD_DATA_PATH = "dashboard_data/dashboard_sample_traffic.csv"
|
| 32 |
|
| 33 |
+
# Original CICIoT SHAP outputs
|
| 34 |
SHAP_IMPORTANCE_PATH = "shap_outputs/global_shap_feature_importance.csv"
|
| 35 |
SHAP_LOCAL_PATH = "shap_outputs/sample_local_explanation.json"
|
| 36 |
SHAP_BAR_IMAGE = "shap_outputs/shap_global_bar.png"
|
| 37 |
SHAP_SUMMARY_IMAGE = "shap_outputs/shap_summary_beeswarm.png"
|
| 38 |
|
| 39 |
+
# Experiment 05 outputs
|
| 40 |
+
EXP05_COMPARISON_PATH = "experiment_outputs/experiment_05_comparison_table.csv"
|
| 41 |
+
EXP05_SUMMARY_PATH = "experiment_outputs/experiment_05c_combined_model_summary.json"
|
| 42 |
+
UNSW_BINARY_IMBALANCE_PATH = "experiment_outputs/unsw_binary_imbalance_summary.csv"
|
| 43 |
+
UNSW_ATTACK_IMBALANCE_PATH = "experiment_outputs/unsw_attack_category_imbalance_summary.csv"
|
| 44 |
+
|
| 45 |
+
EXP05_GRAPH_DIR = "experiment_outputs/graphs"
|
| 46 |
+
|
| 47 |
+
EXP05_GRAPHS = {
|
| 48 |
+
"Experiment 05 Metrics Comparison": f"{EXP05_GRAPH_DIR}/experiment_05_metrics_comparison.png",
|
| 49 |
+
"Experiment 05 Accuracy Comparison": f"{EXP05_GRAPH_DIR}/experiment_05_accuracy_comparison.png",
|
| 50 |
+
"Direct Transfer vs Combined Model on UNSW-NB15": f"{EXP05_GRAPH_DIR}/experiment_05_direct_transfer_vs_combined_unsw.png",
|
| 51 |
+
"Combined Model Confusion Matrix on UNSW-NB15": f"{EXP05_GRAPH_DIR}/experiment_05c_combined_model_unsw_confusion_matrix.png",
|
| 52 |
+
"Combined Model Confusion Matrix on CICIoT2023": f"{EXP05_GRAPH_DIR}/experiment_05c_combined_model_ciciot_confusion_matrix.png",
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
# Combined model SHAP outputs
|
| 56 |
+
COMBINED_SHAP_DIR = "shap_outputs/combined_model"
|
| 57 |
+
COMBINED_SHAP_GRAPH_DIR = f"{COMBINED_SHAP_DIR}/graphs"
|
| 58 |
+
|
| 59 |
+
COMBINED_SHAP_UNSW_PATH = f"{COMBINED_SHAP_DIR}/shap_importance_unsw_combined_model.csv"
|
| 60 |
+
COMBINED_SHAP_CICIOT_PATH = f"{COMBINED_SHAP_DIR}/shap_importance_ciciot_combined_model.csv"
|
| 61 |
+
COMBINED_SHAP_COMPARE_PATH = f"{COMBINED_SHAP_DIR}/shap_top_feature_comparison_unsw_vs_ciciot.csv"
|
| 62 |
+
COMBINED_LOCAL_UNSW_PATH = f"{COMBINED_SHAP_DIR}/local_explanation_unsw_sample.json"
|
| 63 |
+
COMBINED_LOCAL_CICIOT_PATH = f"{COMBINED_SHAP_DIR}/local_explanation_ciciot_sample.json"
|
| 64 |
+
|
| 65 |
+
COMBINED_SHAP_GRAPHS = {
|
| 66 |
+
"UNSW-NB15 SHAP Bar Plot": f"{COMBINED_SHAP_GRAPH_DIR}/shap_bar_unsw_combined_model.png",
|
| 67 |
+
"CICIoT2023 SHAP Bar Plot": f"{COMBINED_SHAP_GRAPH_DIR}/shap_bar_ciciot_combined_model.png",
|
| 68 |
+
"UNSW-NB15 SHAP Beeswarm Plot": f"{COMBINED_SHAP_GRAPH_DIR}/shap_beeswarm_unsw_combined_model.png",
|
| 69 |
+
"CICIoT2023 SHAP Beeswarm Plot": f"{COMBINED_SHAP_GRAPH_DIR}/shap_beeswarm_ciciot_combined_model.png",
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
# ---------------------------------------------------------
|
| 73 |
+
# Safe Loading Helpers
|
| 74 |
# ---------------------------------------------------------
|
| 75 |
+
def file_exists(path):
|
| 76 |
+
return os.path.exists(path)
|
| 77 |
+
|
| 78 |
@st.cache_resource
|
| 79 |
+
def load_model(path):
|
| 80 |
+
if os.path.exists(path):
|
| 81 |
+
return joblib.load(path)
|
| 82 |
+
return None
|
| 83 |
|
| 84 |
@st.cache_data
|
| 85 |
+
def load_pickle_file(path):
|
| 86 |
+
if os.path.exists(path):
|
| 87 |
+
return joblib.load(path)
|
| 88 |
+
return None
|
| 89 |
|
| 90 |
@st.cache_data
|
| 91 |
+
def load_json_file(path):
|
| 92 |
+
if os.path.exists(path):
|
| 93 |
+
with open(path, "r") as f:
|
| 94 |
+
return json.load(f)
|
| 95 |
+
return None
|
| 96 |
|
| 97 |
@st.cache_data
|
| 98 |
+
def load_csv_file(path):
|
| 99 |
+
if os.path.exists(path):
|
| 100 |
+
return pd.read_csv(path)
|
|
|
|
| 101 |
return None
|
| 102 |
|
| 103 |
@st.cache_data
|
| 104 |
def load_dashboard_data():
|
| 105 |
+
if os.path.exists(DASHBOARD_DATA_PATH):
|
| 106 |
+
return pd.read_csv(DASHBOARD_DATA_PATH)
|
| 107 |
+
return pd.DataFrame()
|
| 108 |
|
| 109 |
+
# ---------------------------------------------------------
|
| 110 |
+
# Load Assets
|
| 111 |
+
# ---------------------------------------------------------
|
| 112 |
+
ciciot_model = load_model(CICIOT_MODEL_PATH)
|
| 113 |
+
combined_model = load_model(COMBINED_MODEL_PATH)
|
| 114 |
|
| 115 |
+
selected_features = load_pickle_file(FEATURES_PATH)
|
| 116 |
+
results = load_json_file(RESULTS_PATH)
|
| 117 |
+
rf_results = load_json_file(RF_RESULTS_PATH)
|
|
|
|
|
|
|
|
|
|
| 118 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
traffic_df = load_dashboard_data()
|
| 120 |
+
|
| 121 |
+
shap_importance_df = load_csv_file(SHAP_IMPORTANCE_PATH)
|
| 122 |
+
local_explanation = load_json_file(SHAP_LOCAL_PATH)
|
| 123 |
+
|
| 124 |
+
exp05_comparison_df = load_csv_file(EXP05_COMPARISON_PATH)
|
| 125 |
+
exp05_summary = load_json_file(EXP05_SUMMARY_PATH)
|
| 126 |
+
unsw_binary_imbalance_df = load_csv_file(UNSW_BINARY_IMBALANCE_PATH)
|
| 127 |
+
unsw_attack_imbalance_df = load_csv_file(UNSW_ATTACK_IMBALANCE_PATH)
|
| 128 |
+
|
| 129 |
+
combined_shap_unsw_df = load_csv_file(COMBINED_SHAP_UNSW_PATH)
|
| 130 |
+
combined_shap_ciciot_df = load_csv_file(COMBINED_SHAP_CICIOT_PATH)
|
| 131 |
+
combined_shap_compare_df = load_csv_file(COMBINED_SHAP_COMPARE_PATH)
|
| 132 |
+
combined_local_unsw = load_json_file(COMBINED_LOCAL_UNSW_PATH)
|
| 133 |
+
combined_local_ciciot = load_json_file(COMBINED_LOCAL_CICIOT_PATH)
|
| 134 |
+
|
| 135 |
+
if selected_features is None:
|
| 136 |
+
selected_features = []
|
| 137 |
|
| 138 |
# ---------------------------------------------------------
|
| 139 |
# Helper Functions
|
|
|
|
| 148 |
else:
|
| 149 |
return "Critical", "🔴"
|
| 150 |
|
| 151 |
+
def format_percent(x):
|
| 152 |
+
try:
|
| 153 |
+
return f"{float(x) * 100:.3f}%"
|
| 154 |
+
except Exception:
|
| 155 |
+
return "N/A"
|
| 156 |
+
|
| 157 |
+
def show_image_if_exists(path, caption=None):
|
| 158 |
+
if os.path.exists(path):
|
| 159 |
+
st.image(Image.open(path), caption=caption, use_container_width=True)
|
| 160 |
+
else:
|
| 161 |
+
st.warning(f"Image not found: {path}")
|
| 162 |
+
|
| 163 |
+
def show_csv_if_exists(df, title=None):
|
| 164 |
+
if title:
|
| 165 |
+
st.markdown(title)
|
| 166 |
+
if df is not None and not df.empty:
|
| 167 |
+
st.dataframe(df, use_container_width=True)
|
| 168 |
+
else:
|
| 169 |
+
st.info("File not found or empty.")
|
| 170 |
+
|
| 171 |
+
def predict_single(row, active_model):
|
| 172 |
+
if active_model is None:
|
| 173 |
+
return "Model Missing", 0.0, "Unknown", "⚪"
|
| 174 |
+
|
| 175 |
+
if len(selected_features) == 0:
|
| 176 |
+
return "Features Missing", 0.0, "Unknown", "⚪"
|
| 177 |
+
|
| 178 |
X = pd.DataFrame([row[selected_features].to_dict()])
|
| 179 |
|
|
|
|
|
|
|
| 180 |
for col in selected_features:
|
| 181 |
X[col] = pd.to_numeric(X[col], errors="coerce")
|
| 182 |
|
|
|
|
| 183 |
X = X.fillna(0)
|
|
|
|
|
|
|
| 184 |
X = X[selected_features]
|
|
|
|
|
|
|
| 185 |
X = X.astype(float)
|
| 186 |
|
| 187 |
+
prediction = int(active_model.predict(X)[0])
|
| 188 |
+
|
| 189 |
+
if hasattr(active_model, "predict_proba"):
|
| 190 |
+
probability = float(active_model.predict_proba(X)[0][1])
|
| 191 |
+
else:
|
| 192 |
+
probability = float(prediction)
|
| 193 |
+
|
| 194 |
severity, icon = get_severity(probability)
|
| 195 |
label = "Attack" if prediction == 1 else "Benign"
|
|
|
|
| 196 |
|
| 197 |
+
return label, probability, severity, icon
|
|
|
|
| 198 |
|
| 199 |
+
def display_confusion_matrix(cm, title, labels=("Benign", "Attack")):
|
| 200 |
+
fig = px.imshow(
|
| 201 |
+
cm,
|
| 202 |
+
text_auto=True,
|
| 203 |
+
labels=dict(x="Predicted Label", y="Actual Label", color="Count"),
|
| 204 |
+
x=list(labels),
|
| 205 |
+
y=list(labels),
|
| 206 |
+
title=title
|
| 207 |
+
)
|
| 208 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 209 |
|
| 210 |
# ---------------------------------------------------------
|
| 211 |
# Sidebar
|
|
|
|
| 226 |
)
|
| 227 |
|
| 228 |
st.sidebar.markdown("---")
|
| 229 |
+
st.sidebar.write("**Models:** XGBoost")
|
| 230 |
st.sidebar.write("**XAI:** SHAP")
|
| 231 |
+
st.sidebar.write("**Datasets:** CICIoT2023 + UNSW-NB15")
|
| 232 |
st.sidebar.write("**Mode:** Benchmark Traffic Simulation")
|
| 233 |
|
| 234 |
# ---------------------------------------------------------
|
|
|
|
| 236 |
# ---------------------------------------------------------
|
| 237 |
if page == "Home":
|
| 238 |
st.title("🛡️ WiGuard")
|
| 239 |
+
st.subheader("Explainable AI-Based Network / IoT Intrusion Detection System")
|
| 240 |
|
| 241 |
st.markdown("""
|
| 242 |
**WiGuard** is an explainable intrusion detection framework designed to classify
|
| 243 |
+
network-flow traffic as **Benign** or **Attack** using XGBoost models.
|
| 244 |
|
| 245 |
+
The system now includes both the original **CICIoT2023-based model** and a newer
|
| 246 |
+
**combined CICIoT2023 + UNSW-NB15 model** trained using a shared 44-feature WiGuard representation.
|
| 247 |
+
SHAP explainability is used to explain model behavior globally and locally.
|
| 248 |
""")
|
| 249 |
|
| 250 |
+
col1, col2, col3, col4 = st.columns(4)
|
| 251 |
+
col1.info("Datasets: CICIoT2023 + UNSW-NB15")
|
| 252 |
+
col2.info("Models: XGBoost")
|
| 253 |
+
col3.info("Explainability: SHAP")
|
| 254 |
+
col4.info("Feature Space: 44 WiGuard Features")
|
|
|
|
|
|
|
| 255 |
|
| 256 |
+
st.markdown("### Updated WiGuard Pipeline")
|
| 257 |
st.markdown("""
|
| 258 |
+
1. Load CICIoT2023 and UNSW-NB15 network traffic datasets
|
| 259 |
+
2. Clean and preprocess both datasets
|
| 260 |
+
3. Map UNSW-NB15 into WiGuard's 44-feature format
|
| 261 |
+
4. Train and evaluate CICIoT2023-only, UNSW-specific, and combined models
|
| 262 |
+
5. Analyze cross-dataset generalization and domain shift
|
| 263 |
+
6. Generate SHAP explanations for original and combined models
|
| 264 |
+
7. Display predictions, performance, feature mapping, and explanations in Streamlit
|
| 265 |
+
""")
|
| 266 |
+
|
| 267 |
+
st.success("""
|
| 268 |
+
The combined WiGuard model was trained using samples from both CICIoT2023 and UNSW-NB15.
|
| 269 |
+
This improves robustness compared to direct zero-shot transfer from one dataset to another.
|
| 270 |
""")
|
| 271 |
|
| 272 |
st.warning("""
|
| 273 |
+
This deployed version uses benchmark test records to simulate real-time traffic.
|
| 274 |
+
Live Wireshark/tshark packet capture remains a future local extension because raw packets
|
| 275 |
+
must first be converted into WiGuard-style flow features.
|
| 276 |
""")
|
| 277 |
|
| 278 |
# ---------------------------------------------------------
|
|
|
|
| 281 |
elif page == "Model Performance":
|
| 282 |
st.title("📊 Model Performance")
|
| 283 |
|
| 284 |
+
st.markdown("## 1. Original CICIoT2023 Binary Model")
|
| 285 |
|
| 286 |
+
if results is not None and "test" in results:
|
| 287 |
+
test_results = results["test"]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 288 |
|
| 289 |
+
col1, col2, col3, col4, col5 = st.columns(5)
|
| 290 |
+
col1.metric("Accuracy", format_percent(test_results.get("accuracy")))
|
| 291 |
+
col2.metric("Precision", format_percent(test_results.get("precision")))
|
| 292 |
+
col3.metric("Recall", format_percent(test_results.get("recall")))
|
| 293 |
+
col4.metric("F1 Score", format_percent(test_results.get("f1_score")))
|
| 294 |
+
col5.metric("ROC-AUC", format_percent(test_results.get("roc_auc")))
|
| 295 |
|
| 296 |
+
st.markdown("### CICIoT2023 Confusion Matrix")
|
| 297 |
|
| 298 |
+
cm = np.array(test_results["confusion_matrix"])
|
| 299 |
+
display_confusion_matrix(cm, "Original CICIoT2023 XGBoost Confusion Matrix")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 300 |
|
| 301 |
+
st.markdown(f"""
|
| 302 |
+
- **True Benign:** {cm[0][0]:,}
|
| 303 |
+
- **False Attack Alerts:** {cm[0][1]:,}
|
| 304 |
+
- **Missed Attacks:** {cm[1][0]:,}
|
| 305 |
+
- **Correctly Detected Attacks:** {cm[1][1]:,}
|
| 306 |
+
""")
|
| 307 |
+
else:
|
| 308 |
+
st.warning("Original model results file not found.")
|
| 309 |
|
| 310 |
+
st.markdown("---")
|
| 311 |
+
st.markdown("## 2. Experiment 05: Cross-Dataset and Combined Model Results")
|
|
|
|
| 312 |
|
| 313 |
+
if exp05_comparison_df is not None and not exp05_comparison_df.empty:
|
| 314 |
+
st.dataframe(exp05_comparison_df, use_container_width=True)
|
| 315 |
+
|
| 316 |
+
st.markdown("### Key Interpretation")
|
| 317 |
+
st.markdown("""
|
| 318 |
+
- **05-A Direct Transfer** showed poor generalization because the CICIoT2023-trained model predicted all UNSW-NB15 samples as attacks.
|
| 319 |
+
- **05-B UNSW-specific model** proved that the mapped UNSW-NB15 44-feature representation is learnable.
|
| 320 |
+
- **05-C Combined model** performed strongly on both CICIoT2023 and UNSW-NB15, supporting the common feature-space training strategy.
|
| 321 |
+
""")
|
| 322 |
+
else:
|
| 323 |
+
st.warning("Experiment 05 comparison table not found.")
|
| 324 |
+
|
| 325 |
+
st.markdown("### Experiment 05 Graphs")
|
| 326 |
+
|
| 327 |
+
for title, path in EXP05_GRAPHS.items():
|
| 328 |
+
with st.expander(title, expanded=False):
|
| 329 |
+
show_image_if_exists(path, title)
|
| 330 |
+
|
| 331 |
+
st.markdown("---")
|
| 332 |
+
st.markdown("## 3. Combined Model Summary")
|
| 333 |
|
| 334 |
+
if exp05_summary is not None:
|
| 335 |
+
col1, col2 = st.columns(2)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 336 |
|
| 337 |
+
with col1:
|
| 338 |
+
st.markdown("### Tested on UNSW-NB15")
|
| 339 |
+
unsw_results = exp05_summary.get("unsw_test_results", {})
|
| 340 |
+
st.metric("Accuracy", format_percent(unsw_results.get("accuracy", 0)))
|
| 341 |
+
st.metric("F1 Score", format_percent(unsw_results.get("f1_score", 0)))
|
| 342 |
+
st.metric("ROC-AUC", format_percent(unsw_results.get("roc_auc", 0)))
|
| 343 |
+
|
| 344 |
+
with col2:
|
| 345 |
+
st.markdown("### Tested on CICIoT2023")
|
| 346 |
+
ciciot_results = exp05_summary.get("ciciot_test_results", {})
|
| 347 |
+
st.metric("Accuracy", format_percent(ciciot_results.get("accuracy", 0)))
|
| 348 |
+
st.metric("F1 Score", format_percent(ciciot_results.get("f1_score", 0)))
|
| 349 |
+
st.metric("ROC-AUC", format_percent(ciciot_results.get("roc_auc", 0)))
|
| 350 |
+
|
| 351 |
+
with st.expander("View Full Experiment 05-C Summary JSON"):
|
| 352 |
+
st.json(exp05_summary)
|
| 353 |
+
else:
|
| 354 |
+
st.info("Combined model summary JSON not found.")
|
| 355 |
|
| 356 |
# ---------------------------------------------------------
|
| 357 |
# Live Traffic Simulation Page
|
|
|
|
| 360 |
st.title("📡 Live Traffic Simulation")
|
| 361 |
|
| 362 |
st.markdown("""
|
| 363 |
+
This page simulates incoming network-flow records using benchmark test samples.
|
| 364 |
+
You can choose between the original CICIoT2023 model and the combined CICIoT2023 + UNSW-NB15 model.
|
| 365 |
""")
|
| 366 |
|
| 367 |
+
available_models = {
|
| 368 |
+
"Original CICIoT2023 Binary Model": ciciot_model,
|
| 369 |
+
"Combined CICIoT2023 + UNSW-NB15 Binary Model": combined_model,
|
| 370 |
+
}
|
| 371 |
+
|
| 372 |
+
model_choice = st.selectbox(
|
| 373 |
+
"Select model for prediction",
|
| 374 |
+
list(available_models.keys())
|
| 375 |
+
)
|
| 376 |
+
|
| 377 |
+
active_model = available_models[model_choice]
|
| 378 |
+
|
| 379 |
+
if active_model is None:
|
| 380 |
+
st.error(f"Selected model file is missing for: {model_choice}")
|
| 381 |
+
|
| 382 |
+
if traffic_df.empty:
|
| 383 |
+
st.error("Dashboard sample traffic file not found.")
|
| 384 |
+
st.stop()
|
| 385 |
+
|
| 386 |
max_index = len(traffic_df) - 1
|
| 387 |
|
| 388 |
selected_index = st.slider(
|
|
|
|
| 395 |
|
| 396 |
row = traffic_df.iloc[selected_index]
|
| 397 |
|
| 398 |
+
label, probability, severity, icon = predict_single(row, active_model)
|
| 399 |
|
| 400 |
+
col1, col2, col3, col4, col5 = st.columns(5)
|
| 401 |
col1.metric("Prediction", label)
|
| 402 |
col2.metric("Attack Probability", f"{probability * 100:.3f}%")
|
| 403 |
col3.metric("Threat Severity", f"{icon} {severity}")
|
| 404 |
col4.metric("Actual Category", str(row.get("attack_category", "Unknown")))
|
| 405 |
+
col5.metric("Model Used", model_choice.split(" Binary")[0])
|
| 406 |
|
| 407 |
st.markdown("### Traffic Record Features")
|
| 408 |
st.dataframe(row[selected_features].to_frame(name="Value"), use_container_width=True)
|
| 409 |
|
| 410 |
st.markdown("### Manual Simulation")
|
| 411 |
+
|
| 412 |
if st.button("Run Next 10 Records"):
|
| 413 |
logs = []
|
| 414 |
progress = st.progress(0)
|
| 415 |
|
| 416 |
+
total_to_run = min(10, len(traffic_df) - selected_index)
|
| 417 |
+
|
| 418 |
+
for offset, i in enumerate(range(selected_index, selected_index + total_to_run)):
|
| 419 |
current_row = traffic_df.iloc[i]
|
| 420 |
+
pred_label, prob, sev, sev_icon = predict_single(current_row, active_model)
|
| 421 |
|
| 422 |
logs.append({
|
| 423 |
"time": datetime.now().strftime("%H:%M:%S"),
|
| 424 |
"index": i,
|
| 425 |
+
"model_used": model_choice,
|
| 426 |
"prediction": pred_label,
|
| 427 |
"attack_probability": round(prob * 100, 3),
|
| 428 |
"severity": sev,
|
| 429 |
"actual_category": current_row.get("attack_category", "Unknown")
|
| 430 |
})
|
| 431 |
|
| 432 |
+
progress.progress((offset + 1) / total_to_run)
|
| 433 |
+
time.sleep(0.1)
|
| 434 |
|
| 435 |
st.dataframe(pd.DataFrame(logs), use_container_width=True)
|
| 436 |
|
|
|
|
| 441 |
st.title("🧠 SHAP Explainability")
|
| 442 |
|
| 443 |
st.markdown("""
|
| 444 |
+
SHAP is used to explain how each feature contributes to model predictions.
|
| 445 |
+
Positive SHAP values generally push predictions toward **Attack**, while negative SHAP values
|
| 446 |
+
push predictions toward **Benign**.
|
| 447 |
""")
|
| 448 |
|
| 449 |
+
tab1, tab2 = st.tabs([
|
| 450 |
+
"Original CICIoT2023 Model SHAP",
|
| 451 |
+
"Combined Model SHAP"
|
| 452 |
+
])
|
| 453 |
+
|
| 454 |
+
with tab1:
|
| 455 |
+
st.markdown("## Original CICIoT2023 Model Explainability")
|
| 456 |
+
|
| 457 |
+
if shap_importance_df is not None and not shap_importance_df.empty:
|
| 458 |
+
top_n = st.slider("Number of top original-model features", 5, 20, 10, key="orig_shap_slider")
|
| 459 |
+
top_shap = shap_importance_df.head(top_n)
|
| 460 |
+
|
| 461 |
+
fig = px.bar(
|
| 462 |
+
top_shap.sort_values("mean_abs_shap"),
|
| 463 |
+
x="mean_abs_shap",
|
| 464 |
+
y="feature",
|
| 465 |
+
orientation="h",
|
| 466 |
+
title="Top Global SHAP Features - Original CICIoT2023 Model"
|
| 467 |
+
)
|
| 468 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 469 |
+
else:
|
| 470 |
+
st.info("Original SHAP importance CSV not found.")
|
| 471 |
+
|
| 472 |
+
st.markdown("### Saved Original SHAP Plots")
|
| 473 |
+
col1, col2 = st.columns(2)
|
| 474 |
+
with col1:
|
| 475 |
+
show_image_if_exists(SHAP_BAR_IMAGE, "Original Global SHAP Bar Plot")
|
| 476 |
+
with col2:
|
| 477 |
+
show_image_if_exists(SHAP_SUMMARY_IMAGE, "Original SHAP Beeswarm Plot")
|
| 478 |
+
|
| 479 |
+
st.markdown("### Original Sample Local Explanation")
|
| 480 |
+
if local_explanation is not None:
|
| 481 |
+
st.json(local_explanation)
|
| 482 |
+
else:
|
| 483 |
+
st.info("Original local explanation JSON not found.")
|
| 484 |
+
|
| 485 |
+
with tab2:
|
| 486 |
+
st.markdown("## Combined CICIoT2023 + UNSW-NB15 Model Explainability")
|
| 487 |
+
|
| 488 |
+
st.markdown("""
|
| 489 |
+
The combined model was explained separately on CICIoT2023 and UNSW-NB15 samples.
|
| 490 |
+
This helps show how feature importance changes across datasets.
|
| 491 |
+
""")
|
| 492 |
+
|
| 493 |
+
subtab1, subtab2, subtab3, subtab4 = st.tabs([
|
| 494 |
+
"UNSW SHAP",
|
| 495 |
+
"CICIoT SHAP",
|
| 496 |
+
"Feature Comparison",
|
| 497 |
+
"Local Explanations"
|
| 498 |
+
])
|
| 499 |
+
|
| 500 |
+
with subtab1:
|
| 501 |
+
st.markdown("### UNSW-NB15 Global SHAP Importance")
|
| 502 |
+
if combined_shap_unsw_df is not None and not combined_shap_unsw_df.empty:
|
| 503 |
+
top_n_unsw = st.slider("Top UNSW SHAP features", 5, 20, 10, key="unsw_shap_slider")
|
| 504 |
+
top_unsw = combined_shap_unsw_df.head(top_n_unsw)
|
| 505 |
+
|
| 506 |
+
fig = px.bar(
|
| 507 |
+
top_unsw.sort_values("mean_abs_shap"),
|
| 508 |
+
x="mean_abs_shap",
|
| 509 |
+
y="feature",
|
| 510 |
+
orientation="h",
|
| 511 |
+
title="Combined Model SHAP Importance on UNSW-NB15"
|
| 512 |
+
)
|
| 513 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 514 |
+
st.dataframe(combined_shap_unsw_df.head(20), use_container_width=True)
|
| 515 |
+
else:
|
| 516 |
+
st.info("UNSW combined SHAP CSV not found.")
|
| 517 |
+
|
| 518 |
+
show_image_if_exists(COMBINED_SHAP_GRAPHS["UNSW-NB15 SHAP Bar Plot"], "UNSW-NB15 SHAP Bar Plot")
|
| 519 |
+
show_image_if_exists(COMBINED_SHAP_GRAPHS["UNSW-NB15 SHAP Beeswarm Plot"], "UNSW-NB15 SHAP Beeswarm Plot")
|
| 520 |
+
|
| 521 |
+
with subtab2:
|
| 522 |
+
st.markdown("### CICIoT2023 Global SHAP Importance")
|
| 523 |
+
if combined_shap_ciciot_df is not None and not combined_shap_ciciot_df.empty:
|
| 524 |
+
top_n_ciciot = st.slider("Top CICIoT SHAP features", 5, 20, 10, key="ciciot_shap_slider")
|
| 525 |
+
top_ciciot = combined_shap_ciciot_df.head(top_n_ciciot)
|
| 526 |
+
|
| 527 |
+
fig = px.bar(
|
| 528 |
+
top_ciciot.sort_values("mean_abs_shap"),
|
| 529 |
+
x="mean_abs_shap",
|
| 530 |
+
y="feature",
|
| 531 |
+
orientation="h",
|
| 532 |
+
title="Combined Model SHAP Importance on CICIoT2023"
|
| 533 |
+
)
|
| 534 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 535 |
+
st.dataframe(combined_shap_ciciot_df.head(20), use_container_width=True)
|
| 536 |
+
else:
|
| 537 |
+
st.info("CICIoT combined SHAP CSV not found.")
|
| 538 |
+
|
| 539 |
+
show_image_if_exists(COMBINED_SHAP_GRAPHS["CICIoT2023 SHAP Bar Plot"], "CICIoT2023 SHAP Bar Plot")
|
| 540 |
+
show_image_if_exists(COMBINED_SHAP_GRAPHS["CICIoT2023 SHAP Beeswarm Plot"], "CICIoT2023 SHAP Beeswarm Plot")
|
| 541 |
+
|
| 542 |
+
with subtab3:
|
| 543 |
+
st.markdown("### Top Feature Comparison: UNSW-NB15 vs CICIoT2023")
|
| 544 |
+
if combined_shap_compare_df is not None and not combined_shap_compare_df.empty:
|
| 545 |
+
st.dataframe(combined_shap_compare_df, use_container_width=True)
|
| 546 |
+
|
| 547 |
+
st.markdown("""
|
| 548 |
+
This comparison shows that some features are important across both datasets,
|
| 549 |
+
while others are dataset-specific. This supports the domain-shift finding from
|
| 550 |
+
Experiment 05-A.
|
| 551 |
+
""")
|
| 552 |
+
else:
|
| 553 |
+
st.info("Combined SHAP comparison CSV not found.")
|
| 554 |
+
|
| 555 |
+
with subtab4:
|
| 556 |
+
st.markdown("### Local Explanation: UNSW-NB15 Sample")
|
| 557 |
+
if combined_local_unsw is not None:
|
| 558 |
+
st.json(combined_local_unsw)
|
| 559 |
+
else:
|
| 560 |
+
st.info("UNSW local explanation JSON not found.")
|
| 561 |
+
|
| 562 |
+
st.markdown("### Local Explanation: CICIoT2023 Sample")
|
| 563 |
+
if combined_local_ciciot is not None:
|
| 564 |
+
st.json(combined_local_ciciot)
|
| 565 |
+
else:
|
| 566 |
+
st.info("CICIoT local explanation JSON not found.")
|
| 567 |
|
| 568 |
# ---------------------------------------------------------
|
| 569 |
# Dataset & Features Page
|
|
|
|
| 572 |
st.title("🧾 Dataset & Features")
|
| 573 |
|
| 574 |
st.markdown("""
|
| 575 |
+
WiGuard uses a shared **44-feature representation** for model training and prediction.
|
| 576 |
+
CICIoT2023 already contains these selected features, while UNSW-NB15 was mapped into this
|
| 577 |
+
format for cross-dataset and combined training.
|
| 578 |
""")
|
| 579 |
|
| 580 |
+
st.markdown("## Final Selected WiGuard Features")
|
| 581 |
+
|
| 582 |
feature_df = pd.DataFrame({"Feature": selected_features})
|
| 583 |
st.dataframe(feature_df, use_container_width=True)
|
| 584 |
|
| 585 |
+
st.markdown("---")
|
| 586 |
+
st.markdown("## UNSW-NB15 Feature Mapping")
|
| 587 |
+
|
| 588 |
+
mapping_df = pd.DataFrame([
|
| 589 |
+
{"WiGuard Feature": "flow_duration", "UNSW-NB15 Mapping": "dur", "Mapping Type": "Direct"},
|
| 590 |
+
{"WiGuard Feature": "duration", "UNSW-NB15 Mapping": "dur", "Mapping Type": "Direct"},
|
| 591 |
+
{"WiGuard Feature": "rate", "UNSW-NB15 Mapping": "rate", "Mapping Type": "Direct"},
|
| 592 |
+
{"WiGuard Feature": "srate", "UNSW-NB15 Mapping": "sload", "Mapping Type": "Approximate"},
|
| 593 |
+
{"WiGuard Feature": "drate", "UNSW-NB15 Mapping": "dload", "Mapping Type": "Approximate"},
|
| 594 |
+
{"WiGuard Feature": "protocol_type", "UNSW-NB15 Mapping": "encoded proto", "Mapping Type": "Derived"},
|
| 595 |
+
{"WiGuard Feature": "tcp", "UNSW-NB15 Mapping": "proto == tcp", "Mapping Type": "Derived"},
|
| 596 |
+
{"WiGuard Feature": "udp", "UNSW-NB15 Mapping": "proto == udp", "Mapping Type": "Derived"},
|
| 597 |
+
{"WiGuard Feature": "icmp", "UNSW-NB15 Mapping": "proto == icmp", "Mapping Type": "Derived"},
|
| 598 |
+
{"WiGuard Feature": "http", "UNSW-NB15 Mapping": "service == http", "Mapping Type": "Derived"},
|
| 599 |
+
{"WiGuard Feature": "dns", "UNSW-NB15 Mapping": "service == dns", "Mapping Type": "Derived"},
|
| 600 |
+
{"WiGuard Feature": "smtp", "UNSW-NB15 Mapping": "service == smtp", "Mapping Type": "Derived"},
|
| 601 |
+
{"WiGuard Feature": "ssh", "UNSW-NB15 Mapping": "service == ssh", "Mapping Type": "Derived"},
|
| 602 |
+
{"WiGuard Feature": "tot_sum", "UNSW-NB15 Mapping": "sbytes + dbytes", "Mapping Type": "Derived"},
|
| 603 |
+
{"WiGuard Feature": "tot_size", "UNSW-NB15 Mapping": "sbytes + dbytes", "Mapping Type": "Derived"},
|
| 604 |
+
{"WiGuard Feature": "number", "UNSW-NB15 Mapping": "spkts + dpkts", "Mapping Type": "Derived"},
|
| 605 |
+
{"WiGuard Feature": "avg", "UNSW-NB15 Mapping": "(sbytes + dbytes) / (spkts + dpkts)", "Mapping Type": "Derived"},
|
| 606 |
+
{"WiGuard Feature": "iat", "UNSW-NB15 Mapping": "mean(sinpkt, dinpkt)", "Mapping Type": "Approximate"},
|
| 607 |
+
{"WiGuard Feature": "header_length", "UNSW-NB15 Mapping": "(spkts + dpkts) × 20", "Mapping Type": "Approximate"},
|
| 608 |
+
])
|
| 609 |
+
|
| 610 |
+
st.dataframe(mapping_df, use_container_width=True)
|
| 611 |
|
|
|
|
| 612 |
st.info("""
|
| 613 |
+
Some CICIoT2023-style features do not have exact equivalents in UNSW-NB15.
|
| 614 |
+
These were either approximated using similar UNSW-NB15 fields or filled with zero.
|
| 615 |
+
This is why direct zero-shot transfer performed poorly, while combined training worked better.
|
|
|
|
| 616 |
""")
|
| 617 |
|
| 618 |
+
st.markdown("---")
|
| 619 |
+
st.markdown("## UNSW-NB15 Imbalance Analysis")
|
| 620 |
+
|
| 621 |
+
show_csv_if_exists(unsw_binary_imbalance_df, "### Binary Class Imbalance")
|
| 622 |
+
show_csv_if_exists(unsw_attack_imbalance_df, "### Attack Category Imbalance")
|
| 623 |
+
|
| 624 |
+
st.markdown("---")
|
| 625 |
+
st.markdown("## Dashboard Sample Data")
|
| 626 |
+
|
| 627 |
+
if not traffic_df.empty:
|
| 628 |
+
st.write("Shape:", traffic_df.shape)
|
| 629 |
+
st.dataframe(traffic_df.head(20), use_container_width=True)
|
| 630 |
+
else:
|
| 631 |
+
st.warning("Dashboard sample traffic data not found.")
|
| 632 |
+
|
| 633 |
# ---------------------------------------------------------
|
| 634 |
# Attack Logs Page
|
| 635 |
# ---------------------------------------------------------
|
|
|
|
| 637 |
st.title("📜 Attack Logs")
|
| 638 |
|
| 639 |
st.markdown("""
|
| 640 |
+
This page generates prediction logs from a batch of simulated traffic samples.
|
| 641 |
+
The logs now include the selected model name.
|
| 642 |
""")
|
| 643 |
|
| 644 |
+
available_models = {
|
| 645 |
+
"Original CICIoT2023 Binary Model": ciciot_model,
|
| 646 |
+
"Combined CICIoT2023 + UNSW-NB15 Binary Model": combined_model,
|
| 647 |
+
}
|
| 648 |
+
|
| 649 |
+
model_choice = st.selectbox(
|
| 650 |
+
"Select model for log generation",
|
| 651 |
+
list(available_models.keys()),
|
| 652 |
+
key="logs_model_choice"
|
| 653 |
+
)
|
| 654 |
+
|
| 655 |
+
active_model = available_models[model_choice]
|
| 656 |
+
|
| 657 |
+
if traffic_df.empty:
|
| 658 |
+
st.error("Dashboard sample traffic file not found.")
|
| 659 |
+
st.stop()
|
| 660 |
+
|
| 661 |
batch_size = st.slider("Number of records to process", 10, 500, 50)
|
| 662 |
|
| 663 |
if st.button("Generate Logs"):
|
| 664 |
+
sample_batch = traffic_df.sample(n=min(batch_size, len(traffic_df)), random_state=42)
|
| 665 |
|
| 666 |
logs = []
|
| 667 |
|
| 668 |
for idx, row in sample_batch.iterrows():
|
| 669 |
+
pred_label, prob, sev, sev_icon = predict_single(row, active_model)
|
| 670 |
|
| 671 |
logs.append({
|
| 672 |
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
| 673 |
"record_index": idx,
|
| 674 |
+
"model_used": model_choice,
|
| 675 |
"prediction": pred_label,
|
| 676 |
"attack_probability": round(prob * 100, 3),
|
| 677 |
"severity": sev,
|