Instructions to use DaveyD347/log-anomaly-context-lr with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Scikit-learn
How to use DaveyD347/log-anomaly-context-lr with Scikit-learn:
# โ ๏ธ Model filename not specified in config.json
- Notebooks
- Google Colab
- Kaggle
Log Anomaly Detector (context-aware logistic regression)
Scores every line of a raw log stream for "is this part of an attack?", and says why. It reads Apache access logs,
sshd/sudo syslog, Linux auditd EXECVE, AWS CloudTrail JSON and BIND query logs, mixed in any order.
Most log classifiers look at one line at a time. That fails on the cases that matter: uname -a is routine when an
admin runs it and post-exploitation discovery when it follows 80 failed SSH logins; GetObject is normal from the
pipeline's usual IP and exfiltration from an IP that key has never used. This model reads the stream top to bottom
and keeps a small memory per IP, account, access key, host and DNS client, so each line is scored with what came
before it, and only what came before it, which makes it usable on a live feed.
It is a logistic regression over 194 line tokens and 40 context features: 6 KB of weights that run in the browser. Try it in the Log Anomaly Detector Space.
Leaderboard
Per-line results. Challenge is a shifted set of 360 sessions (16,324 lines) with attack tools, payloads, usernames, domains and encodings that never appear in training, plus new hard negatives (details below). Test is the dataset's held-out test split (418 sessions, 25,977 lines), which comes from the same templates as training.
| model | context | challenge F1 | challenge AP | challenge precision | challenge recall | challenge FPR | test F1 | test AP | test FPR |
|---|---|---|---|---|---|---|---|---|---|
| Signature rules (16 regexes) | none | 0.522 | 0.655 | 0.849 | 0.377 | 0.078 | 0.740 | 0.795 | 0.012 |
| Isolation Forest, benign-only (unsupervised) | streaming context | 0.867 | 0.908 | 0.835 | 0.902 | 0.207 | 0.850 | 0.865 | 0.261 |
| TF-IDF char 3-5-grams + LR | one line | 0.673 | 0.779 | 0.856 | 0.555 | 0.108 | 0.998 | 1.000 | 0.000 |
| Line tokens + LR (ablation, no context) | one line | 0.453 | 0.708 | 0.882 | 0.305 | 0.047 | 0.970 | 0.991 | 0.000 |
| Gradient-boosted trees, same features as ours | streaming context | 0.821 | 0.963 | 0.972 | 0.710 | 0.024 | 1.000 | 1.000 | 0.001 |
| Ours: context-aware LR | streaming context | 0.926 | 0.991 | 0.930 | 0.923 | 0.081 | 1.000 | 1.000 | 0.001 |
AP is average precision (area under the precision-recall curve), FPR the share of normal lines flagged. Supervised models use a 0.5 threshold; the Isolation Forest uses the threshold that maximizes validation F1.
What the table says:
- The in-distribution test split is saturated. A character n-gram classifier that sees one line at a time scores 0.998 F1 there, because the test lines come from the training templates. It is a sanity check, not a benchmark.
- On unseen variants, context is what generalizes. Both one-line models collapse (0.45-0.67 F1). They learned
sqlmap,Invalid user adminandpython-requests, and the challenge attacks use a browser user agent, unseen usernames and new endpoints. The models with streaming context stay at 0.82-0.93. - Gradient boosting is more precise but brittle. On the same features it keeps false positives at 2.4% but misses 29% of attack lines, because its splits latch onto exact token values. The linear model degrades more gracefully.
- Unsupervised is a fair baseline, not a winner. Isolation Forest, fit on benign sessions only, catches 90% of attack lines but flags 21-26% of normal ones, which would bury an analyst.
Session level (a session is flagged if any line is): ours detects 100% of attack sessions in both sets, with false
alarms on 5.5% of benign test sessions (an admin's uname -a that looks like post-exploitation discovery) and 25%
of benign challenge sessions (all of them the "health checks + typos" web scenario, described below).
Where it struggles (challenge set)
| scenario | line accuracy | notes |
|---|---|---|
stolen AWS key, normal aws-cli/2 user agent |
100% | caught by "this key, new IP and new user agent" |
| credential stuffing with browser user agents on a new endpoint | 99.9% | many login posts from many IPs |
| hex-encoded DNS tunneling over A/AAAA | 99.7% | label length, entropy, unique subdomains per domain |
| slow SSH password spray with unseen usernames | 90.8% | first few attempts and the id/lscpu discovery commands are missed |
| web scanning + SQLi + JSP/ASPX shell with a browser user agent | 64.1% | only 34% of probes and 58% of SQLi requests caught |
benign: uptime checker using curl, users mistyping passwords, SEO crawler 404s |
72.8% | curl user agent and failed logins trigger false positives |
benign: password-auth admins, grep /etc/passwd, wget from a known repo |
100% | |
| benign: onboarding a new hire (CreateUser, AttachUserPolicy, CreateAccessKey) | 100% | |
| benign: telemetry agent resolving long hashed CDN hostnames, DKIM TXT lookups | 100% |
Per ATT&CK technique on the challenge set, recall is weakest for active scanning (T1595.002, 34%), web shells (T1505.003, 43%), SQL injection (T1190, 58%) and discovery commands (T1082 65%, T1033 0%).
Quick start
from huggingface_hub import hf_hub_download
from skops.io import load, get_untrusted_types
import os, sys
repo = "DaveyD347/log-anomaly-context-lr"
paths = [hf_hub_download(repo, f) for f in ["model.skops", "src/features.py", "src/common.py", "src/train.py"]]
sys.path.insert(0, os.path.dirname(paths[1]))
from features import featurize_stream
from train import ours_matrix
m = load(paths[0], trusted=get_untrusted_types(file=paths[0]))
logs = """Feb 14 08:14:42 jump-03 sshd[10398]: Failed password for git from 203.0.113.115 port 50495 ssh2
Feb 14 08:14:45 jump-03 sshd[30485]: Invalid user guest from 203.0.113.115 port 44815
Feb 14 08:14:48 jump-03 sshd[21110]: Invalid user oracle from 203.0.113.115 port 41405
Feb 14 08:14:52 jump-03 sshd[21111]: Failed password for git from 203.0.113.115 port 41466 ssh2
Feb 14 08:15:30 jump-03 sshd[21112]: Accepted password for git from 203.0.113.115 port 41501 ssh2
type=EXECVE msg=audit(1739521151.919:816324): argc=2 a0="uname" a1="-a" uid=1001 auid=1001 exe="/usr/bin/uname" host=jump-03""".splitlines()
feats = featurize_stream(logs) # [(parsed, tokens, numeric), ...] in stream order
X = ours_matrix([t for _, t, _ in feats], [x for _, _, x in feats], m["vocab"], m["token_scale"])
for line, p in zip(logs, m["clf"].predict_proba(X)[:, 1]):
print(f"{p:6.1%} {'ANOMALY' if p >= m['threshold'] else ' '} {line[:90]}")
The final uname -a scores 72% here because it follows a password login from an IP with failed attempts. The same
line after an admin's key-based login from an internal address scores 0.3%.
Check what get_untrusted_types returns before loading any .skops file you didn't create. Feed one stream per
featurize_stream call (for example one host, or one time window); state is kept within a call.
For JavaScript, model.json holds the same weights, and js/features.js plus js/model.js reproduce the pipeline.
A parity test checks JS and Python agree on all 25,977 test lines (max probability difference 4e-7, no label
differences).
How it works
Parsing. Each line is recognised by format and parsed into fields (IP, method, path, query, status, user agent;
sshd event kind, user, IP; argv and uid; CloudTrail event, access key, user agent, error; DNS client, name, type).
Lines in other formats are scored as unknown.
Line tokens (194, weighted x0.3). Categorical facts about the line itself: src=web, st=404, ua=sqlmap,
seg=wp-login.php, ssh=failed_password, ssh_generic_user, exe=crontab, ev=AttachUserPolicy, err=AccessDenied,
qt=TXT. They are down-weighted because they are surface strings that attackers change freely.
Context features (40). Computed from the stream so far, scaled to [0, 1]:
| source | features |
|---|---|
| web | prior requests, 404s, 4xx share, failed logins and SQLi-like requests from this IP; scanner/tool user agent seen from this IP; login posts, distinct login IPs, login failure share and dominant user-agent share across the stream; SQL syntax in this query; large response to a parameterised request |
| ssh | prior failures and distinct usernames from this IP; successful login after failures; account that logged in suspiciously; failed logins across the stream |
| exec | command after a suspicious SSH login on this host; command after web-shell requests; download from a raw IP; credential file access; hidden file in a temp dir; reverse-shell pattern; crontab write |
| cloud | access key used from a new IP / with a new user agent (compared to its first use); prior events for this key and this IP; AdministratorAccess in the request; denied call; external IP; prior denials for this key from this IP |
| dns | longest label, subdomain entropy, number of labels, digit share; prior queries from this client to this domain; unique subdomains of this domain; TXT/NULL/CNAME query |
| all | external (non-RFC 1918) source IP |
The largest weights: long DNS label (+13.6), command after web-shell activity (+11.5), external source IP (+7.4), command after a suspicious SSH login (+6.9), many distinct login IPs (+6.8), access key with a new user agent (+6.3).
Training
- Data: the
eventsconfig ofDaveyD347/sanitized-incident-logs, train split (3,163 sessions, 193,521 lines), each session fed as one stream inseqorder. Validation (419 sessions) is used only to set the Isolation Forest baseline's threshold; test and challenge are used only for the table above. LogisticRegression(C=1.0), threshold 0.5. Training all six models takes about 3 minutes on a 4-core CPU, with no GPU.- Development note, for transparency. The challenge set was written before the model was finalised, and two
decisions were made after looking at challenge results: the 0.3 weight on line tokens (versus 1.0; validation F1
is 0.999 either way; challenge F1 was 0.918 at 1.0 and 0.924 at 0.3), and dropping a DNS top-level-domain token, because the
dataset puts every attacker domain under the reserved
.testTLD and the model was learning that artifact. Treat the challenge numbers as somewhat optimistic for that reason.
The challenge set
data/challenge.parquet (generated by src/challenge_set.py, seed 9001, 40 sessions per scenario) uses the
dataset's generator and log formats, with every scenario's surface changed:
| attack variant | what changed versus training |
|---|---|
ch_web_exploit |
probes for unseen paths (/.svn/entries, /manager/html, /jenkins/script), a browser or Nuclei user agent, error- and time-based SQLi in new parameters, a shell uploaded with PUT as .jsp/.aspx and driven with exec=, a Python reverse shell |
ch_ssh_spray |
slow spray (5-40 s apart) over unseen usernames, Failed password for invalid user lines, a crypto miner, persistence through authorized_keys |
ch_cred_stuffing |
/account/signin with 403/302 responses and real browser user agents only |
ch_cloud_key |
normal aws-cli/2 user agent, GetAccountAuthorizationDetails/ListSecrets discovery, PutUserPolicy escalation, GetSecretValue theft, DeleteFlowLogs |
ch_dns_tunnel |
hex labels over A/AAAA queries to new domains, lower rate |
| hard negative | why it is hard |
|---|---|
ch_benign_web |
an uptime checker with a curl user agent, a user failing to sign in 2-5 times, an SEO crawler hitting 404s |
ch_benign_ssh |
admins logging in with passwords, reading /etc/passwd, wget-ing a package, crontab -l |
ch_benign_cloud |
an admin creating a user, attaching a policy and creating an access key |
ch_benign_dns |
a telemetry agent resolving many long hashed CDN hostnames, DKIM/DMARC TXT lookups |
It adds three techniques that training never shows (T1098.004, T1496, T1555.006).
Intended use
- Teaching and demos: show how context changes the meaning of a log line, and why per-line keyword alerts miss attacks and drown analysts at the same time.
- A baseline for log anomaly detection research on the incident-logs dataset; the challenge set and all baselines are
reproducible from
src/. - A cheap triage signal to rank lines for review, next to real detection tooling.
Not a SIEM or EDR replacement.
Limitations and risks
- Synthetic training data. Five log formats, one host or account per stream, a handful of attack patterns. Real logs have far more variety, other formats (Windows events, Kubernetes, firewalls) and much lower attack base rates (about half the training lines are malicious). Expect many more false positives on real traffic without retraining on your own baseline.
- "External IP" carries a lot of weight. In the training data, SSH from the internet is always an attack. That is a reasonable prior but not a rule; an exposed bastion with legitimate remote users will alert.
- Context needs history. The first probes of a slow attacker, and attackers who blend into normal browsing, score low until the pattern builds up. Streams that start mid-attack lose the evidence that came before.
- Behavioural features are public. Someone who reads this card can rotate IPs and user agents per request, stay under the rate features, or reuse the key's usual IP.
- Probabilities are only roughly calibrated; use them to rank, not as exact risk.
Files
| file | what |
|---|---|
model.skops |
token vocabulary, logistic regression, token weight and threshold |
model.json |
the same weights for JavaScript (format: stream-logreg-v1, token weight folded in) |
config.json |
hyper-parameters and training sizes |
eval/metrics.json, eval/leaderboard.md, eval/confusion_matrix.png |
full results, including per-scenario and per-technique numbers for every model |
data/challenge.parquet |
the shifted challenge set (same columns as the dataset's events config, plus session_label) |
src/ |
parsing and features, baselines, training, evaluation, challenge generator, Space export, publish script |
js/ |
browser port of the featurizer and scorer |
src/incident_generator.py is a copy of the dataset's generator (CC BY 4.0), used by the challenge set.
Reproduce:
pip install -r requirements.txt
python src/challenge_set.py --out data/challenge.parquet
python src/train.py --out outputs # downloads the dataset from the Hub
python src/evaluate.py --models outputs --challenge data/challenge.parquet --out eval
License
Apache 2.0 for the model and code. The training data is CC BY 4.0.
Citation
@misc{log_anomaly_context_lr_2026,
title = {Context-aware log anomaly detection on synthetic incident telemetry},
author = {DaveyD347},
year = {2026},
howpublished = {\url{https://huggingface.co/DaveyD347/log-anomaly-context-lr}}
}
- Downloads last month
- -
Dataset used to train DaveyD347/log-anomaly-context-lr
Spaces using DaveyD347/log-anomaly-context-lr 2
Evaluation results
- f1 on Shifted challenge set (unseen attack variants and hard negatives)self-reported0.926
- average_precision on Shifted challenge set (unseen attack variants and hard negatives)self-reported0.991
- precision on Shifted challenge set (unseen attack variants and hard negatives)self-reported0.930
- recall on Shifted challenge set (unseen attack variants and hard negatives)self-reported0.923
- f1 on Sanitized Incident Logs (events, test split)test set self-reported1.000
- average_precision on Sanitized Incident Logs (events, test split)test set self-reported1.000
- precision on Sanitized Incident Logs (events, test split)test set self-reported0.999
- recall on Sanitized Incident Logs (events, test split)test set self-reported1.000
