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

Lesson 10 · 45 minutes

Clean a data feed and measure what each step does

After this lesson you can
  • Sort files into structured, semi-structured and unstructured data and load each kind
  • Clean a labelled feed and measure what cleaning does to a score
  • Add training rows by augmentation without letting the test set shape the model
Lab files of this lesson (29)

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 partner of lesson 2 sends a feed of labelled mail for the filter of lesson 12, and three extracts. Your manager asks what kind of data it is and whether it is fit to train on. You sort the extracts, clean the feed, add rows by augmentation, and measure what each step does to a score. Lesson 11 then records the history of the feed. The file and CSV code is from the course Python, lesson 4.

Recall

In lesson 2, half of the training sevens got the label 1. What happened to the score on real sevens?

It fell from 0.976 to 0.537. Wrong labels make a wrong model.

In lesson 3, why is the score on the training data not the score you report?

The model has seen those rows, so the score is too good. Only data that the model never saw says how it works on new data.

The idea

Data that you did not make is a claim until you check it.

TermMeaningIn this lesson
Structured dataFixed columns in every rowfeed_a.dat
Semi-structured dataNamed fields, but records differ or nestfeed_b.dat
Unstructured dataFree text, images, audiofeed_c.dat
Data cleansingFix or drop bad rowsclean()
Data verificationCheck data against a trusted sourcetrusted.csv
Data augmentationMake training rows from real onesaugment()
From a partner feed to a trusted data set
Partner feedRaw copyClean copyTraining rowsModelkeep it as it camedrop empty, conflicting and repeated rowsadd variants that keep the labeltrain, then score on trusted.csvPartner feedRaw copyClean copyTraining rowsModel1234
  1. Partner feed → Raw copy: keep it as it came
  2. Raw copy → Clean copy: drop empty, conflicting and repeated rows
  3. Clean copy → Training rows: add variants that keep the label
  4. Training rows → Model: train, then score on trusted.csv

Worked example

1. Sort three files by type

The name .dat says nothing about the content. Create three extracts.

cd ~/krlab/how-ai-works
source .venv/bin/activate
cat > feed_a.dat <<'EOT'
time,src_ip,port,action
08:01,203.0.113.9,22,deny
08:02,198.51.100.4,443,allow
08:05,192.0.2.77,3389,deny
08:09,198.51.100.4,443,allow
EOT
cat > feed_b.dat <<'EOT'
{"id": 1, "type": "login", "user": "ana", "ok": false}
{"id": 2, "type": "alert", "rule": "scan", "hosts": ["h1", "h2"]}
{"id": 3, "type": "login", "user": "bo", "ok": true, "mfa": "app"}
EOT
cat > feed_c.dat <<'EOT'
Analyst note, Monday. The scan alert came from a laptop in the
guest network. The owner says the laptop was lent to a visitor.
I closed the alert and asked for the visitor's name.
EOT

feed_a.dat has the same four fields in every row: structured. In feed_b.dat every line has named fields, but line 2 has rule and hosts where line 1 has user: semi-structured. feed_c.dat is sentences: unstructured.

2. Load each kind with the right tool

csv.DictReader reads a table as one dictionary for each row, with the header names as keys. json.loads turns a line of JSON into a dictionary. A set, written {...}, keeps each value once. list(rows[0]) gives the keys of the first row, len(text.split()) counts the words of a text, and {k for r in records for k in r} collects every key of every record once. Create kinds.py.

kinds.py

import csv
import json

rows = list(csv.DictReader(open("feed_a.dat")))
print("structured:", len(rows), "rows, columns", list(rows[0]))

records = [json.loads(line) for line in open("feed_b.dat")]
print("semi-structured:", len(records), "records,", len({k for r in records for k in r}), "keys")

text = open("feed_c.dat").read()
print("unstructured:", len(text.split()), "words in one text")
python kinds.py
structured: 4 rows, columns ['time', 'src_ip', 'port', 'action']
semi-structured: 3 records, 7 keys
unstructured: 34 words in one text

A table is ready to become X (lesson 2). Records need a choice of columns from the 7 keys. Text must become numbers first (lesson 9).

3. Clean the feed and measure the damage

trusted.csv holds 10 messages that you checked by hand, and is never trained on. feed.csv has empty cells, labels in three cases, repeated messages, and a thank-you note saved four times as phish.

cat > feed.csv <<'EOT'
id,label,text
1,phish,Verify your password now
2,phish,Your account is locked. Click the link
3,PHISH,CONFIRM YOUR BANK DETAILS
4,phish,You won. Click to claim it
5,Phish,Update your card details
6,phish,Your password expires today
7,ok,Lunch at noon. I booked a table
8,ok,The meeting moved to ten
9,OK,Please review my pull request
10,ok,The build passed today
11,ok,Thanks for the notes
12,Ok,Send me the slides
13,phish,  verify your PASSWORD now
14,ok,the meeting moved to TEN
15,ok,Your account is locked. Click the link
16,phish,Thanks for the notes
17,phish,THANKS FOR THE NOTES
18,phish,Thanks for the notes
19,phish,thanks  for the notes
20,phish,
21,,Send me the slides
22,ok,
EOT
cat > trusted.csv <<'EOT'
id,label,text
1,phish,Tap the page to change your passcode
2,phish,Tap to claim the reward
3,phish,Your card was declined. Change your details
4,phish,Tap here to confirm your bank details
5,phish,Your account is locked. Confirm your passcode
6,ok,Can we move the review to Friday?
7,ok,The backup finished
8,ok,Thanks for the quick fix
9,ok,The release notes are in the shared folder
10,ok,Thanks for the agenda
EOT

