Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Scenario test · 60 minutes

Review a login-attack classifier before it goes live

After this lesson you can
  • Find the flaws in a model that reports a high accuracy
  • Measure a detector on held-out data against a baseline
  • Write a one-page model review with a recommendation
Lab files of this lesson (35)

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

A colleague trained a classifier that flags suspicious login events. It reads five numbers for each login and says "attack" or "normal". The colleague reports "98.5 percent accuracy" and wants to put it live on Monday. Your lead asks you to review it first. "Tell me whether I can trust that number, what the detector really does, and what I should tell the colleague."

You have two files. The first, make_logins.py, makes the data: 20,000 login events, a few of them attacks. It uses a fixed seed, so everyone gets the same file. Create it in ~/krlab/how-ai-works with your editor, and run it with python make_logins.py. It writes logins.csv. The columns are: failed logins in the last hour, distinct source addresses, new device (0 or 1), night time (0 or 1), distance in km from the last login, and the label attack (0 or 1).

The columns of logins.csv
failed_loginsfailed logins in the last hourdistinct_ipsdistinct source addressesnew_device0 or 1night0 or 1km_from_lastdistance (km) from last loginattackthe label: 0 or 1failed_loginsfailed logins in the last hourdistinct_ipsdistinct source addressesnew_device0 or 1night0 or 1km_from_lastdistance (km) from last loginattackthe label: 0 or 1

make_logins.py

import numpy as np

rng = np.random.default_rng(2026)
n, attacks = 20000, 400

y = np.zeros(n, dtype=int)
y[rng.choice(n, attacks, replace=False)] = 1
bad = y == 1

failed = np.where(bad, rng.poisson(1.8, n), rng.poisson(0.8, n))
ips = 1 + np.where(bad, rng.poisson(1.0, n), rng.poisson(0.3, n))
new_device = rng.random(n) < np.where(bad, 0.20, 0.05)
night = rng.random(n) < np.where(bad, 0.22, 0.10)
km = np.where(bad, rng.exponential(90, n), rng.exponential(20, n)).round(0)

table = np.column_stack([failed, ips, new_device, night, km, y]).astype(int)
header = "failed_logins,distinct_ips,new_device,night,km_from_last,attack"
np.savetxt("logins.csv", table, fmt="%d", delimiter=",", header=header, comments="")
print("wrote logins.csv:", len(table), "rows,", y.sum(), "attacks")
wrote logins.csv: 20000 rows, 400 attacks

The second file is the training script of your colleague, review_me.py. np.loadtxt reads a CSV file into a table, and skiprows=1 skips its header line. data[:, :-1] takes every column except the last one.

review_me.py

import numpy as np
from sklearn.linear_model import LogisticRegression

data = np.loadtxt("logins.csv", delimiter=",", skiprows=1)
X, y = data[:, :-1], data[:, -1].astype(int)

model = LogisticRegression(max_iter=1000)
model.fit(X, y)
print("accuracy:", round(model.score(X, y), 3))
python review_me.py
accuracy: 0.985

Your tasks

Work in your own lab. There are no steps. Use what the course taught.

  1. Open logins.csv with a short script. Count the events and the attack events. Work out the accuracy of a "detector" that never raises an alert, on all 20,000 events.
  1. Read review_me.py as a reviewer. Write down every flaw that you see: at least three. Think about the data that it scores on, the measure that it reports, the classes, the cut-off and what is missing.
  2. Measure the model properly. Split the data into a training part and a test part: test_size=0.25, random_state=42, and keep the share of attacks equal in both parts. Train the same model of your colleague on the training part only. Predict the test part. Compute the confusion matrix, the precision and the recall of the attack class, and the accuracy of the "always normal" baseline on the test part.
  1. Try two ways to find more attacks. First, keep the model, but call an event an attack when its attack chance is 0.2 or higher (not 0.5). Second, retrain with the setting class_weight="balanced", which makes a rare class count more. For each way, count the alerts on the test part.
  1. Decide what you would tell your lead. Is the model fit to go live? Which version, if any? What would you need before you say yes?
  2. The colleague adds that the model will be fine-tuned on new login data each month. Name the old test that you would run again after each tuning, and the one thing that you would check about the new data.
  3. The colleague also proposes to replace the model with a neural network, because "it is bigger and so it must detect more". Say what you would measure first, and why the number of parameters is not the answer.

Hand in

Write a one-page model review in a text file. Keep it to about 300 words. A person who has not seen your work must understand it and be able to act on it. Use these four headings.

  1. What was claimed. The claim in the words of the colleague, the data that it was scored on, and what the number is compared with.
  2. What I measured. A small table of your numbers: the baseline accuracy, the accuracy, the recall and the precision of the attack class on the test part, the missed attacks and the false alarms, and the same for the changes of task 4. Name the seed, the split and the versions of your lab (pip freeze).
  3. The flaws. Each flaw in one sentence, with the evidence that you found, in order of importance.
  4. My recommendation. One clear sentence (go, do not go, or go with conditions), then the conditions and the next steps, including what you would check after each monthly tuning and what you would measure before any bigger model.

Keep the review. It is the kind of proof that you can show to an employer: the data, the method and the numbers are all repeatable.

Review your work

A model solution

A reference script for tasks 1, 3 and 4 (review.py). Your own code can differ, but the numbers must match. .ravel() turns the 2 by 2 matrix into four numbers in the order TN, FP, FN, TP, and :<14 pads a name to 14 characters.

import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix, precision_score, recall_score
from sklearn.model_selection import train_test_split

data = np.loadtxt("logins.csv", delimiter=",", skiprows=1)
X, y = data[:, :-1], data[:, -1].astype(int)
print("events:", len(y), "attacks:", y.sum(), "baseline accuracy:", round(1 - y.mean(), 3))

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=42, stratify=y
)
print("test events:", len(y_test), "test attacks:", y_test.sum())
print("baseline on test:", round((y_test == 0).mean(), 3))

