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 02 · 35 minutes

Read a dataset as examples, features and labels

After this lesson you can
  • Load the digits dataset and read one sample as numbers
  • Check how many examples each class has
  • Show that wrong labels make a worse model
Lab files of this lesson (6)

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 partner company offers you a labelled data set to train your detector. "It is clean," they say. Your manager asks: "Can we trust it before we spend a week on training?" You have no time to read every row, so you must find out what is in the data, how the classes are counted, and what bad labels would do. You practise on a small public data set of handwritten digits, then you spoil a different class yourself and measure the damage.

Recall

In lesson 1, which numbers did training set, and what are they called?

The weights and the bias. Together they are the parameters of the model. fit finds them from the examples.

What do `X` and `y` hold in a call of `model.fit(X, y)`?

X holds the inputs, one list of numbers for each example. y holds the right answer for each example, in the same order.

The idea

Machine learning data has three parts.

TermMeaningDigits example
Example (or sample)One item the model learns fromOne picture of a handwritten digit
FeaturesThe numbers that describe an example64 pixel values
LabelThe right answer for an exampleThe digit, 0 to 9
What the model gets from one picture
Exampleone 8 by 8 picture of a digitFeatures64 pixel numbers, one row of XLabelthe right digit, one item of yExampleone 8 by 8 picture of a digitFeatures64 pixel numbers, one row of XLabelthe right digit, one item of y

The features go into a table called X: one row for each example, one column for each feature. The labels go into a list called y. Row 5 of X belongs to item 5 of y.

A class is one possible label. A balanced dataset has about the same number of examples in each class. In security the data is rarely balanced: attacks are rare. You check this before training.

scikit-learn ships with several small datasets. The digits dataset has 1,797 pictures of handwritten digits, each 8 by 8 pixels. It is stored inside the package, so you download nothing.

Worked example

1. Load the data and check its shape

Go to the lab folder and activate the environment from lesson 1. Create look_digits.py. These names are new:

  • load_digits loads the dataset. With return_X_y=True it gives back X and y. Without it, it gives one object with more parts: digits.data is X and digits.target is y.
  • NumPy (import numpy as np) is the library for tables of numbers. Scikit-learn uses it inside.
  • .shape is the size of a table: the rows, then the columns. .min() and .max() give the smallest and the largest value.
import numpy as np
from sklearn.datasets import load_digits

digits = load_digits()
X, y = digits.data, digits.target
print("samples, features:", X.shape)
print("labels shape:", y.shape)
print("pixel range:", X.min(), "to", X.max())
cd ~/krlab/how-ai-works
source .venv/bin/activate
python look_digits.py
samples, features: (1797, 64)
labels shape: (1797,)
pixel range: 0.0 to 16.0

X has 1,797 rows and 64 columns. Each pixel is a number from 0 (white) to 16 (full ink).

2. Look at one sample

digits.images holds the same pictures as 8 by 8 grids, and .astype(int) turns the numbers into whole numbers for a tidy print. Add these lines to the end of the file and run it again.

print("label of sample 0:", y[0])
print(digits.images[0].astype(int))
label of sample 0: 0
[[ 0  0  5 13  9  1  0  0]
 [ 0  0 13 15 10 15  5  0]
 [ 0  3 15  2  0 11  8  0]
 [ 0  4 12  0  0  8  8  0]
 [ 0  5  8  0  0  9  8  0]
 [ 0  4 11  0  1 12  7  0]
 [ 0  2 14  5 10 12  0  0]
 [ 0  0  6 13 10  0  0  0]]

Look at the big numbers. They form a ring: this is a zero. The model never sees a picture. It sees 64 numbers, laid out in one row, and it learns which numbers go with which label.

Sample 0, 64 features and one label
0pixel 00pixel 15pixel 213pixel 3...pixels 4 to 630label: a zero0pixel 00pixel 15pixel 213pixel 3...pixels 4 to 630label: a zero

3. Count the classes

np.bincount(y) counts how often each whole number occurs in y: the first number is the count of label 0, the second of label 1, and so on. Add one more line.

print("class counts:", np.bincount(y))
class counts: [178 182 177 183 181 182 181 179 174 180]

Each digit has between 174 and 183 examples. The dataset is balanced, so a model cannot do well by guessing the most common class. Keep this in mind for lesson 6, where the classes are not balanced.

4. Damage the labels on purpose