In prep.py, with open(path) as f: opens a file and closes it again at the end of the block. newline="" lets the csv module handle the line ends. csv.DictWriter writes dictionaries as rows: writeheader writes the column names, writerows writes the rows, and lineterminator="\n" ends every line the same way on every system. In clean, .strip() removes spaces at both ends, .lower() makes lower case, and " ".join(text.split()) turns a run of spaces into one. clean drops three kinds of row:

  • empty: no text, or a label that is not phish or ok.
  • conflict: the same text with two labels. You cannot tell which is right, so none is kept (setdefault collects the labels of a text).
  • duplicate: the same text and label again. Only the first is kept.

prep.py

import csv


def read_rows(path):
    with open(path, newline="") as f:
        return list(csv.DictReader(f))


def write_rows(path, rows):
    with open(path, "w", newline="") as f:
        writer = csv.DictWriter(f, ["id", "label", "text"], lineterminator="\n")
        writer.writeheader()
        writer.writerows(rows)


def clean(rows):
    dropped = {"empty": 0, "conflict": 0, "duplicate": 0}
    tidy = []
    for row in rows:
        label = row["label"].strip().lower()
        text = " ".join(row["text"].lower().split())
        if label in ("phish", "ok") and text:
            tidy.append({"id": row["id"], "label": label, "text": text})
        else:
            dropped["empty"] += 1
    labels = {}
    for row in tidy:
        labels.setdefault(row["text"], set()).add(row["label"])
    kept, seen = [], set()
    for row in tidy:
        if len(labels[row["text"]]) > 1:
            dropped["conflict"] += 1
        elif row["text"] in seen:
            dropped["duplicate"] += 1
        else:
            seen.add(row["text"])
            kept.append(row)
    return kept, dropped

prepare.py cleans the feed, saves clean.csv, and scores a model trained on the raw rows and one on the clean rows (lessons 9 and 3). C=10 lets the model fit the training rows more closely than the default does (lesson 12 says more).

prepare.py

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression

from prep import clean, read_rows, write_rows


def score(train, test):
    vec = TfidfVectorizer()
    model = LogisticRegression(C=10, max_iter=1000)
    model.fit(vec.fit_transform([r["text"] for r in train]), [r["label"] for r in train])
    return round(model.score(vec.transform([r["text"] for r in test]), [r["label"] for r in test]), 2)


raw = read_rows("feed.csv")
trusted = read_rows("trusted.csv")
kept, dropped = clean(raw)
write_rows("clean.csv", kept)
print("rows:", len(raw), "->", len(kept), dropped)
print("score with the raw feed:  ", score(raw, trusted))
print("score with the clean feed:", score(kept, trusted))
python prepare.py
rows: 22 -> 10 {'empty': 3, 'conflict': 7, 'duplicate': 2}
score with the raw feed:   0.6
score with the clean feed: 0.8

12 of 22 rows are gone. The raw model got 4 of 10 trusted messages wrong (to see them, print each trusted text whose model.predict answer differs from its label). Two are thank-you notes that it calls phishing, because the feed says so four times. Two are phishing messages that it labels Phish and PHISH: it learned three spellings of one label, and a spelling counts as wrong. Cleaning removes both causes. The clean model got 2 wrong, and both contain the word tap. It gives them a chance of phishing of 0.48 and 0.39, so it is unsure, and no training row holds tap. A conflict rule cannot see a wrong label with no twin. Only a comparison with trusted.csv shows that something is wrong (a lower score), not which row: this is data verification.

4. Add rows by augmentation

Augmentation makes training rows from real ones by a change that keeps the label true. Here a word is swapped for another of the same job. The rule comes from the training rows only: in clean.csv, verify, confirm and update each open a phishing message, so the swaps stay among them. No word comes from trusted.csv. Add this at the end of prep.py. In prepare.py, add augment to the import line and the last three lines at the end.

SWAPS = {"verify": "confirm", "confirm": "verify", "update": "confirm"}


def augment(rows):
    extra = []
    for row in rows:
        words = row["text"].split()
        new = [SWAPS.get(word, word) for word in words]
        if new != words:
            extra.append({"id": row["id"] + "a", "label": row["label"], "text": " ".join(new)})
    return rows + extra
more = augment(kept)
print("training rows:", len(kept), "->", len(more))
print("score with augmented rows:", score(more, trusted))

The new rows get ids that end in a, so that you can tell them from the real rows. Run prepare.py again: the first three lines stay, and two are new.

