Machine Learning for CybersecuritySource on GitHub

Unit 2 · Exercises

Unit 2 exercises

These exercises practice the calculations of Lesson 2.3, the encodings of Lesson 2.1 and the splitting decisions of Lesson 2.2. Work each one before opening its solution.

Exercise 1. AUC and average precision by hand

A detector scores ten connections. The table below lists them sorted by decreasing score, with their labels.

Rank Score Label
1 0.90 A
2 0.80 A
3 0.70 N
4 0.60 A
5 0.50 N
6 0.40 N
7 0.30 N
8 0.20 A
9 0.10 N
10 0.05 N

A is an attack and N a normal connection.

(a) Compute the AUC with the pair-counting formula of Lesson 2.3 by counting correctly ordered pairs. (b) Compute the average precision. (c) What would AP be for a detector that ranks these ten records at random, approximately? (d) An analyst can investigate three alerts. Which threshold meets that budget, and what are the recall and precision?

Show the answer

(a) There are 4 attacks and 6 normal records, so 24 pairs. The attack at rank 1 is above all 6 normal records, the one at rank 2 also above 6, the one at rank 4 above 5 (ranks 5, 6, 7, 9, 10), and the one at rank 8 above 2 (ranks 9 and 10). The count is \(6 + 6 + 5 + 2 = 19\), so \(\mathrm{AUC} = 19/24 \approx 0.792\).

(b) The precision at the rank of each attack is \(1/1\), \(2/2\), \(3/4\) and \(4/8\). AP is their mean, \((1 + 1 + 0.75 + 0.5)/4\), which equals 0.8125. (Joining the points of the precision-recall curve with straight lines from \((0, 1)\) and applying the trapezoidal rule gives about 0.793. The course uses the step-wise definition because, as Lesson 2.3 explains, straight-line interpolation between points in precision-recall space is incorrect.)

(c) A random ranking has expected precision equal to the base rate, \(4/10 = 0.4\), at every cutoff, and for a large set of records its AP is close to that value. With only ten records the expected AP is higher, about 0.53 (the mean over all 210 equally likely placements of the four attacks), because AP evaluates precision at the rank of each attack, a cutoff that always includes that attack. The value approaches the base rate as the number of records grows.

(d) A threshold of 0.70 flags ranks 1 to 3. Two of the three alerts are attacks, so precision is \(2/3\) and recall is \(2/4 = 0.5\).

Exercise 2. Undoing balanced class weights

A logistic regression was trained with class_weight="balanced", so it behaves as if half of all records were attacks. In deployment the base rate is \(b' = 0.002\).

(a) Let \(p\) be the model's probability of attack for a record, assumed correct for a population with base rate \(b\), and \(p'\) the probability for the same record in a population with base rate \(b'\). Starting from Bayes' rule, show that

\[ \frac{p'}{1-p'} = \frac{p}{1-p}\cdot\frac{b'/(1-b')}{b/(1-b)}, \label{eq:ex-odds} \]

assuming the class-conditional distributions of the features do not change.

(b) Convert the outputs 0.5, 0.9, 0.99 and 0.999 of the balanced model to deployment probabilities. (c) Which balanced output corresponds to a deployment probability of 0.1?

Show the answer

(a) By Bayes' rule, \(p = P(x \mid A)\,b / P(x)\) and \(1 - p = P(x \mid N)(1-b)/P(x)\), so the odds are \(p/(1-p) = \Lambda(x)\, b/(1-b)\) with the likelihood ratio \(\Lambda(x) = P(x \mid A)/P(x \mid N)\). The same holds at \(b'\) with the same \(\Lambda(x)\), because the class-conditional distributions are unchanged. Dividing one expression by the other eliminates \(\Lambda(x)\) and gives \eqref{eq:ex-odds}. It is the odds form of Theorem 2 of Elkan (2001), the base-rate correction of predicted probabilities in Lesson 2.3.

(b) With \(b = 0.5\) the denominator \(b/(1-b)\) is 1 and \(b'/(1-b') = 0.002/0.998\). An output of 0.5 has odds 1, giving \(p' = 0.002\). An output of 0.9 has odds 9, giving odds \(0.01804\) and \(p' \approx 0.0177\). An output of 0.99 gives \(p' \approx 0.166\), and 0.999 gives \(p' \approx 0.667\).

