Restore original SVM trainer/scorer (svm.py from initial commit 25f6a47) — source of Table 10 Stage-2 exact-match and Stage-3 normalize_label rules
Browse files- evaluation/drift/CADE/svm.py +905 -0
evaluation/drift/CADE/svm.py
ADDED
|
@@ -0,0 +1,905 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
SVM-based IoT Device Classification
|
| 3 |
+
====================================
|
| 4 |
+
Classifies devices into (device_type-vendor) combined labels.
|
| 5 |
+
|
| 6 |
+
Pipeline:
|
| 7 |
+
1. Load training IPs + vendor labels from vendor-50/
|
| 8 |
+
2. Retrieve IP fingerprints from ipraw_{device_type}.csv
|
| 9 |
+
3. Feature engineering: TF-IDF on text columns, one-hot on categorical
|
| 10 |
+
4. Train SVM with kernel / C / gamma tuning via GridSearchCV
|
| 11 |
+
5. Evaluate: per-fold hinge loss, accuracy, precision, recall, F1
|
| 12 |
+
6. Save per-device-type prediction results to SVM_train/predict/
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import os, sys, time, json, re, warnings, argparse
|
| 16 |
+
import numpy as np
|
| 17 |
+
import pandas as pd
|
| 18 |
+
from sklearn.svm import SVC
|
| 19 |
+
from sklearn.model_selection import StratifiedKFold, GridSearchCV
|
| 20 |
+
from sklearn.preprocessing import LabelEncoder, MaxAbsScaler
|
| 21 |
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 22 |
+
from sklearn.metrics import (
|
| 23 |
+
accuracy_score, precision_score, recall_score,
|
| 24 |
+
f1_score, hinge_loss, classification_report,
|
| 25 |
+
)
|
| 26 |
+
from scipy.sparse import hstack, csr_matrix
|
| 27 |
+
import joblib
|
| 28 |
+
|
| 29 |
+
warnings.filterwarnings("ignore")
|
| 30 |
+
|
| 31 |
+
# ────────────────────────── Paths ──────────────────────────
|
| 32 |
+
VENDOR50_DIR = r"e:\iot-classification\evaluation\drift\CADE\dataset\train_SVM\vendor-50"
|
| 33 |
+
IPRAW_DIR = r"e:\iot-classification\platform_data\csv"
|
| 34 |
+
OUTPUT_DIR = r"e:\iot-classification\evaluation\drift\CADE\SVM_train"
|
| 35 |
+
PREDICT_SUBDIR = os.path.join(OUTPUT_DIR, "predict")
|
| 36 |
+
DRIFT_FILTER_DIR = r"e:\iot-classification\platform_data\2026-04-06\filter"
|
| 37 |
+
TEST_SVM_DIR = r"e:\iot-classification\evaluation\drift\CADE\dataset\test_SVM"
|
| 38 |
+
SVM_TEST_DIR = r"e:\iot-classification\evaluation\drift\CADE\SVM_test"
|
| 39 |
+
TEST_PREDICT_SUBDIR = os.path.join(SVM_TEST_DIR, "predict")
|
| 40 |
+
MODEL_DIR = r"e:\iot-classification\evaluation\drift\CADE\SVM_model"
|
| 41 |
+
MODEL_BUNDLE = os.path.join(MODEL_DIR, "svm_bundle.pkl")
|
| 42 |
+
VALIDATION_DIR = r"e:\iot-classification\evaluation\drift\CADE\SVM_validation"
|
| 43 |
+
CADE_DETECTED = os.path.join(VALIDATION_DIR, "CADE", "detected_ips.csv")
|
| 44 |
+
IOTPROBER_DETECTED = os.path.join(VALIDATION_DIR, "IoTProber", "detected_ips.csv")
|
| 45 |
+
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
| 46 |
+
os.makedirs(PREDICT_SUBDIR, exist_ok=True)
|
| 47 |
+
os.makedirs(SVM_TEST_DIR, exist_ok=True)
|
| 48 |
+
os.makedirs(TEST_PREDICT_SUBDIR, exist_ok=True)
|
| 49 |
+
os.makedirs(MODEL_DIR, exist_ok=True)
|
| 50 |
+
|
| 51 |
+
DEVICE_TYPES = [
|
| 52 |
+
"BUILDING_AUTOMATION", "CAMERA", "MEDIA_SERVER", "MEDICAL",
|
| 53 |
+
"NAS", "NVR", "POWER_METER", "PRINTER", "ROUTER", "SCADA", "VPN",
|
| 54 |
+
]
|
| 55 |
+
|
| 56 |
+
# ────────────────────────── Column config ──────────────────────────
|
| 57 |
+
# Exact 25 features from local_used_features.txt (+ip)
|
| 58 |
+
USE_COLS = [
|
| 59 |
+
"ip",
|
| 60 |
+
"as-asn", "as-name", "as-bgp_prefix", "as-country_code",
|
| 61 |
+
"whois-network-handle", "whois-network-name",
|
| 62 |
+
"whois-organization-handle", "whois-organization-name",
|
| 63 |
+
"os-vendor", "os-product", "os-version",
|
| 64 |
+
"sw-vendors", "sw-products", "sw-versions",
|
| 65 |
+
"hw-vendors", "hw-products", "hw-versions",
|
| 66 |
+
"service-distribution",
|
| 67 |
+
"http-bodys", "http-tags", "http-favicon-urls",
|
| 68 |
+
"cert-subjects", "cert-issuers", "tls-versions",
|
| 69 |
+
"dns-reverse",
|
| 70 |
+
]
|
| 71 |
+
|
| 72 |
+
# Treat as TF-IDF documents
|
| 73 |
+
TEXT_FEATURES = [
|
| 74 |
+
"as-name", "as-bgp_prefix",
|
| 75 |
+
"whois-network-name", "whois-organization-name",
|
| 76 |
+
"os-version",
|
| 77 |
+
"sw-vendors", "sw-products", "sw-versions",
|
| 78 |
+
"hw-vendors", "hw-products", "hw-versions",
|
| 79 |
+
"service-distribution",
|
| 80 |
+
"http-bodys", "http-tags", "http-favicon-urls",
|
| 81 |
+
"cert-subjects", "cert-issuers", "tls-versions",
|
| 82 |
+
"dns-reverse",
|
| 83 |
+
]
|
| 84 |
+
|
| 85 |
+
# Treat as one-hot categorical
|
| 86 |
+
CAT_FEATURES = [
|
| 87 |
+
"as-country_code",
|
| 88 |
+
"whois-network-handle", "whois-organization-handle",
|
| 89 |
+
"os-vendor", "os-product",
|
| 90 |
+
]
|
| 91 |
+
|
| 92 |
+
CHUNK_SIZE = 80_000 # rows per chunk when scanning ipraw
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
# ────────────────────────── Helpers ──────────────────────────
|
| 96 |
+
VENDOR_ALIASES = {
|
| 97 |
+
"electroind": "electroindustries",
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def _normalize_vendor(v):
|
| 102 |
+
"""Strip all non-alphanumeric chars and lowercase."""
|
| 103 |
+
return re.sub(r'[^a-z0-9]', '', v.lower())
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def normalize_label(label):
|
| 107 |
+
"""Normalize a label to canonical form: lowercase device_type + normalized vendor."""
|
| 108 |
+
parts = label.split("-", 1)
|
| 109 |
+
if len(parts) != 2:
|
| 110 |
+
return label.lower()
|
| 111 |
+
dt, vendor = parts
|
| 112 |
+
nv = _normalize_vendor(vendor)
|
| 113 |
+
nv = VENDOR_ALIASES.get(nv, nv)
|
| 114 |
+
return dt.lower() + "-" + nv
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def label_match(label, label_pred):
|
| 118 |
+
"""Case-insensitive match; if device_type matches, also fuzzy-match vendor
|
| 119 |
+
by stripping all symbols and applying alias mapping."""
|
| 120 |
+
return normalize_label(label) == normalize_label(label_pred)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def comma_tokenizer(text):
|
| 124 |
+
"""Split comma-separated fingerprint fields into tokens."""
|
| 125 |
+
return [t.strip() for t in str(text).split(",") if t.strip()]
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
# ────────────────────────── 1. Load labels ──────────────────────────
|
| 129 |
+
def load_labels():
|
| 130 |
+
frames = []
|
| 131 |
+
for dt in DEVICE_TYPES:
|
| 132 |
+
df = pd.read_csv(os.path.join(VENDOR50_DIR, f"{dt}.csv"))
|
| 133 |
+
df["device_type"] = dt
|
| 134 |
+
df["label"] = dt + "-" + df["vendor"].astype(str)
|
| 135 |
+
frames.append(df)
|
| 136 |
+
return pd.concat(frames, ignore_index=True)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
# ────────────────────────── 2. Load fingerprints ──────────────────────────
|
| 140 |
+
def load_fingerprints(label_df):
|
| 141 |
+
all_fps = []
|
| 142 |
+
for dt in DEVICE_TYPES:
|
| 143 |
+
ip_set = set(label_df.loc[label_df["device_type"] == dt, "ip"])
|
| 144 |
+
ipraw_path = os.path.join(IPRAW_DIR, f"ipraw_{dt}.csv")
|
| 145 |
+
print(f" {dt:30s} ({len(ip_set):4d} IPs) ... ", end="", flush=True)
|
| 146 |
+
t0 = time.time()
|
| 147 |
+
parts, found = [], 0
|
| 148 |
+
for chunk in pd.read_csv(
|
| 149 |
+
ipraw_path, usecols=USE_COLS, chunksize=CHUNK_SIZE, low_memory=False
|
| 150 |
+
):
|
| 151 |
+
matched = chunk[chunk["ip"].isin(ip_set)]
|
| 152 |
+
if len(matched):
|
| 153 |
+
parts.append(matched)
|
| 154 |
+
found += len(matched)
|
| 155 |
+
if found >= len(ip_set):
|
| 156 |
+
break
|
| 157 |
+
if parts:
|
| 158 |
+
fp = pd.concat(parts).drop_duplicates("ip", keep="first")
|
| 159 |
+
fp["device_type"] = dt
|
| 160 |
+
all_fps.append(fp)
|
| 161 |
+
print(f"found {len(fp):4d} ({time.time()-t0:.1f}s)")
|
| 162 |
+
else:
|
| 163 |
+
print("NONE found!")
|
| 164 |
+
return pd.concat(all_fps, ignore_index=True)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
# ────────────────────────── 3. Feature engineering ──────────────────────────
|
| 168 |
+
# http-bodys is very large text; cap its TF-IDF vocab to avoid noise
|
| 169 |
+
_TFIDF_MAX = {"http-bodys": 200, "http-tags": 200, "http-favicon-urls": 100}
|
| 170 |
+
_TFIDF_DEFAULT = 300
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def build_features(df):
|
| 174 |
+
"""Return sparse feature matrix X, fitted vectorizers, and cat columns map."""
|
| 175 |
+
matrices = []
|
| 176 |
+
|
| 177 |
+
# 3-a. TF-IDF on text columns
|
| 178 |
+
vectorizers = {}
|
| 179 |
+
cat_columns_map = {}
|
| 180 |
+
for col in TEXT_FEATURES:
|
| 181 |
+
df[col] = df[col].fillna("").astype(str)
|
| 182 |
+
max_feat = _TFIDF_MAX.get(col, _TFIDF_DEFAULT)
|
| 183 |
+
vec = TfidfVectorizer(
|
| 184 |
+
tokenizer=comma_tokenizer,
|
| 185 |
+
token_pattern=None,
|
| 186 |
+
max_features=max_feat,
|
| 187 |
+
sublinear_tf=True,
|
| 188 |
+
)
|
| 189 |
+
m = vec.fit_transform(df[col])
|
| 190 |
+
matrices.append(m)
|
| 191 |
+
vectorizers[col] = vec
|
| 192 |
+
print(f" tfidf {col:30s} -> {m.shape[1]:4d} dims")
|
| 193 |
+
|
| 194 |
+
# 3-b. One-hot on categorical columns
|
| 195 |
+
for col in CAT_FEATURES:
|
| 196 |
+
df[col] = df[col].fillna("UNK").astype(str)
|
| 197 |
+
dummies = pd.get_dummies(df[col], prefix=col)
|
| 198 |
+
cat_columns_map[col] = list(dummies.columns)
|
| 199 |
+
m = csr_matrix(dummies.values.astype(np.float32))
|
| 200 |
+
matrices.append(m)
|
| 201 |
+
print(f" onehot {col:30s} -> {m.shape[1]:4d} dims")
|
| 202 |
+
|
| 203 |
+
# 3-c. Numeric: as-asn
|
| 204 |
+
asn = pd.to_numeric(df["as-asn"], errors="coerce").fillna(0).values.reshape(-1, 1)
|
| 205 |
+
matrices.append(csr_matrix(asn.astype(np.float32)))
|
| 206 |
+
print(f" numeric as-asn{' ':24s} -> 1 dim")
|
| 207 |
+
|
| 208 |
+
X = hstack(matrices, format="csr")
|
| 209 |
+
print(f" Final feature matrix: {X.shape[0]} samples x {X.shape[1]} features")
|
| 210 |
+
return X, vectorizers, cat_columns_map
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
# ────────────────────────── Transform for test set ──────────────────────────
|
| 214 |
+
def transform_features(df, vectorizers, cat_columns_map):
|
| 215 |
+
"""Transform a dataframe using fitted vectorizers and stored category columns."""
|
| 216 |
+
matrices = []
|
| 217 |
+
for col in TEXT_FEATURES:
|
| 218 |
+
df[col] = df[col].fillna("").astype(str)
|
| 219 |
+
matrices.append(vectorizers[col].transform(df[col]))
|
| 220 |
+
for col in CAT_FEATURES:
|
| 221 |
+
df[col] = df[col].fillna("UNK").astype(str)
|
| 222 |
+
dummies = pd.get_dummies(df[col], prefix=col)
|
| 223 |
+
dummies = dummies.reindex(columns=cat_columns_map[col], fill_value=0)
|
| 224 |
+
matrices.append(csr_matrix(dummies.values.astype(np.float32)))
|
| 225 |
+
asn = pd.to_numeric(df["as-asn"], errors="coerce").fillna(0).values.reshape(-1, 1)
|
| 226 |
+
matrices.append(csr_matrix(asn.astype(np.float32)))
|
| 227 |
+
return hstack(matrices, format="csr")
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
# ────────────────────────── 4-5. Train & evaluate ──────────────────────────
|
| 231 |
+
def train_evaluate(X, y, le):
|
| 232 |
+
# Scale
|
| 233 |
+
scaler = MaxAbsScaler()
|
| 234 |
+
X = scaler.fit_transform(X)
|
| 235 |
+
|
| 236 |
+
n_classes = len(le.classes_)
|
| 237 |
+
print(f" Samples={X.shape[0]} Features={X.shape[1]} Classes={n_classes}")
|
| 238 |
+
|
| 239 |
+
# --- Hyperparameter grid ---
|
| 240 |
+
param_grid = [
|
| 241 |
+
{"kernel": ["rbf"], "C": [1, 10, 100], "gamma": ["scale", 0.01]},
|
| 242 |
+
{"kernel": ["linear"], "C": [0.1, 1, 10]},
|
| 243 |
+
{"kernel": ["poly"], "C": [1, 10], "degree": [3], "gamma": ["scale"]},
|
| 244 |
+
]
|
| 245 |
+
|
| 246 |
+
skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
|
| 247 |
+
|
| 248 |
+
svm = SVC(
|
| 249 |
+
decision_function_shape="ovr",
|
| 250 |
+
class_weight="balanced",
|
| 251 |
+
random_state=42,
|
| 252 |
+
cache_size=2000,
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
grid = GridSearchCV(
|
| 256 |
+
svm, param_grid, cv=skf, scoring="f1_macro",
|
| 257 |
+
n_jobs=-1, verbose=2, refit=True,
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
print("\n Running GridSearchCV ...")
|
| 261 |
+
t0 = time.time()
|
| 262 |
+
grid.fit(X, y)
|
| 263 |
+
print(f" GridSearch done in {time.time()-t0:.0f}s")
|
| 264 |
+
|
| 265 |
+
best = grid.best_estimator_
|
| 266 |
+
print(f" Best params : {grid.best_params_}")
|
| 267 |
+
print(f" Best CV F1 : {grid.best_score_:.4f}")
|
| 268 |
+
|
| 269 |
+
# --- Per-fold loss (hinge) with best params ---
|
| 270 |
+
print("\n Per-fold metrics (best params):")
|
| 271 |
+
fold_metrics = []
|
| 272 |
+
for i, (tr_idx, val_idx) in enumerate(skf.split(X, y)):
|
| 273 |
+
X_tr, X_val = X[tr_idx], X[val_idx]
|
| 274 |
+
y_tr, y_val = y[tr_idx], y[val_idx]
|
| 275 |
+
m = SVC(
|
| 276 |
+
**grid.best_params_,
|
| 277 |
+
decision_function_shape="ovr",
|
| 278 |
+
class_weight="balanced",
|
| 279 |
+
random_state=42,
|
| 280 |
+
cache_size=2000,
|
| 281 |
+
)
|
| 282 |
+
m.fit(X_tr, y_tr)
|
| 283 |
+
y_p = m.predict(X_val)
|
| 284 |
+
dec = m.decision_function(X_val)
|
| 285 |
+
h = hinge_loss(y_val, dec, labels=np.arange(n_classes))
|
| 286 |
+
f1 = f1_score(y_val, y_p, average="macro", zero_division=0)
|
| 287 |
+
acc = accuracy_score(y_val, y_p)
|
| 288 |
+
prec = precision_score(y_val, y_p, average="macro", zero_division=0)
|
| 289 |
+
rec = recall_score(y_val, y_p, average="macro", zero_division=0)
|
| 290 |
+
fold_metrics.append({
|
| 291 |
+
"fold": i + 1, "hinge_loss": round(h, 4),
|
| 292 |
+
"f1_macro": round(f1, 4), "accuracy": round(acc, 4),
|
| 293 |
+
"precision_macro": round(prec, 4), "recall_macro": round(rec, 4),
|
| 294 |
+
})
|
| 295 |
+
print(f" Fold {i+1}: loss={h:.4f} prec={prec:.4f} rec={rec:.4f} "
|
| 296 |
+
f"F1={f1:.4f} acc={acc:.4f}")
|
| 297 |
+
|
| 298 |
+
# --- Full-data predictions (best estimator already refit) ---
|
| 299 |
+
y_pred = best.predict(X)
|
| 300 |
+
dec_all = best.decision_function(X)
|
| 301 |
+
overall_loss = hinge_loss(y, dec_all, labels=np.arange(n_classes))
|
| 302 |
+
|
| 303 |
+
metrics = {
|
| 304 |
+
"accuracy": round(accuracy_score(y, y_pred), 4),
|
| 305 |
+
"precision_macro": round(precision_score(y, y_pred, average="macro", zero_division=0), 4),
|
| 306 |
+
"recall_macro": round(recall_score(y, y_pred, average="macro", zero_division=0), 4),
|
| 307 |
+
"f1_macro": round(f1_score(y, y_pred, average="macro", zero_division=0), 4),
|
| 308 |
+
"f1_weighted": round(f1_score(y, y_pred, average="weighted", zero_division=0), 4),
|
| 309 |
+
"hinge_loss": round(overall_loss, 4),
|
| 310 |
+
"best_params": grid.best_params_,
|
| 311 |
+
"cv_best_f1": round(grid.best_score_, 4),
|
| 312 |
+
"fold_metrics": fold_metrics,
|
| 313 |
+
}
|
| 314 |
+
|
| 315 |
+
print(f"\n {'='*50}")
|
| 316 |
+
print(f" Overall Metrics (full training set)")
|
| 317 |
+
print(f" {'='*50}")
|
| 318 |
+
for k in ["accuracy", "precision_macro", "recall_macro",
|
| 319 |
+
"f1_macro", "f1_weighted", "hinge_loss"]:
|
| 320 |
+
print(f" {k:20s}: {metrics[k]:.4f}")
|
| 321 |
+
|
| 322 |
+
report = classification_report(
|
| 323 |
+
y, y_pred, target_names=le.classes_, zero_division=0
|
| 324 |
+
)
|
| 325 |
+
print(f"\n{report}")
|
| 326 |
+
|
| 327 |
+
return best, scaler, y_pred, metrics, report
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
# ────────────────────────── 7. Drift test ──────────────────────────
|
| 331 |
+
def run_drift_test(model, scaler, vectorizers, cat_columns_map, le):
|
| 332 |
+
"""Test trained SVM on 2026-04-06 data using test_SVM labels."""
|
| 333 |
+
print("\n" + "=" * 60)
|
| 334 |
+
print(" Drift Test (2026-04-06 data)")
|
| 335 |
+
print("=" * 60)
|
| 336 |
+
|
| 337 |
+
test_frames = []
|
| 338 |
+
for dt in DEVICE_TYPES:
|
| 339 |
+
test_path = os.path.join(TEST_SVM_DIR, f"{dt}.csv")
|
| 340 |
+
filter_path = os.path.join(DRIFT_FILTER_DIR, f"ipraw_{dt}.csv")
|
| 341 |
+
if not os.path.exists(test_path) or not os.path.exists(filter_path):
|
| 342 |
+
continue
|
| 343 |
+
|
| 344 |
+
test_labels = pd.read_csv(test_path, dtype=str)
|
| 345 |
+
test_labels["device_type"] = dt
|
| 346 |
+
test_labels["label"] = dt + "-" + test_labels["vendor"].astype(str)
|
| 347 |
+
ip_set = set(test_labels["ip"])
|
| 348 |
+
|
| 349 |
+
parts, found = [], 0
|
| 350 |
+
for chunk in pd.read_csv(
|
| 351 |
+
filter_path, usecols=USE_COLS, chunksize=CHUNK_SIZE, low_memory=False
|
| 352 |
+
):
|
| 353 |
+
matched = chunk[chunk["ip"].isin(ip_set)]
|
| 354 |
+
if len(matched):
|
| 355 |
+
parts.append(matched)
|
| 356 |
+
found += len(matched)
|
| 357 |
+
if found >= len(ip_set):
|
| 358 |
+
break
|
| 359 |
+
|
| 360 |
+
if parts:
|
| 361 |
+
fp = pd.concat(parts).drop_duplicates("ip", keep="first")
|
| 362 |
+
fp["device_type"] = dt
|
| 363 |
+
merged = test_labels.merge(fp, on=["ip", "device_type"], how="inner")
|
| 364 |
+
if len(merged):
|
| 365 |
+
test_frames.append(merged)
|
| 366 |
+
print(f" {dt:30s}: {len(merged):4d} samples")
|
| 367 |
+
else:
|
| 368 |
+
print(f" {dt:30s}: NONE found in filter")
|
| 369 |
+
|
| 370 |
+
if not test_frames:
|
| 371 |
+
print(" No test data found — skipping drift test.")
|
| 372 |
+
return
|
| 373 |
+
|
| 374 |
+
test_df = pd.concat(test_frames, ignore_index=True)
|
| 375 |
+
|
| 376 |
+
known_mask = test_df["label"].isin(le.classes_)
|
| 377 |
+
skipped = (~known_mask).sum()
|
| 378 |
+
if skipped:
|
| 379 |
+
print(f" Skipping {skipped} samples with unseen labels (not in training set)")
|
| 380 |
+
test_df = test_df[known_mask].copy()
|
| 381 |
+
if test_df.empty:
|
| 382 |
+
print(" All test labels are unseen — skipping drift test.")
|
| 383 |
+
return
|
| 384 |
+
|
| 385 |
+
X_test = transform_features(test_df.copy(), vectorizers, cat_columns_map)
|
| 386 |
+
X_test = scaler.transform(X_test)
|
| 387 |
+
y_true = le.transform(test_df["label"])
|
| 388 |
+
y_pred = model.predict(X_test)
|
| 389 |
+
|
| 390 |
+
metrics = {
|
| 391 |
+
"accuracy": round(accuracy_score(y_true, y_pred), 4),
|
| 392 |
+
"precision_macro": round(precision_score(y_true, y_pred, average="macro", zero_division=0), 4),
|
| 393 |
+
"recall_macro": round(recall_score(y_true, y_pred, average="macro", zero_division=0), 4),
|
| 394 |
+
"f1_macro": round(f1_score(y_true, y_pred, average="macro", zero_division=0), 4),
|
| 395 |
+
"f1_weighted": round(f1_score(y_true, y_pred, average="weighted", zero_division=0), 4),
|
| 396 |
+
}
|
| 397 |
+
|
| 398 |
+
print(f"\n {'='*50}")
|
| 399 |
+
print(f" Drift Test Metrics")
|
| 400 |
+
print(f" {'='*50}")
|
| 401 |
+
for k, v in metrics.items():
|
| 402 |
+
print(f" {k:20s}: {v:.4f}")
|
| 403 |
+
|
| 404 |
+
unique_true = np.unique(y_true)
|
| 405 |
+
report = classification_report(
|
| 406 |
+
y_true, y_pred,
|
| 407 |
+
labels=unique_true,
|
| 408 |
+
target_names=le.inverse_transform(unique_true),
|
| 409 |
+
zero_division=0,
|
| 410 |
+
)
|
| 411 |
+
print(f"\n{report}")
|
| 412 |
+
|
| 413 |
+
labels_pred = le.inverse_transform(y_pred)
|
| 414 |
+
test_df = test_df.copy()
|
| 415 |
+
test_df["label_pred"] = labels_pred
|
| 416 |
+
test_df["correct"] = test_df["label"] == test_df["label_pred"]
|
| 417 |
+
|
| 418 |
+
print(" Per-type drift test accuracy:")
|
| 419 |
+
for dt in DEVICE_TYPES:
|
| 420 |
+
sub = test_df[test_df["device_type"] == dt]
|
| 421 |
+
if sub.empty:
|
| 422 |
+
continue
|
| 423 |
+
out = sub[["ip", "vendor", "label", "label_pred", "correct"]].copy()
|
| 424 |
+
out.to_csv(os.path.join(TEST_PREDICT_SUBDIR, f"{dt}_test_pred.csv"), index=False)
|
| 425 |
+
acc = sub["correct"].mean()
|
| 426 |
+
print(f" {dt:30s}: {sub['correct'].sum():4d}/{len(sub):4d} ({acc*100:.1f}%)")
|
| 427 |
+
|
| 428 |
+
def _convert(o):
|
| 429 |
+
if isinstance(o, (np.integer,)):
|
| 430 |
+
return int(o)
|
| 431 |
+
if isinstance(o, (np.floating,)):
|
| 432 |
+
return float(o)
|
| 433 |
+
if isinstance(o, np.ndarray):
|
| 434 |
+
return o.tolist()
|
| 435 |
+
return o
|
| 436 |
+
|
| 437 |
+
with open(os.path.join(SVM_TEST_DIR, "test_metrics.json"), "w", encoding="utf-8") as f:
|
| 438 |
+
json.dump(metrics, f, indent=2, default=_convert)
|
| 439 |
+
with open(os.path.join(SVM_TEST_DIR, "test_classification_report.txt"), "w") as f:
|
| 440 |
+
f.write(report)
|
| 441 |
+
|
| 442 |
+
print(f"\n Test predictions saved to {TEST_PREDICT_SUBDIR}")
|
| 443 |
+
print(f" Test metrics/reports saved to {SVM_TEST_DIR}")
|
| 444 |
+
return metrics
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
# ────────────────────────── 6. Save results ──────────────────────────
|
| 448 |
+
def save_results(merged_df, y_pred, le, metrics, report):
|
| 449 |
+
labels_pred = le.inverse_transform(y_pred)
|
| 450 |
+
merged_df = merged_df.copy()
|
| 451 |
+
merged_df["label_pred"] = labels_pred
|
| 452 |
+
merged_df["correct"] = merged_df["label"] == merged_df["label_pred"]
|
| 453 |
+
|
| 454 |
+
print(" Per-type training accuracy:")
|
| 455 |
+
for dt in DEVICE_TYPES:
|
| 456 |
+
sub = merged_df[merged_df["device_type"] == dt]
|
| 457 |
+
out = sub[["ip", "vendor", "label", "label_pred", "correct"]].copy()
|
| 458 |
+
out.to_csv(os.path.join(PREDICT_SUBDIR, f"{dt}_pred.csv"), index=False)
|
| 459 |
+
acc = sub["correct"].mean()
|
| 460 |
+
print(f" {dt:30s}: {sub['correct'].sum():4d}/{len(sub):4d} "
|
| 461 |
+
f"({acc*100:.1f}%)")
|
| 462 |
+
|
| 463 |
+
# numpy / pandas type converter for JSON
|
| 464 |
+
def _convert(o):
|
| 465 |
+
if isinstance(o, (np.integer,)):
|
| 466 |
+
return int(o)
|
| 467 |
+
if isinstance(o, (np.floating,)):
|
| 468 |
+
return float(o)
|
| 469 |
+
if isinstance(o, np.ndarray):
|
| 470 |
+
return o.tolist()
|
| 471 |
+
return o
|
| 472 |
+
|
| 473 |
+
with open(os.path.join(OUTPUT_DIR, "metrics.json"), "w", encoding="utf-8") as f:
|
| 474 |
+
json.dump(metrics, f, indent=2, default=_convert)
|
| 475 |
+
|
| 476 |
+
with open(os.path.join(OUTPUT_DIR, "classification_report.txt"), "w") as f:
|
| 477 |
+
f.write(report)
|
| 478 |
+
|
| 479 |
+
label_map = {name: int(idx) for idx, name in enumerate(le.classes_)}
|
| 480 |
+
with open(os.path.join(OUTPUT_DIR, "label_encoding.json"), "w", encoding="utf-8") as f:
|
| 481 |
+
json.dump(label_map, f, indent=2, ensure_ascii=False)
|
| 482 |
+
|
| 483 |
+
print(f"\n Predictions saved to {PREDICT_SUBDIR}")
|
| 484 |
+
print(f" Metrics/reports saved to {OUTPUT_DIR}")
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
# ────────────────────────── Model save / load ──────────────────────────
|
| 488 |
+
def save_model(model, scaler, vectorizers, cat_columns_map, le):
|
| 489 |
+
bundle = {
|
| 490 |
+
"model": model,
|
| 491 |
+
"scaler": scaler,
|
| 492 |
+
"vectorizers": vectorizers,
|
| 493 |
+
"cat_columns_map": cat_columns_map,
|
| 494 |
+
"le": le,
|
| 495 |
+
}
|
| 496 |
+
joblib.dump(bundle, MODEL_BUNDLE, compress=3)
|
| 497 |
+
print(f" Model bundle saved → {MODEL_BUNDLE}")
|
| 498 |
+
|
| 499 |
+
|
| 500 |
+
def load_model():
|
| 501 |
+
if not os.path.exists(MODEL_BUNDLE):
|
| 502 |
+
return None
|
| 503 |
+
bundle = joblib.load(MODEL_BUNDLE)
|
| 504 |
+
print(f" Model bundle loaded ← {MODEL_BUNDLE}")
|
| 505 |
+
return bundle["model"], bundle["scaler"], bundle["vectorizers"], bundle["cat_columns_map"], bundle["le"]
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
# ────────────────────────── 8. Validation ──────────────────────────
|
| 509 |
+
def load_detected_ips(csv_path):
|
| 510 |
+
"""Load detected IPs CSV (ip, vendor, device_type, class_drift_score)."""
|
| 511 |
+
df = pd.read_csv(csv_path, dtype=str)
|
| 512 |
+
df["label"] = df["device_type"] + "-" + df["vendor"]
|
| 513 |
+
return df
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
def load_fingerprints_from_filter(label_df):
|
| 517 |
+
"""Load fingerprints for IPs from the drift filter directory (2026-04-06)."""
|
| 518 |
+
all_fps = []
|
| 519 |
+
for dt in DEVICE_TYPES:
|
| 520 |
+
ip_set = set(label_df.loc[label_df["device_type"] == dt, "ip"])
|
| 521 |
+
if not ip_set:
|
| 522 |
+
continue
|
| 523 |
+
filter_path = os.path.join(DRIFT_FILTER_DIR, f"ipraw_{dt}.csv")
|
| 524 |
+
if not os.path.exists(filter_path):
|
| 525 |
+
continue
|
| 526 |
+
print(f" {dt:30s} ({len(ip_set):4d} IPs) ... ", end="", flush=True)
|
| 527 |
+
t0 = time.time()
|
| 528 |
+
parts, found = [], 0
|
| 529 |
+
for chunk in pd.read_csv(
|
| 530 |
+
filter_path, usecols=USE_COLS, chunksize=CHUNK_SIZE, low_memory=False
|
| 531 |
+
):
|
| 532 |
+
matched = chunk[chunk["ip"].isin(ip_set)]
|
| 533 |
+
if len(matched):
|
| 534 |
+
parts.append(matched)
|
| 535 |
+
found += len(matched)
|
| 536 |
+
if found >= len(ip_set):
|
| 537 |
+
break
|
| 538 |
+
if parts:
|
| 539 |
+
fp = pd.concat(parts).drop_duplicates("ip", keep="first")
|
| 540 |
+
fp["device_type"] = dt
|
| 541 |
+
all_fps.append(fp)
|
| 542 |
+
print(f"found {len(fp):4d} ({time.time()-t0:.1f}s)")
|
| 543 |
+
else:
|
| 544 |
+
print("NONE found!")
|
| 545 |
+
if not all_fps:
|
| 546 |
+
return pd.DataFrame()
|
| 547 |
+
return pd.concat(all_fps, ignore_index=True)
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
def run_validation(method_name, detected_csv, train_label_df, train_fp_df):
|
| 551 |
+
"""
|
| 552 |
+
Validation: add detected IPs to training set, retrain SVM, evaluate on drift test set.
|
| 553 |
+
"""
|
| 554 |
+
val_out_dir = os.path.join(VALIDATION_DIR, "performance", method_name)
|
| 555 |
+
val_pred_dir = os.path.join(val_out_dir, "predict")
|
| 556 |
+
os.makedirs(val_pred_dir, exist_ok=True)
|
| 557 |
+
|
| 558 |
+
print("\n" + "=" * 60)
|
| 559 |
+
print(f" Validation ({method_name})")
|
| 560 |
+
print("=" * 60)
|
| 561 |
+
|
| 562 |
+
# ── Load detected IPs ──
|
| 563 |
+
print(f"\n Loading detected IPs from {detected_csv} ...")
|
| 564 |
+
detected_df = load_detected_ips(detected_csv)
|
| 565 |
+
print(f" Detected IPs: {len(detected_df)}")
|
| 566 |
+
|
| 567 |
+
# ── Load fingerprints for detected IPs from filter dir ──
|
| 568 |
+
print(" Loading fingerprints for detected IPs ...")
|
| 569 |
+
det_fp = load_fingerprints_from_filter(detected_df)
|
| 570 |
+
if det_fp.empty:
|
| 571 |
+
print(" No fingerprints found for detected IPs — skipping validation.")
|
| 572 |
+
return
|
| 573 |
+
det_merged = detected_df[["ip", "vendor", "device_type", "label"]].merge(
|
| 574 |
+
det_fp, on=["ip", "device_type"], how="inner"
|
| 575 |
+
)
|
| 576 |
+
print(f" Detected IPs with fingerprints: {len(det_merged)}")
|
| 577 |
+
|
| 578 |
+
# ── Combine with original training data ──
|
| 579 |
+
orig_merged = train_label_df[["ip", "vendor", "device_type", "label"]].merge(
|
| 580 |
+
train_fp_df, on=["ip", "device_type"], how="inner"
|
| 581 |
+
)
|
| 582 |
+
combined = pd.concat([orig_merged, det_merged], ignore_index=True)
|
| 583 |
+
combined = combined.drop_duplicates("ip", keep="first")
|
| 584 |
+
print(f" Combined training set: {len(combined)} (orig {len(orig_merged)} + detected {len(det_merged)})")
|
| 585 |
+
|
| 586 |
+
# ── Encode labels ──
|
| 587 |
+
le_val = LabelEncoder()
|
| 588 |
+
y_combined = le_val.fit_transform(combined["label"])
|
| 589 |
+
|
| 590 |
+
# ── Build features ──
|
| 591 |
+
print(" Building features ...")
|
| 592 |
+
X_combined, vec_val, cat_map_val = build_features(combined.copy())
|
| 593 |
+
|
| 594 |
+
# ── Train SVM ──
|
| 595 |
+
scaler_val = MaxAbsScaler()
|
| 596 |
+
X_combined = scaler_val.fit_transform(X_combined)
|
| 597 |
+
|
| 598 |
+
n_classes = len(le_val.classes_)
|
| 599 |
+
print(f" Samples={X_combined.shape[0]} Features={X_combined.shape[1]} Classes={n_classes}")
|
| 600 |
+
|
| 601 |
+
param_grid = [
|
| 602 |
+
{"kernel": ["rbf"], "C": [1, 10, 100], "gamma": ["scale", 0.01]},
|
| 603 |
+
{"kernel": ["linear"], "C": [0.1, 1, 10]},
|
| 604 |
+
{"kernel": ["poly"], "C": [1, 10], "degree": [3], "gamma": ["scale"]},
|
| 605 |
+
]
|
| 606 |
+
skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
|
| 607 |
+
svm = SVC(
|
| 608 |
+
decision_function_shape="ovr",
|
| 609 |
+
class_weight="balanced",
|
| 610 |
+
random_state=42,
|
| 611 |
+
cache_size=2000,
|
| 612 |
+
)
|
| 613 |
+
grid = GridSearchCV(
|
| 614 |
+
svm, param_grid, cv=skf, scoring="f1_macro",
|
| 615 |
+
n_jobs=-1, verbose=2, refit=True,
|
| 616 |
+
)
|
| 617 |
+
print("\n Running GridSearchCV ...")
|
| 618 |
+
t0 = time.time()
|
| 619 |
+
grid.fit(X_combined, y_combined)
|
| 620 |
+
print(f" GridSearch done in {time.time()-t0:.0f}s")
|
| 621 |
+
best = grid.best_estimator_
|
| 622 |
+
print(f" Best params : {grid.best_params_}")
|
| 623 |
+
print(f" Best CV F1 : {grid.best_score_:.4f}")
|
| 624 |
+
|
| 625 |
+
# ── Evaluate on drift test set ──
|
| 626 |
+
print("\n Evaluating on drift test set ...")
|
| 627 |
+
test_frames = []
|
| 628 |
+
for dt in DEVICE_TYPES:
|
| 629 |
+
test_path = os.path.join(TEST_SVM_DIR, f"{dt}.csv")
|
| 630 |
+
filter_path = os.path.join(DRIFT_FILTER_DIR, f"ipraw_{dt}.csv")
|
| 631 |
+
if not os.path.exists(test_path) or not os.path.exists(filter_path):
|
| 632 |
+
continue
|
| 633 |
+
test_labels = pd.read_csv(test_path, dtype=str)
|
| 634 |
+
test_labels["device_type"] = dt
|
| 635 |
+
test_labels["label"] = dt + "-" + test_labels["vendor"].astype(str)
|
| 636 |
+
ip_set = set(test_labels["ip"])
|
| 637 |
+
parts, found = [], 0
|
| 638 |
+
for chunk in pd.read_csv(
|
| 639 |
+
filter_path, usecols=USE_COLS, chunksize=CHUNK_SIZE, low_memory=False
|
| 640 |
+
):
|
| 641 |
+
matched = chunk[chunk["ip"].isin(ip_set)]
|
| 642 |
+
if len(matched):
|
| 643 |
+
parts.append(matched)
|
| 644 |
+
found += len(matched)
|
| 645 |
+
if found >= len(ip_set):
|
| 646 |
+
break
|
| 647 |
+
if parts:
|
| 648 |
+
fp = pd.concat(parts).drop_duplicates("ip", keep="first")
|
| 649 |
+
fp["device_type"] = dt
|
| 650 |
+
merged = test_labels.merge(fp, on=["ip", "device_type"], how="inner")
|
| 651 |
+
if len(merged):
|
| 652 |
+
test_frames.append(merged)
|
| 653 |
+
print(f" {dt:30s}: {len(merged):4d} samples")
|
| 654 |
+
else:
|
| 655 |
+
print(f" {dt:30s}: NONE found in filter")
|
| 656 |
+
|
| 657 |
+
if not test_frames:
|
| 658 |
+
print(" No test data found — skipping validation test.")
|
| 659 |
+
return
|
| 660 |
+
|
| 661 |
+
test_df = pd.concat(test_frames, ignore_index=True)
|
| 662 |
+
known_mask = test_df["label"].isin(le_val.classes_)
|
| 663 |
+
skipped = (~known_mask).sum()
|
| 664 |
+
if skipped:
|
| 665 |
+
print(f" Skipping {skipped} samples with unseen labels")
|
| 666 |
+
test_df = test_df[known_mask].copy()
|
| 667 |
+
if test_df.empty:
|
| 668 |
+
print(" All test labels are unseen — skipping validation test.")
|
| 669 |
+
return
|
| 670 |
+
|
| 671 |
+
X_test = transform_features(test_df.copy(), vec_val, cat_map_val)
|
| 672 |
+
X_test = scaler_val.transform(X_test)
|
| 673 |
+
y_pred_enc = best.predict(X_test)
|
| 674 |
+
|
| 675 |
+
labels_pred = le_val.inverse_transform(y_pred_enc)
|
| 676 |
+
test_df = test_df.copy()
|
| 677 |
+
test_df["label_pred"] = labels_pred
|
| 678 |
+
test_df["correct"] = [
|
| 679 |
+
label_match(a, b) for a, b in zip(test_df["label"], test_df["label_pred"])
|
| 680 |
+
]
|
| 681 |
+
|
| 682 |
+
# Compute metrics on normalized labels (case-insensitive + vendor fuzzy)
|
| 683 |
+
norm_true = [normalize_label(l) for l in test_df["label"]]
|
| 684 |
+
norm_pred = [normalize_label(l) for l in test_df["label_pred"]]
|
| 685 |
+
le_norm = LabelEncoder()
|
| 686 |
+
all_norm = list(set(norm_true + norm_pred))
|
| 687 |
+
le_norm.fit(all_norm)
|
| 688 |
+
y_true_n = le_norm.transform(norm_true)
|
| 689 |
+
y_pred_n = le_norm.transform(norm_pred)
|
| 690 |
+
|
| 691 |
+
metrics = {
|
| 692 |
+
"accuracy": round(accuracy_score(y_true_n, y_pred_n), 4),
|
| 693 |
+
"precision_macro": round(precision_score(y_true_n, y_pred_n, average="macro", zero_division=0), 4),
|
| 694 |
+
"recall_macro": round(recall_score(y_true_n, y_pred_n, average="macro", zero_division=0), 4),
|
| 695 |
+
"f1_macro": round(f1_score(y_true_n, y_pred_n, average="macro", zero_division=0), 4),
|
| 696 |
+
"f1_weighted": round(f1_score(y_true_n, y_pred_n, average="weighted", zero_division=0), 4),
|
| 697 |
+
"best_params": grid.best_params_,
|
| 698 |
+
"cv_best_f1": round(grid.best_score_, 4),
|
| 699 |
+
"n_train_orig": len(orig_merged),
|
| 700 |
+
"n_train_detected": len(det_merged),
|
| 701 |
+
"n_train_combined": len(combined),
|
| 702 |
+
}
|
| 703 |
+
|
| 704 |
+
print(f"\n {'='*50}")
|
| 705 |
+
print(f" Validation Test Metrics ({method_name})")
|
| 706 |
+
print(f" {'='*50}")
|
| 707 |
+
for k in ["accuracy", "precision_macro", "recall_macro", "f1_macro", "f1_weighted"]:
|
| 708 |
+
print(f" {k:20s}: {metrics[k]:.4f}")
|
| 709 |
+
|
| 710 |
+
unique_true_n = np.unique(y_true_n)
|
| 711 |
+
report = classification_report(
|
| 712 |
+
y_true_n, y_pred_n,
|
| 713 |
+
labels=unique_true_n,
|
| 714 |
+
target_names=le_norm.inverse_transform(unique_true_n),
|
| 715 |
+
zero_division=0,
|
| 716 |
+
)
|
| 717 |
+
print(f"\n{report}")
|
| 718 |
+
|
| 719 |
+
print(f" Per-type validation accuracy ({method_name}):")
|
| 720 |
+
for dt in DEVICE_TYPES:
|
| 721 |
+
sub = test_df[test_df["device_type"] == dt]
|
| 722 |
+
if sub.empty:
|
| 723 |
+
continue
|
| 724 |
+
out = sub[["ip", "vendor", "label", "label_pred", "correct"]].copy()
|
| 725 |
+
out.to_csv(os.path.join(val_pred_dir, f"{dt}_val_pred.csv"), index=False)
|
| 726 |
+
acc = sub["correct"].mean()
|
| 727 |
+
print(f" {dt:30s}: {sub['correct'].sum():4d}/{len(sub):4d} ({acc*100:.1f}%)")
|
| 728 |
+
|
| 729 |
+
def _convert(o):
|
| 730 |
+
if isinstance(o, (np.integer,)):
|
| 731 |
+
return int(o)
|
| 732 |
+
if isinstance(o, (np.floating,)):
|
| 733 |
+
return float(o)
|
| 734 |
+
if isinstance(o, np.ndarray):
|
| 735 |
+
return o.tolist()
|
| 736 |
+
return o
|
| 737 |
+
|
| 738 |
+
with open(os.path.join(val_out_dir, "val_metrics.json"), "w", encoding="utf-8") as f:
|
| 739 |
+
json.dump(metrics, f, indent=2, default=_convert)
|
| 740 |
+
with open(os.path.join(val_out_dir, "val_classification_report.txt"), "w") as f:
|
| 741 |
+
f.write(report)
|
| 742 |
+
|
| 743 |
+
print(f"\n Validation results saved to {val_out_dir}")
|
| 744 |
+
return metrics
|
| 745 |
+
|
| 746 |
+
|
| 747 |
+
# ────────────────────── Re-evaluate predictions ──────────────────────
|
| 748 |
+
def reeval_predictions(method_name):
|
| 749 |
+
"""Re-read existing prediction CSVs, recompute correctness and full metrics
|
| 750 |
+
using normalized labels (case-insensitive + vendor fuzzy match)."""
|
| 751 |
+
perf_dir = os.path.join(VALIDATION_DIR, "performance", method_name)
|
| 752 |
+
pred_dir = os.path.join(perf_dir, "predict")
|
| 753 |
+
|
| 754 |
+
print("\n" + "=" * 60)
|
| 755 |
+
print(f" Re-evaluate predictions ({method_name})")
|
| 756 |
+
print("=" * 60)
|
| 757 |
+
|
| 758 |
+
all_frames = []
|
| 759 |
+
for dt in DEVICE_TYPES:
|
| 760 |
+
csv_path = os.path.join(pred_dir, f"{dt}_val_pred.csv")
|
| 761 |
+
if not os.path.exists(csv_path):
|
| 762 |
+
continue
|
| 763 |
+
df = pd.read_csv(csv_path, dtype=str)
|
| 764 |
+
df["correct"] = [
|
| 765 |
+
label_match(a, b) for a, b in zip(df["label"], df["label_pred"])
|
| 766 |
+
]
|
| 767 |
+
df["device_type"] = dt
|
| 768 |
+
df.to_csv(csv_path, index=False, columns=["ip", "vendor", "label", "label_pred", "correct"])
|
| 769 |
+
all_frames.append(df)
|
| 770 |
+
acc = df["correct"].mean()
|
| 771 |
+
print(f" {dt:30s}: {df['correct'].sum():4d}/{len(df):4d} ({acc*100:.1f}%)")
|
| 772 |
+
|
| 773 |
+
if not all_frames:
|
| 774 |
+
print(" No prediction files found.")
|
| 775 |
+
return
|
| 776 |
+
|
| 777 |
+
full = pd.concat(all_frames, ignore_index=True)
|
| 778 |
+
|
| 779 |
+
# Compute full metrics on normalized labels
|
| 780 |
+
norm_true = [normalize_label(l) for l in full["label"]]
|
| 781 |
+
norm_pred = [normalize_label(l) for l in full["label_pred"]]
|
| 782 |
+
le_norm = LabelEncoder()
|
| 783 |
+
le_norm.fit(list(set(norm_true + norm_pred)))
|
| 784 |
+
y_true_n = le_norm.transform(norm_true)
|
| 785 |
+
y_pred_n = le_norm.transform(norm_pred)
|
| 786 |
+
|
| 787 |
+
metrics = {
|
| 788 |
+
"accuracy": round(accuracy_score(y_true_n, y_pred_n), 4),
|
| 789 |
+
"precision_macro": round(precision_score(y_true_n, y_pred_n, average="macro", zero_division=0), 4),
|
| 790 |
+
"recall_macro": round(recall_score(y_true_n, y_pred_n, average="macro", zero_division=0), 4),
|
| 791 |
+
"f1_macro": round(f1_score(y_true_n, y_pred_n, average="macro", zero_division=0), 4),
|
| 792 |
+
"f1_weighted": round(f1_score(y_true_n, y_pred_n, average="weighted", zero_division=0), 4),
|
| 793 |
+
"total_samples": int(len(full)),
|
| 794 |
+
}
|
| 795 |
+
|
| 796 |
+
print(f"\n {'='*50}")
|
| 797 |
+
print(f" Overall Metrics ({method_name})")
|
| 798 |
+
print(f" {'='*50}")
|
| 799 |
+
for k in ["accuracy", "precision_macro", "recall_macro", "f1_macro", "f1_weighted"]:
|
| 800 |
+
print(f" {k:20s}: {metrics[k]:.4f}")
|
| 801 |
+
|
| 802 |
+
metrics_path = os.path.join(perf_dir, "val_metrics.json")
|
| 803 |
+
with open(metrics_path, "w", encoding="utf-8") as f:
|
| 804 |
+
json.dump(metrics, f, indent=2)
|
| 805 |
+
print(f" Updated metrics saved to {metrics_path}")
|
| 806 |
+
|
| 807 |
+
|
| 808 |
+
# ────────────────────────── main ──────────────────────────
|
| 809 |
+
def main():
|
| 810 |
+
parser = argparse.ArgumentParser(description="SVM IoT Device Classifier")
|
| 811 |
+
parser.add_argument("--retrain", action="store_true",
|
| 812 |
+
help="Force retraining even if a saved model bundle exists")
|
| 813 |
+
parser.add_argument("--drift-only", action="store_true",
|
| 814 |
+
help="Skip training, only run drift test using saved model")
|
| 815 |
+
parser.add_argument("--validate-only", action="store_true",
|
| 816 |
+
help="Skip training and drift test, only run validation")
|
| 817 |
+
parser.add_argument("--reeval", action="store_true",
|
| 818 |
+
help="Re-evaluate existing prediction CSVs case-insensitively")
|
| 819 |
+
args = parser.parse_args()
|
| 820 |
+
|
| 821 |
+
t_start = time.time()
|
| 822 |
+
print("=" * 60)
|
| 823 |
+
print(" SVM IoT Device Classifier (type-vendor labels)")
|
| 824 |
+
print("=" * 60)
|
| 825 |
+
|
| 826 |
+
if args.reeval:
|
| 827 |
+
reeval_predictions("IoTProber")
|
| 828 |
+
reeval_predictions("CADE")
|
| 829 |
+
print(f"\nTotal time: {time.time()-t_start:.0f}s")
|
| 830 |
+
return
|
| 831 |
+
|
| 832 |
+
if args.validate_only:
|
| 833 |
+
# ── Validate-only mode: skip training & drift test ──
|
| 834 |
+
print("\n --validate-only: skipping training and drift test.")
|
| 835 |
+
print("\n Loading training data for validation ...")
|
| 836 |
+
label_df = load_labels()
|
| 837 |
+
fp_df = load_fingerprints(label_df)
|
| 838 |
+
else:
|
| 839 |
+
# ── Try loading saved model ────────────────────────────────────────
|
| 840 |
+
bundle = None if args.retrain else load_model()
|
| 841 |
+
|
| 842 |
+
if bundle is not None:
|
| 843 |
+
model, scaler, vectorizers, cat_columns_map, le = bundle
|
| 844 |
+
print(f" Loaded {len(le.classes_)} classes from saved bundle.")
|
| 845 |
+
print(" Skipping training. Use --retrain to force retraining.")
|
| 846 |
+
else:
|
| 847 |
+
if args.drift_only:
|
| 848 |
+
print(" --drift-only requires a saved model bundle. Run without --drift-only first.")
|
| 849 |
+
return
|
| 850 |
+
|
| 851 |
+
# 1. Labels
|
| 852 |
+
print("\n[1/5] Loading labels ...")
|
| 853 |
+
label_df = load_labels()
|
| 854 |
+
print(f" {len(label_df)} samples, {label_df['label'].nunique()} classes")
|
| 855 |
+
|
| 856 |
+
# 2. Fingerprints
|
| 857 |
+
print("\n[2/5] Loading fingerprints ...")
|
| 858 |
+
fp_df = load_fingerprints(label_df)
|
| 859 |
+
|
| 860 |
+
merged = label_df.merge(fp_df, on=["ip", "device_type"], how="inner")
|
| 861 |
+
print(f" Matched: {len(merged)} / {len(label_df)}")
|
| 862 |
+
|
| 863 |
+
le = LabelEncoder()
|
| 864 |
+
y = le.fit_transform(merged["label"])
|
| 865 |
+
|
| 866 |
+
# 3. Features
|
| 867 |
+
print("\n[3/5] Building features ...")
|
| 868 |
+
X, vectorizers, cat_columns_map = build_features(merged)
|
| 869 |
+
|
| 870 |
+
# 4-5. Train & Evaluate
|
| 871 |
+
print("\n[4/5] Training SVM ...")
|
| 872 |
+
model, scaler, y_pred, metrics, report = train_evaluate(X, y, le)
|
| 873 |
+
|
| 874 |
+
# 6. Save predictions
|
| 875 |
+
print("\n[5/5] Saving predictions ...")
|
| 876 |
+
save_results(merged, y_pred, le, metrics, report)
|
| 877 |
+
|
| 878 |
+
# Save model bundle
|
| 879 |
+
print("\n Saving model bundle ...")
|
| 880 |
+
save_model(model, scaler, vectorizers, cat_columns_map, le)
|
| 881 |
+
|
| 882 |
+
# 7. Drift test
|
| 883 |
+
print("\n[6/8] Running drift test on 2026-04-06 data ...")
|
| 884 |
+
run_drift_test(model, scaler, vectorizers, cat_columns_map, le)
|
| 885 |
+
|
| 886 |
+
# ── Prepare original training data for validation ──
|
| 887 |
+
if bundle is not None:
|
| 888 |
+
# Need to reload training data for validation
|
| 889 |
+
print("\n Reloading training data for validation ...")
|
| 890 |
+
label_df = load_labels()
|
| 891 |
+
fp_df = load_fingerprints(label_df)
|
| 892 |
+
|
| 893 |
+
# 8. Validation: IoTProber (using CADE-detected IPs)
|
| 894 |
+
print("\n[7/8] Running validation (IoTProber) ...")
|
| 895 |
+
run_validation("IoTProber", CADE_DETECTED, label_df, fp_df)
|
| 896 |
+
|
| 897 |
+
# 9. Validation: CADE (using IoTProber-detected IPs)
|
| 898 |
+
print("\n[8/8] Running validation (CADE) ...")
|
| 899 |
+
run_validation("CADE", IOTPROBER_DETECTED, label_df, fp_df)
|
| 900 |
+
|
| 901 |
+
print(f"\nTotal time: {time.time()-t_start:.0f}s")
|
| 902 |
+
|
| 903 |
+
|
| 904 |
+
if __name__ == "__main__":
|
| 905 |
+
main()
|