{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# CYB008 Baseline Classifier — Inference Example\n", "\n", "End-to-end demo: load the trained XGBoost and PyTorch MLP models from the Hugging Face repo and predict the **SOC alert triage outcome** from a per-alert record.\n", "\n", "**Models predict one of 5 outcome classes:** `auto_resolved_soar`, `duplicate_merged`, `false_positive_closed`, `true_positive_remediated`, `true_positive_escalated`.\n", "\n", "**This is a baseline reference model**, not a production SOC triage system. See the model card and **especially `leakage_diagnostic.json`** for the structural-leakage findings (three columns were dropped as oracles)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1. Install dependencies" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%pip install --quiet xgboost torch safetensors pandas numpy huggingface_hub" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2. Download model artifacts from Hugging Face" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from huggingface_hub import hf_hub_download\n", "\n", "REPO_ID = \"xpertsystems/cyb008-baseline-classifier\"\n", "\n", "files = {}\n", "for name in [\"model_xgb.json\", \"model_mlp.safetensors\",\n", " \"feature_engineering.py\", \"feature_meta.json\",\n", " \"feature_scaler.json\"]:\n", " files[name] = hf_hub_download(repo_id=REPO_ID, filename=name)\n", " print(f\" downloaded: {name}\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import sys, os\n", "fe_dir = os.path.dirname(files[\"feature_engineering.py\"])\n", "if fe_dir not in sys.path:\n", " sys.path.insert(0, fe_dir)\n", "\n", "from feature_engineering import transform_single, load_meta, INT_TO_LABEL" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3. Load models and metadata" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import json\n", "import numpy as np\n", "import torch\n", "import torch.nn as nn\n", "import xgboost as xgb\n", "from safetensors.torch import load_file\n", "\n", "meta = load_meta(files[\"feature_meta.json\"])\n", "with open(files[\"feature_scaler.json\"]) as f:\n", " scaler = json.load(f)\n", "\n", "N_FEATURES = len(meta[\"feature_names\"])\n", "N_CLASSES = len(meta[\"int_to_label\"])\n", "print(f\"feature count: {N_FEATURES}\")\n", "print(f\"class count: {N_CLASSES}\")\n", "print(f\"label classes: {list(meta['int_to_label'].values())}\")\n", "print(f\"\\noracle columns excluded (do not pass these to the model):\")\n", "for c in meta.get(\"oracle_excluded\", []):\n", " print(f\" - {c}\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "xgb_model = xgb.XGBClassifier()\n", "xgb_model.load_model(files[\"model_xgb.json\"])\n", "\n", "# MLP architecture (must match training)\n", "class TriageMLP(nn.Module):\n", " def __init__(self, n_features, n_classes=5, hidden1=128, hidden2=64, dropout=0.3):\n", " super().__init__()\n", " self.net = nn.Sequential(\n", " nn.Linear(n_features, hidden1),\n", " nn.BatchNorm1d(hidden1),\n", " nn.ReLU(),\n", " nn.Dropout(dropout),\n", " nn.Linear(hidden1, hidden2),\n", " nn.BatchNorm1d(hidden2),\n", " nn.ReLU(),\n", " nn.Dropout(dropout),\n", " nn.Linear(hidden2, n_classes),\n", " )\n", " def forward(self, x):\n", " return self.net(x)\n", "\n", "mlp_model = TriageMLP(N_FEATURES, n_classes=N_CLASSES)\n", "mlp_model.load_state_dict(load_file(files[\"model_mlp.safetensors\"]))\n", "mlp_model.eval()\n", "print(\"models loaded\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4. Prediction helper" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "MU = np.array(scaler[\"mean\"], dtype=np.float32)\n", "SD = np.array(scaler[\"std\"], dtype=np.float32)\n", "\n", "def predict_triage_outcome(record: dict) -> dict:\n", " \"\"\"Predict the resolution outcome for one SOC alert record.\n", "\n", " Note: do NOT include alert_lifecycle_phase, automation_resolved,\n", " or escalation_flag in the record. These were structural oracles\n", " in the training data and are excluded from the feature set.\n", " \"\"\"\n", " X = transform_single(record, meta)\n", "\n", " xgb_proba = xgb_model.predict_proba(X)[0]\n", " xgb_label = INT_TO_LABEL[int(np.argmax(xgb_proba))]\n", "\n", " Xs = ((X - MU) / SD).astype(np.float32)\n", " with torch.no_grad():\n", " logits = mlp_model(torch.tensor(Xs))\n", " mlp_proba = torch.softmax(logits, dim=1).numpy()[0]\n", " mlp_label = INT_TO_LABEL[int(np.argmax(mlp_proba))]\n", "\n", " return {\n", " \"xgboost\": {\n", " \"label\": xgb_label,\n", " \"probabilities\": {INT_TO_LABEL[i]: float(p) for i, p in enumerate(xgb_proba)},\n", " },\n", " \"mlp\": {\n", " \"label\": mlp_label,\n", " \"probabilities\": {INT_TO_LABEL[i]: float(p) for i, p in enumerate(mlp_proba)},\n", " },\n", " }" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5. Run on an example record\n", "\n", "Real high-severity ITDR identity-anomaly alert assigned to an L3 threat hunter, who escalated it to a true-positive incident. Both models should predict `true_positive_escalated` or the adjacent `true_positive_remediated`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Real alert from the sample dataset (true outcome: true_positive_escalated)\n", "example_record = {\n", " \"alert_severity\": \"high_severity\",\n", " \"alert_source\": \"itdr_identity_anomaly\",\n", " \"mitre_tactic\": \"initial_access\",\n", " \"analyst_tier\": \"L3_threat_hunter\",\n", " \"siem_platform\": \"logrhythm_axon\",\n", " \"raw_score\": 0.2683,\n", " \"enriched_score\": 0.343,\n", " \"time_in_phase_minutes\": 429.26,\n", " \"queue_depth_at_ingestion\": 0,\n", " \"soar_playbook_triggered\": 0,\n", " \"sla_breached_flag\": 1,\n", " \"mttd_minutes\": 177.47,\n", " \"mttr_minutes\": 429.26,\n", " \"fatigue_score_at_alert\": 0.3805,\n", "}\n", "\n", "result = predict_triage_outcome(example_record)\n", "\n", "print(f\"XGBoost -> {result['xgboost']['label']}\")\n", "for lbl, p in sorted(result['xgboost']['probabilities'].items(), key=lambda x: -x[1]):\n", " print(f\" P({lbl:30s}) = {p:.4f}\")\n", "\n", "print(f\"\\nMLP -> {result['mlp']['label']}\")\n", "for lbl, p in sorted(result['mlp']['probabilities'].items(), key=lambda x: -x[1]):\n", " print(f\" P({lbl:30s}) = {p:.4f}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Honest confusion between TP-remediated and TP-escalated\n", "\n", "The two `true_positive_*` outcomes look behaviourally similar in the data — both involve genuine threats. They differ by whether the alert was closed by the original analyst (remediated) or passed to a higher tier (escalated). When the trained models confuse these two classes on individual alerts, that's honest learning — not a defect.\n", "\n", "In a production triage workflow, the better operational metric is **TP vs FP** (recall on true positives, regardless of remediated/escalated). The published baseline achieves ROC-AUC 0.955 on the full 5-class task, which substantially exceeds practical thresholds for downstream binary TP-vs-FP decisions." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6. Batch prediction on the sample dataset" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from huggingface_hub import snapshot_download\n", "import pandas as pd\n", "\n", "ds_path = snapshot_download(repo_id=\"xpertsystems/cyb008-sample\", repo_type=\"dataset\")\n", "alerts = pd.read_csv(f\"{ds_path}/soc_alerts.csv\")\n", "\n", "# Score the first 500 alerts\n", "sample = alerts.head(500).copy()\n", "preds = [predict_triage_outcome(row.to_dict())[\"xgboost\"][\"label\"] for _, row in sample.iterrows()]\n", "sample[\"xgb_pred\"] = preds\n", "\n", "ct = pd.crosstab(sample[\"resolution_outcome\"], sample[\"xgb_pred\"],\n", " rownames=[\"true\"], colnames=[\"pred\"])\n", "print(\"Confusion on first 500 sample alerts (XGBoost):\")\n", "print(ct)\n", "acc = (sample[\"resolution_outcome\"] == sample[\"xgb_pred\"]).mean()\n", "print(f\"\\nbatch accuracy on first 500 alerts (in-distribution): {acc:.4f}\")\n", "print(\"\\nNote: this includes training-set alerts. See validation_results.json\\n\"\n", " \"for proper held-out test metrics.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 7. Important reading: the leakage diagnostic\n", "\n", "Before using CYB008 sample data to train your own triage model, read **`leakage_diagnostic.json`** in this repo. The CYB008 sample has three columns (`alert_lifecycle_phase`, `automation_resolved`, `escalation_flag`) that structurally encode the resolution_outcome label. With these columns present, a plain XGBoost achieves 100% accuracy that does not reflect real learning. The published baseline excludes them; the diagnostic file shows the cumulative ablation.\n", "\n", "The diagnostic also documents that **mitre_tactic prediction is unlearnable on this sample** (acc 0.08 vs majority 0.14). The README lists this as a top suggested use case, but the per-tactic feature distributions are too similar to learn from." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 8. Next steps\n", "\n", "- See `validation_results.json` for held-out test metrics (1,380 alerts).\n", "- See `multi_seed_results.json` for the across-10-seeds picture (accuracy 0.777 ± 0.007, ROC-AUC 0.955 ± 0.003).\n", "- See `ablation_results.json` for per-feature-group contribution. Alert severity carries the dominant signal (−25 pp accuracy when removed); the SOAR-playbook-triggered indicator is second (−15 pp).\n", "- See **`leakage_diagnostic.json`** for the full structural-leakage and unlearnable-target audit.\n", "- For the full ~335k-row CYB008 dataset and commercial licensing, contact **pradeep@xpertsystems.ai**." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python", "version": "3.10" } }, "nbformat": 4, "nbformat_minor": 5 }