(c) Deployment odds of \(0.1/0.9 = 0.1111\) require balanced odds of \(0.1111 \times 0.998/0.002\), which is 55.4, so \(p = 55.4/56.4 \approx 0.982\).

Exercise 3. Choosing an operating point from a budget

A network carries about 1,000,000 normal connections and 20 attack connections a day. Analysts can investigate 50 alerts a day. Three thresholds of a detector have the rates in the table below, measured on validation days.

Threshold False positive rate True positive rate
\(t_1\) \(10^{-4}\) 0.90
\(t_2\) \(3 \times 10^{-5}\) 0.75
\(t_3\) \(10^{-5}\) 0.50

(a) For each threshold, compute the expected alerts per day, the true alerts among them and the precision. (b) Which threshold would you deploy, and why? (c) Name one reason the daily alert count in deployment may differ from your answer to (a).

Show the answer

(a) At \(t_1\) there are 100 false and 18 true alerts, 118 in all, and precision is \(18/118 \approx 0.153\). At \(t_2\) there are 30 false and 15 true alerts, 45 in all, and precision is \(15/45 \approx 0.333\). At \(t_3\) there are 10 false and 10 true alerts, 20 in all, and precision is 0.5.

(b) \(t_2\). It is the threshold with the highest recall whose expected volume fits within the budget of 50. \(t_1\) would more than double the analysts' workload, so in practice many of its alerts would not be investigated at all. \(t_3\) leaves budget unused and misses a third of the attacks that \(t_2\) would catch (5 of 15 a day).

(c) Rates measured on validation days carry sampling error (at a false positive rate of \(3 \times 10^{-5}\), the estimate rests on a few dozen false alerts), and traffic changes. A software update, a new scanner or a new attack family can shift the score distribution, and a burst of attacks adds true alerts, as the denial-of-service traffic on day 11 does for the fixed threshold of Lab 2. The alert count has to be monitored.

Exercise 4. Target encoding with cross-fitting

Ten training connections have the user agent and label given in the table below, with the cross-fitting fold of each row.

Row User agent Label Fold
1 curl 1 1
2 curl 1 2
3 curl 0 1
4 curl 1 2
5 firefox 0 1
6 firefox 0 2
7 firefox 1 1
8 firefox 0 2
9 python 1 1
10 python 0 2

Use the smoothed target encoding of Lesson 2.1 with \(m = 1\). In it, \(s_c\) is the number of attacks among the \(n_c\) rows of category \(c\), and \(\bar y\) is the attack share of the rows used to compute the encoding.

(a) Compute the encoding of each user agent from all ten rows. This is what transform would apply to new data. (b) Compute the cross-fitted encoding of the rows in fold 1 (statistics from fold 2) and of the rows in fold 2 (statistics from fold 1). (c) Compare the encoding of row 7 under (a) and (b). Why is (b) the right value to train on?

Show the answer

(a) \(\bar y = 5/10 = 0.5\). For curl, \(s_c = 3\) and \(n_c = 4\), so \((3 + 0.5)/5 = 0.7\). For firefox, \((1 + 0.5)/5 = 0.3\). For python, \((1 + 0.5)/3 = 0.5\).

(b) Rows in fold 1 use fold 2 (rows 2, 4, 6, 8, 10), where \(\bar y = 2/5 = 0.4\). Curl has \(s_c = 2\), \(n_c = 2\), giving \((2 + 0.4)/3 = 0.8\). Firefox has \(s_c = 0\), \(n_c = 2\), giving \(0.4/3 = 0.133\). Python has \(s_c = 0\), \(n_c = 1\), giving \(0.4/2 = 0.2\). Rows in fold 2 use fold 1 (rows 1, 3, 5, 7, 9), where \(\bar y = 3/5 = 0.6\). Curl has \(s_c = 1\), \(n_c = 2\), giving \(1.6/3 = 0.533\). Firefox has \(s_c = 1\), \(n_c = 2\), giving \(0.533\). Python has \(s_c = 1\), \(n_c = 1\), giving \(1.6/2 = 0.8\).

(Here the prior \(\bar y\) is computed from the rows used for the encoding. Using the overall attack share of 0.5 instead changes the numbers slightly but not the conclusion.)

