Lesson 02 · 40 minutes
Triage alerts with a model and measure what auto-closing costs
- Train a classifier on four weeks of labelled alerts and score a new week
- Measure precision and recall for the real-incident class
- Choose a threshold from the number of incidents that auto-closing would miss
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
The manager from lesson 1 has agreed to a trial. The idea: a model gives each alert a score, the team reads the high scores first, and alerts with a very low score are closed with no reading. Your lead asks: "How many real incidents do we lose if the model closes alerts for us, and which threshold is safe?" You have four earlier weeks of labelled alerts for training, and the fixed week 5 that the model has never seen, for the test.
Recall
Lesson 1: with 80 reads a day, how many of the 59 incidents did the best simple rule reach?
46, with the critical assets first. Arrival order reached 32. A model must beat 46 to be worth its cost.
"How AI works", lesson 6: what do precision and recall tell you about a detector?
Precision is the share of alerts that are real (TP / (TP + FP)). Recall is the share of real incidents that the detector finds (TP / (TP + FN)). Precision protects the analyst from noise, and recall protects the company from missed incidents.
The idea
A classifier turns each alert into numbers (the features, lesson 2 of "How AI works"), and returns for each alert a score between 0 and 1: the higher it is, the more the alert looks like past incidents. The score ranks alerts. It is not a calibrated probability: a score of 0.9 does not mean that 9 in 10 such alerts are real. In this course a "model" is a classical machine-learning model that learns from labelled rows. Only lesson 3 uses a language model, because writing text is the job it is made for. Lesson 9 shows how to keep either kind from acting by itself. The model does not decide. A threshold (a cut-off that you choose) turns the score into an action: below it the alert is closed, at or above it a person reads it.
- Alert → Features: rule, severity, hour, count
- Features → Model: trained on four past weeks
- Model → Score: 0 to 1, a ranking
- Score → Threshold: you choose the cut-off
- Threshold → Person reads: at or above: a person reads
- Threshold → Closed unread: below the cut-off
Two kinds of mistake have different costs. A missed incident is a real alert below the threshold. It is closed and nobody reads it. A false alarm is a harmless alert above the threshold, and it costs six minutes of an analyst. Auto-closing is the case where the first mistake becomes silent, so you count it first. The usual cut-off of 0.5 is a default of the library, not a decision about your risk.
Worked example
1. Save the model code
Save triage.py. features(a) makes one row of numbers from one alert: eight 0-or-1 columns for the rule name (only one is 1) and then the numeric fields. GradientBoostingClassifier builds many small decision trees, one after the other, and each tree corrects the mistakes of the trees before it. random_state=0 fixes its random choices, so you get the same model every time. fit(X, y) trains it on the rows X with the true labels y. predict_proba returns two columns, the score of class 0 and the score of class 1, and [:, 1] keeps the second column: the score of a real incident. round(float(p), 4) makes a plain number with four decimals.
The model trains on weeks 1 to 4 (4,000 alerts). Week 5 is not in them, so it is a fair test (lesson 3 of "How AI works").
triage.py
"""triage.py: features, training and scoring of alerts."""
from sklearn.ensemble import GradientBoostingClassifier
from gen import RULES, alerts
HISTORY = [1, 2, 3, 4]
def features(a):
"""One row of numbers for one alert. The rule becomes one column of 0 or 1 for each rule name."""
rule = [int(a["rule"] == r) for r in RULES]
return rule + [a["severity"], a["hour"], a["count"], a["mb_out"], a["asset"], a["admin"], a["ext_src"], a["new_source"]]
def train(weeks=HISTORY):
rows = [a for w in weeks for a in alerts(w)]
model = GradientBoostingClassifier(random_state=0)
return model.fit([features(a) for a in rows], [a["label"] for a in rows])
def scores(model, rows):
"""The score of a real incident for each alert, between 0 and 1. It ranks alerts and is not a calibrated probability."""
return [round(float(p), 4) for p in model.predict_proba([features(a) for a in rows])[:, 1]]2. Score some alerts
python3 -c "
from gen import alerts
from triage import train, scores
week = alerts(5)
rows = sorted(zip(scores(train(), week), week), key=lambda x: -x[0])
for s, a in rows[:3] + rows[500:502] + rows[-2:]:
print(a['id'], a['rule'].ljust(18), 'score', s, 'real' if a['label'] else '')
"W5-0335 new-admin-account score 0.998 real
W5-0705 impossible-travel score 0.998 real
W5-0176 large-upload score 0.9972 real
W5-0864 dns-odd-domain score 0.0088
W5-0937 dns-odd-domain score 0.0088
W5-0672 port-scan score 0.0007
W5-0570 port-scan score 0.0005 sorted with key=lambda x: -x[0] puts the highest score first. The output shows the three highest scores, two from the middle and the two lowest. The top alerts have scores near 1, and most of the week is near 0. The scores make a ranking. The next steps measure how good it is.
3. Measure and print the cost table
Save threshold.py. choose is used in step 6. precision_score and recall_score come from scikit-learn and take the true labels and the predicted labels. zip(a, b) walks two lists together, and dict(zip(keys, values)) makes a dictionary from them. In an f-string, {x:>9} writes x right-aligned in 9 characters, and {x:>16.0%} writes a share as a whole percent. The table closes every alert below each threshold and counts the real incidents among them.
threshold.py
"""threshold.py: measure the triage model on the fixed week, and show what auto-closing costs."""
from sklearn.metrics import precision_score, recall_score
from gen import alerts
from triage import scores, train
from workload import reached
THRESHOLDS = [0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.5]
def table(week, score):
"""For each threshold: close every alert below it, and count what that costs."""
real = sum(a["label"] for a in week)
print(f"{'threshold':>9}{'auto-closed':>13}{'missed':>8}{'to read':>9}{'workload saved':>16}")
for t in THRESHOLDS:
closed = [a for a in week if score[a["id"]] < t]
missed = sum(a["label"] for a in closed)
print(f"{t:>9}{len(closed):>13}{missed:>8}{len(week) - len(closed):>9}{len(closed) / len(week):>16.0%}")
print("real incidents in the week:", real)
def choose(week, score, share=0.10):
"""The largest threshold that auto-closes at most `share` of the real incidents of this week."""
limit = share * sum(a["label"] for a in week)
return max((t for t in THRESHOLDS if sum(a["label"] for a in week if score[a["id"]] < t) <= limit), default=0)
if __name__ == "__main__":
model, week = train(), alerts(5)
score = dict(zip((a["id"] for a in week), scores(model, week)))
y = [a["label"] for a in week]
pred = [int(score[a["id"]] >= 0.5) for a in week]
print("at the usual cut-off 0.5: precision", round(precision_score(y, pred), 2), " recall", round(recall_score(y, pred), 2))
print()
table(week, score)
print()
print("incidents reached with a capacity of 80 a day:", len(reached(week, lambda a: -score[a["id"]])), "(arrival order: 32)")
older, week4 = train([1, 2, 3]), alerts(4)
chosen = choose(week4, dict(zip((a["id"] for a in week4), scores(older, week4))))
missed = sum(a["label"] for a in week if score[a["id"]] < chosen)
print(f"threshold chosen on week 4 (model of weeks 1 to 3): {chosen}; on week 5 it misses {missed} of 59")python3 threshold.pyat the usual cut-off 0.5: precision 0.93 recall 0.71
threshold auto-closed missed to read workload saved
0.01 546 4 454 55%
0.02 746 7 254 75%
0.05 885 11 115 88%
0.1 934 15 66 93%
0.2 945 15 55 94%
0.3 948 16 52 95%
0.5 955 17 45 96%
real incidents in the week: 59
incidents reached with a capacity of 80 a day: 56 (arrival order: 32)
threshold chosen on week 4 (model of weeks 1 to 3): 0.02; on week 5 it misses 7 of 594. Read the table
At the usual cut-off of 0.5, precision is 0.93 and recall is 0.71. Of the alerts that the model escalates, 93 in 100 are real. But it finds only 71 in 100 of the real incidents. If you close everything below 0.5, you save 96 percent of the reading and you lose 17 of 59 incidents (29 percent), in silence.
Go down the column "missed". At 0.1 you miss 15, at 0.05 you miss 11, at 0.02 you miss 7, and at 0.01 you miss 4. Each step down in the threshold gives you more to read: 454 alerts at 0.01 against 45 at 0.5. The model cannot remove the trade, it only shows its price.
Notice that the missed incidents are not random. About one real alert in ten is "quiet": it looks like a harmless alert in every field. This model, with these fields, cannot score such an alert high, and no threshold that the table lists will find it. A model with other fields might. This is the limit of a classifier that learns from the data you have.
5. Use the score to order the reading
The last line is the better use of the model. The team still reads 80 alerts a day, but it reads the highest scores first. It reaches 56 of 59 incidents, against 32 in arrival order and 46 with the best simple rule of lesson 1. The model beats the baseline, and nothing was closed with no reading.
6. Choose a threshold on a week that you do not report
A threshold is a decision about risk, so state it as a rule: "Auto-closing may miss at most one real incident in ten." If you pick the threshold from the week 5 table and then report week 5, the report is too good, because you chose the value that looks best on the data that you report. Choose on another week. choose takes a week and its scores and returns the largest threshold of the list that auto-closes no more than that share of the incidents of the week. The last line of the output uses it on week 4, with a model that trained on weeks 1 to 3, and then reports week 5. The threshold is 0.02. On week 5 it misses 7 of 59 incidents, which is 12 percent and more than the rule allows. The week 5 table alone would have given 0.01 and 4 missed, a result that is too good. Report 7, write the rule, the threshold and the date in your notes, and revisit them when the data changes (lesson 13).
Your turn
The lead doubts that four weeks are needed. Train the model on weeks 3 and 4 only (train([3, 4])), and measure it on week 5 as before, with the same two tools: the 0.5 cut-off and the table. You write the code. Do not change the data or the model settings.
Last, decide in one sentence whether the shorter history is a safe saving.
Check yourself
The model has recall 0.71 at 0.5 and precision 0.93. The vendor says "93 percent of its alerts are real". Which number do you report to the manager?
Both, and the count of missed incidents: 17 of 59. Precision hides the misses. A manager who hears "93 percent" will think that 7 in 100 incidents are lost, when 29 in 100 are.
Why do you score week 5 with a model that never saw week 5?
A model scores its own training data too well. Week 5 stands for the next week, which nobody has seen. Only a fair test tells you what auto-closing will cost.
Why do you choose the threshold from the table and not at 0.5?
0.5 is a default that says nothing about your costs. The table shows what each threshold costs in missed incidents and in reading, and you can match it to a rule about risk that someone can sign.
Ordering by score reached 56 incidents. Why is that safer than auto-closing?
Nothing is closed without a read. The model only changes the order. An alert with a low score is read later, or not at all if time ends, but the team chose the time limit, not the model.
Field notes
- The labels are from the past. A new attack that looks like nothing in the four weeks gets a low score. Lesson 15 shows a week where this happens. Retrain on a schedule, and measure each new week before you trust the old threshold.
- One week has 59 incidents. One more miss moves recall by about 1.7 points. Do not choose between thresholds that differ by one or two incidents. Use several weeks to measure the rate, as the course "How AI works" taught.
- A gradient-boosting score ranks, and it is not calibrated. If you need a probability, for example to compute an expected loss, calibrate it on a separate week (
CalibratedClassifierCVin scikit-learn). Several alerts can also share a score near 0, so decide how the team orders them. - Log the score with every automatic decision. An auditor, or you in three months, must be able to ask "why was this alert closed?" and read the score and the threshold of the day (lesson 13).
- A model can use fields that carry bias, for example a user name or a host that is always handled by one team. Review the features: each one should be something that an analyst would call evidence.