Now you test what bad data does. The program below trains one model on correct labels and one on labels where half of the training sevens have been relabelled as ones. New parts:

  • train_test_split cuts the data into a training part and a test part. Lesson 3 explains it. For now, accept that the test part is data that the model does not see during training. test_size=0.25 makes the test part a quarter of the data. random_state=42 fixes the random cut, so that your numbers match the page. max_iter=2000 lets the training run long enough to finish (lesson 3 says more).
  • model.score(X, y) gives the share of right answers of the model on the data you give it.
  • yte == 7 makes a list of True and False, one for each label: a mask. pred[sevens] keeps only the predictions where the mask is true, and .mean() of a list of True and False is the share of True.
  • np.where(bad == 7)[0] gives the positions where the condition holds. .copy() makes a second list, so that the first stays correct.
  • // divides and drops the decimals, so len(sevens) // 2 is half of the count, rounded down. sevens[: n] keeps the first n items.

Create poison.py.

poison.py

import numpy as np
from sklearn.datasets import load_digits
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split

X, y = load_digits(return_X_y=True)
Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.25, random_state=42)

def run(labels, name):
    m = LogisticRegression(max_iter=2000).fit(Xtr, labels)
    pred = m.predict(Xte)
    sevens = yte == 7
    print(f"{name}: overall {m.score(Xte, yte):.3f}, on real 7s {(pred[sevens] == 7).mean():.3f}")

run(ytr, "clean   ")
bad = ytr.copy()
sevens = np.where(bad == 7)[0]
bad[sevens[: len(sevens) // 2]] = 1      # half of the 7s are labelled 1
run(bad, "poisoned")
python poison.py
clean   : overall 0.973, on real 7s 0.976
poisoned: overall 0.918, on real 7s 0.537
Accuracy before and after the poisoning
Clean model, all digits0.973Poisoned model, all digits0.918Clean model, real 7s0.976Poisoned model, real 7s0.537Clean model, all digits0.973Poisoned model, all digits0.918Clean model, real 7s0.976Poisoned model, real 7s0.537

Only about 5 percent of the training labels changed, and only in one class. The overall score fell a little. The score on real sevens fell by almost half. A single average number hid most of the damage. Lesson 6 shows how to look for this.

5. The finished file

This is the whole file look_digits.py as it stands after the steps above. The lab files of the course hold it.

The finished file: look_digits.py

look_digits.py

import numpy as np
from sklearn.datasets import load_digits

digits = load_digits()
X, y = digits.data, digits.target
print("samples, features:", X.shape)
print("labels shape:", y.shape)
print("pixel range:", X.min(), "to", X.max())
print("label of sample 0:", y[0])
print(digits.images[0].astype(int))
print("class counts:", np.bincount(y))

Your turn

Do the same attack on another class, on another split. There is no code here: adapt poison.py.

  1. Split the digits with test_size=0.2 and random_state=7. Do not use stratify.
  2. Poison the training labels: find the training examples whose label is 3, and relabel the first half of them as 5. Use whole-number division by 2, and keep the order in which they appear.
  3. Train a LogisticRegression(max_iter=2000) on the poisoned labels. Test it on the untouched test labels.
  4. Measure the share of the real 3s in the test part that the model still calls 3.

Last, write one sentence for your manager: how would a check of the overall score alone have missed this?

Check yourself

What do the rows and the columns of X stand for in the digits dataset?

Each row is one picture (one example). Each column is one pixel position (one feature). So X has 1,797 rows and 64 columns.

A dataset for a malware detector has 99,000 harmless files and 1,000 malware files. Why does the class count matter before you train?

The data is not balanced. A model that says "harmless" every time is right 99 percent of the time and finds no malware. You need to know this before you read any score.

In the worked example, the overall score fell only from 0.973 to 0.918. Why is that not a reason to relax?

The damage is in one class. The score for real sevens fell from 0.976 to 0.537. An attacker who wants one specific failure does not need to spoil the whole model.

Where in a real security system could wrong labels come from?

From analysts who close alerts in a hurry, from rules that label data by a weak guess, from user feedback buttons, and from an attacker who submits samples that are labelled on purpose.

Field notes

  • The attack in this lesson is data poisoning, in the form called label flipping. The OWASP Top 10 for LLM applications and MITRE ATLAS both list poisoning of training data. Later courses attack and defend against it.
  • Check for duplicates and near-duplicates before you split data. The same item in the training and test parts gives a score that is too good. This is one form of data leakage.
  • Write down where each part of the data came from, who labelled it and when. This record (a data sheet) is the first thing an auditor asks for.
  • Features can hide a shortcut. A model for "malware or not" that learns "the file was collected in 2024" has learned the date, not the malware. Look at which features carry the weight (lesson 12).
  • Real labels are never perfect. Plan for some wrong ones, and keep a clean, small, hand-checked set for testing.