training rows: 10 -> 13
score with augmented rows: 0.8
Score on trusted.csv, 10 messages
Raw feed0.6Clean feed0.8Clean feed and augmented rows0.8Raw feed0.6Clean feed0.8Clean feed and augmented rows0.8

The score does not move: augmentation adds only what your rule knows. The two misses hold tap, passcode and reward, and no training row holds those words. If you also swapped the word click for tap and the word password for passcode, the score would be 1.0. But you would have chosen those swaps by reading the misses on trusted.csv. Then the test set has shaped the model, and 1.0 is flattering (lesson 3). Augment training rows only.

5. The finished files

The finished files: prep.py and prepare.py

prep.py

import csv


def read_rows(path):
    with open(path, newline="") as f:
        return list(csv.DictReader(f))


def write_rows(path, rows):
    with open(path, "w", newline="") as f:
        writer = csv.DictWriter(f, ["id", "label", "text"], lineterminator="\n")
        writer.writeheader()
        writer.writerows(rows)


def clean(rows):
    dropped = {"empty": 0, "conflict": 0, "duplicate": 0}
    tidy = []
    for row in rows:
        label = row["label"].strip().lower()
        text = " ".join(row["text"].lower().split())
        if label in ("phish", "ok") and text:
            tidy.append({"id": row["id"], "label": label, "text": text})
        else:
            dropped["empty"] += 1
    labels = {}
    for row in tidy:
        labels.setdefault(row["text"], set()).add(row["label"])
    kept, seen = [], set()
    for row in tidy:
        if len(labels[row["text"]]) > 1:
            dropped["conflict"] += 1
        elif row["text"] in seen:
            dropped["duplicate"] += 1
        else:
            seen.add(row["text"])
            kept.append(row)
    return kept, dropped


SWAPS = {"verify": "confirm", "confirm": "verify", "update": "confirm"}


def augment(rows):
    extra = []
    for row in rows:
        words = row["text"].split()
        new = [SWAPS.get(word, word) for word in words]
        if new != words:
            extra.append({"id": row["id"] + "a", "label": row["label"], "text": " ".join(new)})
    return rows + extra

prepare.py

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression

from prep import augment, clean, read_rows, write_rows


def score(train, test):
    vec = TfidfVectorizer()
    model = LogisticRegression(C=10, max_iter=1000)
    model.fit(vec.fit_transform([r["text"] for r in train]), [r["label"] for r in train])
    return round(model.score(vec.transform([r["text"] for r in test]), [r["label"] for r in test]), 2)


raw = read_rows("feed.csv")
trusted = read_rows("trusted.csv")
kept, dropped = clean(raw)
write_rows("clean.csv", kept)
print("rows:", len(raw), "->", len(kept), dropped)
print("score with the raw feed:  ", score(raw, trusted))
print("score with the clean feed:", score(kept, trusted))

more = augment(kept)
print("training rows:", len(kept), "->", len(more))
print("score with augmented rows:", score(more, trusted))

Your turn

A second partner sends feed2.csv. Prepare it with prep.py. Write a short script that calls the functions of prep.py (read_rows, clean, augment, write_rows). Lesson 11 uses clean2.csv again, so save it.

cat > feed2.csv <<'EOT'
id,label,text
1,phish,Your invoice is overdue. Click the link
2,PHISH,Confirm your password now
3,ok,Standup moved to ten
4,Ok,The VPN is down on Sunday
5,ok,  standup moved to TEN
6,phish,Free reward. Click now
7,ok,Free reward. Click now
8,phish,Free reward. Click now
9,,Lunch on Friday?
10,ok,
EOT
  1. Clean feed2.csv, save clean2.csv, and count the rows kept and the rows dropped as a conflict.
  2. Augment the kept rows and count the rows.

Check yourself

An email has the fields From, To and Subject, then a free-text body. Which kind of data is it?

Semi-structured: named fields that differ from mail to mail. The body is unstructured text.

Why does `clean` drop both rows of a conflict and not keep one of them?

You cannot tell which label is right. If you keep the wrong one, the model learns a wrong answer. Dropping both costs two rows and risks nothing.

Cleaning raised the score on `trusted.csv` from 0.6 to 0.8. Does that prove that the clean feed has no wrong labels?

No. The rules catch only what they can see: empty cells, two spellings, repeats and conflicts. A wrong label with no twin passes them. The trusted messages show that something is wrong (a lower score), not which row.

Why must you pick the swaps from the training rows, and augment only them?

A swap that you pick after reading the test rows, or a made copy of a test row, lets the test set shape the model. The score is too good. Test rows stay real and unseen.

Field notes

  • Keep the raw feed as it came, and write the clean rows to a new file. Then you can always run the cleaning again with another rule.
  • Read the dropped counts every time. A feed that suddenly loses half its rows to conflicts has changed in some way, and a person should look before the model trains.
  • Keep trusted.csv small, checked by hand, and out of every training and augmentation step. Change it only on purpose, and say so in your report.
  • Poisoning (the course Securing models, lesson 2) enters through a feed or a label tool. Cleaning and a trusted set are the first defence. Lesson 11 adds a record that shows a later change.