(c) Row 7 is a firefox attack in fold 1. Under (a) its encoding, 0.3, includes its own label; under (b) it is 0.133, computed only from rows 6 and 8, both normal, and the prior of fold 2. In training, the encoding must look the way it will look on new data, where the record's own label is unknown. Encoding from statistics that include the row's own label makes the attacks of each category look slightly more like attacks than they will at prediction time, and with small categories that difference is large enough for a model to exploit.

Exercise 5. Grouped and forward-chaining cross-validation on the course data

Add a cell at the end of Lab 2 that estimates the AP of the gradient boosting detector (a) with five-fold cross-validation grouped by src_host and stratified by label, and (b) with forward-chaining folds that train on all days before day \(d\) and test on day \(d\), for \(d = 8, \dots, 13\). Report the score of each fold and explain what you see.

Show the answer

One solution, which uses dedup and make_model from the lab,

from sklearn.model_selection import (StratifiedGroupKFold,
                                     cross_val_score)

cv = StratifiedGroupKFold(n_splits=5, shuffle=True, random_state=0)
scores = cross_val_score(make_model("hgb"), dedup, dedup["label"],
                         groups=dedup["src_host"], cv=cv,
                         scoring="average_precision")
print("grouped 5-fold AP per fold:", scores.round(3),
      "mean", scores.mean().round(3))

by_day = dedup.sort_values("timestamp").reset_index(drop=True)
folds = [(np.flatnonzero(by_day["day"] < d),
          np.flatnonzero(by_day["day"] == d)) for d in range(8, 14)]
scores_t = cross_val_score(make_model("hgb"), by_day, by_day["label"],
                           cv=folds, scoring="average_precision")
print("forward-chaining AP per test day 8 to 13:", scores_t.round(3))

cross_val_score accepts an explicit list of (training indices, test indices) pairs as cv, which makes custom temporal folds easy. In the grouped cross-validation, one fold scores far below the others. That is the fold whose test hosts include A010, the IT scanner, for the reason explained in Lesson 2.2; the mean over folds hides the problem, and the per-fold scores reveal it. In the forward-chaining folds, the score drops on day 10, when the beacon family first appears, and recovers on days 11 to 13, because from then on day 10 is part of the training data. The temporal split of the lab, which trains only on days 0 to 9, corresponds to a detector that is never retrained; the forward-chaining scores correspond to one retrained daily with labels from the previous day. That assumption needs analysts to label yesterday's traffic, which is itself an operational cost.

Exercise 6. Designing the evaluation of a phishing detector

You are asked to evaluate a model that classifies incoming e-mails as phishing. The dataset contains 400,000 e-mails received by one organization between January 2024 and June 2025, labeled by the security team. Available fields include the sender address and domain, the subject and body, attachments, the receiving user, the time of receipt, the gateway's spam score at delivery, the number of users who reported the message, and whether the security team quarantined it.

(a) Which fields would you exclude as leakage, and why? (b) How would you split the data? (c) Which metric and which operating point would you report?

Show the answer

(a) The number of user reports and the quarantine flag both accumulate after delivery and partly reflect the label, so they are target leakage. The gateway spam score at delivery is legitimate if it is the score recorded at the time of receipt; it would not be if it was recomputed later with updated rules. Any feature computed over a window (for example, how many messages a sender sent that week) must use only messages received before the one being classified.

(b) Split by time, for example training on January 2024 to December 2024, using January to March 2025 for validation and threshold selection, and testing on April to June 2025. In addition, group by campaign or by sender domain so that near-identical messages of one campaign do not appear on both sides; a temporal split alone does not prevent this when a campaign spans the boundary. Remove exact duplicates first, since the same message is often delivered to many users.

(c) Report the precision-recall curve and average precision on the test months, together with the base rate of phishing in those months, and the ROC curve for comparison with other datasets. Choose the threshold on the validation months from the team's alert budget (or from the costs of a missed phish and of a quarantined legitimate message), and report the recall, precision and daily alert volume at that fixed threshold on the test months.

References

  1. Elkan, C. (2001). The foundations of cost-sensitive learning. Proceedings of the Seventeenth International Joint Conference on Artificial Intelligence (IJCAI), 973-978. https://www.ijcai.org/Proceedings/01/IJCAI-2001-k.pdf