"""Compare offline verdict classifiers on disjoint organization groups in GUIDE v2.""" import argparse from collections import Counter from concurrent.futures import ThreadPoolExecutor import csv from dataclasses import dataclass, field from datetime import datetime import hashlib import json from pathlib import Path import platform from typing import Optional from urllib.request import urlopen import numpy as np import scipy import sklearn from sklearn.base import clone from sklearn.dummy import DummyClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.feature_extraction import DictVectorizer from sklearn.linear_model import LogisticRegression from sklearn.metrics import confusion_matrix, f1_score from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from error_analysis import category_analysis BASE = "https://www.kaggle.com/api/v1/datasets/download/microsoft/microsoft-security-incident-prediction" VERSION = 2 MAX_ROWS_PER_FILE = 150_000 GRADES = ("BenignPositive", "FalsePositive", "TruePositive") COLUMNS = ("OrgId", "IncidentId", "AlertId", "Timestamp", "IncidentGrade", "Category", "DetectorId") SEED = 42 @dataclass class Incident: first_timestamp: Optional[datetime] = None early_categories: set = field(default_factory=set) early_alerts: set = field(default_factory=set) early_detectors: set = field(default_factory=set) observed_alerts: set = field(default_factory=set) grades: set = field(default_factory=set) def record(self, alert, timestamp, grade, category, detector): self.observed_alerts.add(alert) if grade: self.grades.add(grade) if self.first_timestamp is None or timestamp < self.first_timestamp: self.first_timestamp = timestamp self.early_categories.clear() self.early_alerts.clear() self.early_detectors.clear() if timestamp == self.first_timestamp: self.early_alerts.add(alert) if category: self.early_categories.add(category) if detector: self.early_detectors.add(detector) def features(self): features = {f"category={category}": 1 for category in sorted(self.early_categories)} features["early_alert_count"] = len(self.early_alerts) features["early_detector_count"] = len(self.early_detectors) features["category_missing"] = int(not self.early_categories) return features def label_status(self): if not self.grades: return "unlabeled" if len(self.grades) > 1: return "conflicting" grade = next(iter(self.grades)) return grade if grade in GRADES else "unsupported" def parse_prefix(response, limit): header = response.readline() if not header: raise ValueError("empty evidence file") fields = next(csv.reader([header.decode("utf-8-sig")])) if len(set(fields)) != len(fields) or not set(COLUMNS).issubset(fields): raise ValueError("unsupported GUIDE evidence schema") indices = tuple(fields.index(name) for name in COLUMNS) digest = hashlib.sha256() incidents = {} rows = 0 first_record_time = None last_record_time = None for _ in range(limit): line = response.readline() if not line: break digest.update(line) rows += 1 values = next(csv.reader([line.decode("utf-8")], strict=True)) if len(values) != len(fields): raise ValueError(f"invalid CSV width in record {rows}") org, case, alert, timestamp, grade, category, detector = (values[index].strip() for index in indices) if not org or not case or not alert: raise ValueError(f"blank evidence identity in record {rows}") try: timestamp = datetime.fromisoformat(timestamp[:-1] + "+00:00" if timestamp.endswith("Z") else timestamp) if timestamp.tzinfo is None or timestamp.utcoffset() is None: raise ValueError("timestamp lacks timezone") except ValueError as exc: raise ValueError(f"invalid timestamp in record {rows}") from exc first_record_time = timestamp if first_record_time is None else min(first_record_time, timestamp) last_record_time = timestamp if last_record_time is None else max(last_record_time, timestamp) identity = org, case if identity not in incidents: incidents[identity] = Incident() incidents[identity].record(alert, timestamp, grade, category, detector) if not incidents: raise ValueError("evidence prefix contains no records") return incidents, { "rows": rows, "prefix_sha256_excluding_header": digest.hexdigest(), "file_header_sha256": hashlib.sha256(header).hexdigest(), "earliest_observed_timestamp": first_record_time.isoformat(), "latest_observed_timestamp": last_record_time.isoformat(), **profile(incidents), } def fetch_prefix(name, limit): url = f"{BASE}/GUIDE_{name}.csv?datasetVersionNumber={VERSION}" with urlopen(url, timeout=35) as response: incidents, summary = parse_prefix(response, limit) return incidents, {"url": url, **summary} def profile(incidents): return { "incidents": len(incidents), "organization_count": len({org for org, _ in incidents}), "verdict_and_eligibility_counts": dict(sorted(Counter( incident.label_status() for incident in incidents.values() ).items())), "earliest_alert_count": dict(sorted(Counter( len(incident.early_alerts) for incident in incidents.values() ).items())), "earliest_category_count": dict(sorted(Counter( len(incident.early_categories) for incident in incidents.values() ).items())), "earliest_detector_count": dict(sorted(Counter( len(incident.early_detectors) for incident in incidents.values() ).items())), } def disjoint_train(train, test): test_orgs = {org for org, _ in test} train_orgs = {org for org, _ in train} group_overlap = train_orgs & test_orgs retained = {key: incident for key, incident in train.items() if key[0] not in test_orgs} return retained, { "overlapping_organizations_excluded_from_train": len(group_overlap), "incidents_excluded_from_train_due_to_organization_overlap": len(train) - len(retained), "organization_overlap_after_exclusion": len({org for org, _ in retained} & test_orgs), } def eligible_rows(incidents): scored_incidents, features, labels = [], [], [] for key in sorted(incidents): incident = incidents[key] grade = incident.label_status() if grade in GRADES: scored_incidents.append(incident) features.append(incident.features()) labels.append(grade) return scored_incidents, features, labels def measure(actual, predicted): matrix = confusion_matrix(actual, predicted, labels=GRADES) by_class = {} for index, grade in enumerate(GRADES): true_positives = int(matrix[index, index]) predicted_count = int(matrix[:, index].sum()) actual_count = int(matrix[index, :].sum()) by_class[grade] = { "precision": true_positives / predicted_count if predicted_count else None, "recall": true_positives / actual_count if actual_count else None, "predicted_count": predicted_count, "actual_count": actual_count, "f1": 2 * true_positives / (predicted_count + actual_count), } return { "macro_f1": float(f1_score(actual, predicted, labels=GRADES, average="macro")), "confusion_matrix": matrix.tolist(), "by_class": by_class, } def evaluate(train_all, test): train, overlap = disjoint_train(train_all, test) train_incidents, train_data, train_y = eligible_rows(train) test_incidents, test_data, test_y = eligible_rows(test) summary = { "partition": { **overlap, "train_retained": profile(train), "labeled_train_incidents": len(train_y), "labeled_test_incidents": len(test_y), }, "class_order": GRADES, } if set(train_y) != set(GRADES) or set(test_y) != set(GRADES): return { **summary, "status": "not_supported", "reason": "all three published verdicts must be represented in both eligible partitions", } vectorizer = DictVectorizer() train_x = vectorizer.fit_transform(train_data) test_x = vectorizer.transform(test_data) feature_names = vectorizer.get_feature_names_out() train_feature_names = set(feature_names) category_columns = [ index for index, name in enumerate(feature_names) if name.startswith("category=") or name == "category_missing" ] test_with_unseen_category = sum( any(name.startswith("category=") and name not in train_feature_names for name in row) for row in test_data ) models = { "majority": DummyClassifier(strategy="most_frequent"), "logistic_regression": make_pipeline( StandardScaler(with_mean=False), LogisticRegression(C=1, max_iter=1_000, random_state=SEED), ), "random_forest": RandomForestClassifier( n_estimators=100, min_samples_leaf=5, random_state=SEED, n_jobs=2, ), } metrics = {} lr_predictions = None for name, model in models.items(): model.fit(train_x, train_y) predicted = model.predict(test_x) metrics[name] = measure(test_y, predicted) if name == "logistic_regression": lr_predictions = predicted category_forest = clone(models["random_forest"]) category_forest.fit(train_x[:, category_columns], train_y) metrics["forest_categories_only"] = measure(test_y, category_forest.predict(test_x[:, category_columns])) return { **summary, "status": "scored", "train_feature_count": len(train_feature_names), "categories_only_feature_count": len(category_columns), "test_incidents_with_unseen_category": test_with_unseen_category, "metrics": metrics, "error_analysis": category_analysis(test_incidents, test_y, lr_predictions, train_incidents, GRADES), } def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--limit", type=int, default=MAX_ROWS_PER_FILE) parser.add_argument("--output", type=Path, default=Path(__file__).with_name("soc-results.json")) args = parser.parse_args() if not 1 <= args.limit <= MAX_ROWS_PER_FILE: parser.error(f"--limit must be between 1 and {MAX_ROWS_PER_FILE}") with ThreadPoolExecutor(max_workers=2) as pool: train_future = pool.submit(fetch_prefix, "Train", args.limit) test_future = pool.submit(fetch_prefix, "Test", args.limit) train, train_profile = train_future.result() test, test_profile = test_future.result() result = { "guide_dataset_version": VERSION, "records_limit_per_csv": args.limit, "environment": { "python": platform.python_version(), "numpy": np.__version__, "scipy": scipy.__version__, "scikit-learn": sklearn.__version__, }, "train_prefix": train_profile, "test_prefix": test_profile, **evaluate(train, test), } args.output.write_text(json.dumps(result, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") print(f"{result['status']}: {args.output}") if __name__ == "__main__": main()