model = LogisticRegression(max_iter=1000).fit(X_train, y_train)
print("train accuracy:", round(model.score(X_train, y_train), 3),
      "test accuracy:", round(model.score(X_test, y_test), 3))


def report(name, pred):
    tn, fp, fn, tp = confusion_matrix(y_test, pred).ravel()
    print(f"{name:<14} alerts {pred.sum():>3}  caught {tp:>3}  missed {fn:>3}  false alarms {fp:>3}  "
          f"precision {precision_score(y_test, pred):.3f}  recall {recall_score(y_test, pred):.3f}")


chance = model.predict_proba(X_test)[:, 1]
report("cut-off 0.5", (chance >= 0.5).astype(int))
report("cut-off 0.2", (chance >= 0.2).astype(int))

weighted = LogisticRegression(max_iter=1000, class_weight="balanced").fit(X_train, y_train)
report("balanced", weighted.predict(X_test))
events: 20000 attacks: 400 baseline accuracy: 0.98
test events: 5000 test attacks: 100
baseline on test: 0.98
train accuracy: 0.984 test accuracy: 0.986
cut-off 0.5    alerts  45  caught  38  missed  62  false alarms   7  precision 0.844  recall 0.380
cut-off 0.2    alerts  76  caught  51  missed  49  false alarms  25  precision 0.671  recall 0.510
balanced       alerts 639  caught  83  missed  17  false alarms 556  precision 0.130  recall 0.830
Attacks caught of 100, test part
Cut-off 0.538 of 100Cut-off 0.251 of 100Balanced weights83 of 100Cut-off 0.538 of 100Cut-off 0.251 of 100Balanced weights83 of 100

The flaws, in order of importance.

  1. Accuracy is the wrong measure. Only 2 percent of the events are attacks, so a detector that never alerts scores 0.98. The claimed 0.985 is half a point above doing nothing.
  2. The model finds little. At the default cut-off it catches 38 of 100 attacks (recall 0.38) and misses 62. It is quiet and precise (precision 0.844), but most attacks pass.
  3. The model is scored on its own training data. Here the training and the test accuracy are close (0.984 and 0.986), because this model is simple. The colleague could not know that. A number on training data is not evidence of use in the field.
  4. There is no baseline, no confusion matrix, no precision and no recall in the report.
  5. The cut-off of 0.5 is a default, never a choice. It was not tied to the cost of a missed attack or of a false alarm.
  6. Nothing is recorded: no seed, no versions, no description of the data. The result cannot be repeated by someone else.
  7. A random split is also a risk for login events, which come in time order. A real test should train on the past and test on a later period. This file has no time column, so you can do that only with real data.

A sample report.

What was claimed. The model has 98.5 percent accuracy. The figure comes from the same 20,000 events that trained the model. No baseline is given.

What I measured. On a held-out test part of 5,000 events (100 attacks; seed 42, stratified, scikit-learn 1.9.1) the accuracy is 0.986, but a detector that never alerts also gets 0.980. At the default cut-off the model catches 38 of 100 attacks (recall 0.380, precision 0.844, 7 false alarms). At a cut-off of 0.2 it catches 51 (recall 0.510, precision 0.671, 25 false alarms). With balanced class weights it catches 83 (recall 0.830) but raises 556 false alarms (precision 0.130).

The flaws. Accuracy hides the problem, because attacks are 2 percent of the events. The model misses 62 percent of them. The score is measured on training data. There is no baseline, no per-class measure, no tuned cut-off, no record of seed or versions.

My recommendation. Do not go live on the claim "98.5 percent accurate". Go live only as a helper that ranks events for analysts, with the cut-off near 0.2, if the SOC accepts about 25 false alarms for every 5,000 events. Before that: agree the cost of a missed attack and of a false alarm, split by time, add stronger features (the model sees few of the attacks), measure on real recent events, and report recall and precision each month. After every monthly tuning, run the held-out test of this review again, because tuning can break what worked before, and check where the new data came from and who could change it.

On a bigger model. A neural network has more parameters (lesson 8), but its size says how much it can memorise, not how well it detects. Measure it as in task 3: the same held-out test, the recall and precision of the attack class, and the baseline of 0.98. A new model is worth its cost only if it beats the 0.38 recall of this one on that test.

Mark your report

You mark this yourself, or you ask a colleague or a mentor to mark it. The page checks the numbers above; it cannot read your report.

CriterionNot yetMeets the standardStrong
FindingsFewer than three flaws; accuracy accepted.Baseline 0.98, training-data score, recall 0.38 (62 missed), default cut-off, nothing recorded.Also the random split of time-ordered events.
EvidenceNo split, seed or versions.The claim and its source; held-out table for three versions; seed, split, versions.Another person repeats every number from your script.
JudgementFlaws unranked; bigger model accepted for size.Flaws ranked with reasons; missed attacks against false alarms, in counts.Says what the test cannot show.
RecommendationNone, or "go" on 98.5 percent.A decision with conditions; re-test after each tuning; check of new data.Ties the cut-off to agreed costs.
WritingAn analyst cannot picture the numbers.About 300 words, four headings, dated, no blame.Your lead can act on the first sentence.

Meets the standard in every row: you can show this report as a work sample. Remove names and data that are not yours to share.

The report proves your work on this scenario, on your own machine, without a proctor. It does not prove work on live login data.

Get a result link

When all 9 answers above are right, the server can check them again and give you a signed link. You can put the link in a CV or send it to a manager: it opens a page that shows the course, the test, the date and the name you give here. No account, and nothing is stored: keep the link.