Files
labs/Lab-3/Lab-3-Solution/01_Security_Features_Labels_Solution.ipynb
T

5.3 KiB

Module 3 — Lab 1: Security Features and Binary Labels

Topics: samples, features, labels, class distribution

Solution version: This notebook contains the complete solution. Run the cells in order and compare the results with your Lab notebook.

Learning objectives

After completing this lab, you will be able to:

  • identify samples, features, and labels in a security dataset;
  • inspect the schema and data types of a network-flow table;
  • convert multiple attack names into one binary target;
  • explain why class distribution matters before model training.
In [ ]:
from pathlib import Path
import numpy as np
import pandas as pd

DATA_PATH = Path("data/synthetic_security_flows.csv")
RANDOM_STATE = 42

1. Load and inspect the flow table

In [ ]:
df = pd.read_csv(DATA_PATH)

print("Shape:", df.shape)
df.head()

2. Identify the label and numeric features

In [ ]:
y_text = df["Label"].astype(str).str.strip()
X = df.drop(columns="Label").select_dtypes(include="number")

print("Feature matrix shape:", X.shape)
print("Original labels:")
print(y_text.value_counts())

3. Create a binary security target

In [ ]:
normalized_labels = y_text.str.strip().str.upper()
y_binary = normalized_labels.ne("BENIGN").astype(int)
class_counts = y_binary.value_counts().sort_index()

print(class_counts.rename(index={0: "BENIGN", 1: "ATTACK"}))
print("Attack rate:", round(y_binary.mean(), 3))

4. Connect rows to feature vectors

In [ ]:
sample_index = 0
sample_features = X.iloc[sample_index]
sample_target = int(y_binary.iloc[sample_index])

print("Selected feature vector:")
print(sample_features)
print("Binary target:", sample_target)

Self-check

In [ ]:
assert isinstance(df, pd.DataFrame)
assert "Label" not in X.columns
assert set(y_binary.unique()) == {0, 1}
assert len(X) == len(y_binary)
assert class_counts.loc[0] > class_counts.loc[1]
assert len(sample_features) == X.shape[1]
print("✓ Lab 1 completed")

Reflection questions

  1. Why is each row considered one sample while each column is considered one feature?
  2. What information is lost when several attack families are mapped to one ATTACK class?
  3. Why could high accuracy be misleading when BENIGN is the majority class?
In [ ]:
In [ ]:
In [ ]:
In [ ]: