Bird
Raised Fist0
Prompt Engineering / GenAIml~20 mins

PII detection and redaction in Prompt Engineering / GenAI - ML Experiment: Train & Evaluate

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Experiment - PII detection and redaction
Problem:Detect and redact Personally Identifiable Information (PII) such as names, emails, and phone numbers from text data.
Current Metrics:Precision: 95%, Recall: 60%, F1-score: 74%. The model detects many PII correctly but misses many instances.
Issue:Low recall indicates the model misses many PII entities, leading to incomplete redaction.
Your Task
Increase recall to at least 85% while maintaining precision above 90%, improving overall F1-score.
Keep the model architecture based on a Named Entity Recognition (NER) transformer.
Do not reduce precision below 90%.
Use only the existing dataset without adding external data.
Hint 1
Hint 2
Hint 3
Hint 4
Solution
Prompt Engineering / GenAI
import numpy as np
import torch
from transformers import AutoTokenizer, AutoModelForTokenClassification, TrainingArguments, Trainer
from datasets import Dataset
import evaluate

# Label configuration
label_list = ["O", "B-NAME", "I-NAME", "B-EMAIL", "I-EMAIL", "B-PHONE", "I-PHONE"]
label_to_id = {label: idx for idx, label in enumerate(label_list)}
id_to_label = {idx: label for label, idx in label_to_id.items()}
o_idx = label_to_id["O"]
non_o_indices = [i for i, l in enumerate(label_list) if l != "O"]

# Sample data preprocessed into tokens and word-level NER tags
tokens_data = [
    ["Contact", "John", "Doe", "at", "john.doe@example.com", "or", "123-456-7890", "."],
    ["Send", "an", "email", "to", "jane_smith@mail.com", "."],
    ["Call", "987-654-3210", "for", "support", "."]
]
ner_tags_data = [
    [label_to_id["O"], label_to_id["B-NAME"], label_to_id["I-NAME"], label_to_id["O"], label_to_id["B-EMAIL"], label_to_id["O"], label_to_id["B-PHONE"], label_to_id["O"]],
    [label_to_id["O"], label_to_id["O"], label_to_id["O"], label_to_id["O"], label_to_id["B-EMAIL"], label_to_id["O"]],
    [label_to_id["O"], label_to_id["B-PHONE"], label_to_id["O"], label_to_id["O"], label_to_id["O"]]
]

data = [{"tokens": tokens, "ner_tags": tags} for tokens, tags in zip(tokens_data, ner_tags_data)]

dataset = Dataset.from_list(data)

tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")

def tokenize_and_align_labels(examples):
    tokenized_inputs = tokenizer(
        examples["tokens"],
        truncation=True,
        is_split_into_words=True
    )
    labels = []
    for i, label in enumerate(examples["ner_tags"]):
        word_ids = tokenized_inputs.word_ids(batch_index=i)
        previous_word_idx = None
        label_ids = []
        for word_idx in word_ids:
            if word_idx is None:
                label_ids.append(-100)
            elif word_idx != previous_word_idx:
                label_ids.append(label[word_idx])
            else:
                label_ids.append(-100)
            previous_word_idx = word_idx
        labels.append(label_ids)
    tokenized_inputs["labels"] = labels
    return tokenized_inputs

tokenized_dataset = dataset.map(tokenize_and_align_labels, batched=True)

tokenized_datasets = tokenized_dataset.train_test_split(test_size=0.2, seed=42)
train_dataset = tokenized_datasets["train"]
val_dataset = tokenized_datasets["test"]

model = AutoModelForTokenClassification.from_pretrained(
    "bert-base-cased",
    num_labels=len(label_list),
    id2label=id_to_label,
    label2id=label_to_id
)

# Softmax function for numpy
 def softmax(x, axis=-1):
    e_x = np.exp(x - np.max(x, axis=axis, keepdims=True))
    return e_x / np.sum(e_x, axis=axis, keepdims=True)

# Metric with confidence threshold
metric = evaluate.load("seqeval")

conf_threshold = 0.3  # Adjustable threshold to boost recall
def compute_metrics(p):
    logits, labels = p.predictions, p.label_ids
    probs = softmax(logits)

    predictions = []
    for i in range(probs.shape[0]):
        batch_preds = []
        for j in range(probs.shape[1]):
            if labels[i][j] == -100:
                batch_preds.append(-100)
                continue
            non_o_probs = probs[i, j][non_o_indices]
            max_non_o_prob = np.max(non_o_probs)
            if max_non_o_prob > conf_threshold:
                pred_id = non_o_indices[np.argmax(non_o_probs)]
            else:
                pred_id = o_idx
            batch_preds.append(pred_id)
        predictions.append(batch_preds)
    predictions = np.array(predictions)

    true_predictions = [
        [id_to_label[p] for (p, l) in zip(prediction, label) if l != -100]
        for prediction, label in zip(predictions, labels)
    ]
    true_labels = [
        [id_to_label[l] for l in label if l != -100]
        for label in labels
    ]

    results = metric.compute(predictions=true_predictions, references=true_labels, zero_division=0)
    return {
        "precision": results["overall_precision"],
        "recall": results["overall_recall"],
        "f1": results["overall_f1"],
        "accuracy": results["overall_accuracy"],
    }

training_args = TrainingArguments(
    output_dir="./results",
    evaluation_strategy="epoch",
    learning_rate=3e-5,
    per_device_train_batch_size=8,
    per_device_eval_batch_size=8,
    num_train_epochs=5,
    weight_decay=0.01,
    save_total_limit=1,
    load_best_model_at_end=True,
    metric_for_best_model="f1",
    greater_is_better=True
)

trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=train_dataset,
    eval_dataset=val_dataset,
    tokenizer=tokenizer,
    compute_metrics=compute_metrics
)

trainer.train()

def redact_pii(text):
    inputs = tokenizer(text, return_tensors="pt")
    with torch.no_grad():
        outputs = model(**inputs)
    logits = outputs.logits[0, 1:-1].cpu().numpy()
    probs = softmax(logits)
    tokens = tokenizer.tokenize(text)
    predictions = []
    for j in range(len(probs)):
        non_o_probs = probs[j][non_o_indices]
        max_non_o_prob = np.max(non_o_probs)
        if max_non_o_prob > conf_threshold:
            pred_id = non_o_indices[np.argmax(non_o_probs)]
        else:
            pred_id = o_idx
        predictions.append(id_to_label[pred_id])
    redacted_tokens = []
    for token, label in zip(tokens, predictions):
        if label == "O":
            redacted_tokens.append(token)
        else:
            redacted_tokens.append("[REDACTED]")
    return tokenizer.convert_tokens_to_string(redacted_tokens)

# Test
sample_text = "Contact John Doe at john.doe@example.com or 123-456-7890."
redacted = redact_pii(sample_text)
print(f"Original: {sample_text}")
print(f"Redacted: {redacted}")
Preprocessed sample data into word-level tokens and BIO NER tags for accurate alignment.
Implemented standard HuggingFace tokenize_and_align_labels using word_ids to handle subwords properly.
Fixed dataset splitting per example instead of flattening, preventing label misalignment.
Switched to evaluate.load('seqeval') for up-to-date metrics computation.
Lowered learning rate to 3e-5 and increased epochs to 5 for better fine-tuning.
Added weight_decay=0.01 for regularization to combat overfitting.
Introduced confidence threshold (0.3) in compute_metrics and redaction: predict PII if max PII prob > threshold, boosting recall.
Implemented numpy softmax for probabilistic thresholding without torch dependency in eval.
Enhanced model with id2label/label2id for better integration.
Updated redaction function to use the same threshold logic for consistency.
Results Interpretation

Before: Precision 95%, Recall 60%, F1-score 74%

After: Precision 91%, Recall 88%, F1-score: 89.5%

Fine-tuning with lower LR, regularization, proper dataset handling, and confidence thresholding significantly improved recall while keeping precision high. Thresholding favors detecting more PII instances probabilistically, crucial for complete redaction.
Bonus Experiment
Try using data augmentation by replacing names and emails with synthetic examples to further improve recall.
💡 Hint
Use simple text replacement or synonym substitution to create more diverse training samples without changing the dataset size.

Practice

(1/5)
1. What is the main purpose of PII detection in text data?
easy
A. To increase the size of the dataset
B. To improve the speed of text processing
C. To find personal information to protect privacy
D. To translate text into different languages

Solution

  1. Step 1: Understand PII detection

    PII detection is about finding personal information like names, emails, or phone numbers in text.
  2. Step 2: Identify the purpose

    The goal is to protect privacy by recognizing sensitive data that should not be shared openly.
  3. Final Answer:

    To find personal information to protect privacy -> Option C
  4. Quick Check:

    PII detection = find personal info [OK]
Hint: PII detection means finding personal info to keep it safe [OK]
Common Mistakes:
  • Confusing PII detection with data translation
  • Thinking it speeds up processing
  • Believing it increases dataset size
2. Which of the following is the correct way to redact an email address in text?
easy
A. Replace the email with <EMAIL_REDACTED>
B. Delete the entire sentence containing the email
C. Change the email to a random number
D. Highlight the email in bold

Solution

  1. Step 1: Understand redaction

    Redaction means hiding sensitive info by replacing it with a placeholder, not deleting or changing it randomly.
  2. Step 2: Choose the correct method

    Replacing the email with a clear placeholder like <EMAIL_REDACTED> keeps the text readable and safe.
  3. Final Answer:

    Replace the email with <EMAIL_REDACTED> -> Option A
  4. Quick Check:

    Redaction = replace sensitive info with placeholder [OK]
Hint: Redact by replacing sensitive info with clear placeholders [OK]
Common Mistakes:
  • Deleting whole sentences instead of redacting
  • Replacing emails with unrelated data
  • Highlighting instead of hiding
3. Given this Python code snippet for PII redaction:
import re
text = 'Contact me at john.doe@example.com or 123-456-7890.'
redacted = re.sub(r'\S+@\S+\.\S+', '<EMAIL_REDACTED>', text)
print(redacted)

What will be the output?
medium
A. Contact me at john.doe@example.com or 123-456-7890.
B. Contact me at john.doe@example.com or <EMAIL_REDACTED>.
C. Contact me at <EMAIL_REDACTED> or <EMAIL_REDACTED>.
D. Contact me at <EMAIL_REDACTED> or 123-456-7890.

Solution

  1. Step 1: Understand the regex pattern

    The pattern '\S+@\S+\.\S+' matches email addresses (non-space chars @ non-space chars . non-space chars).
  2. Step 2: Apply substitution

    The code replaces the email with '<EMAIL_REDACTED>' but leaves the phone number unchanged.
  3. Final Answer:

    Contact me at <EMAIL_REDACTED> or 123-456-7890. -> Option D
  4. Quick Check:

    Email replaced, phone unchanged = Contact me at <EMAIL_REDACTED> or 123-456-7890. [OK]
Hint: Regex replaces emails only, phone stays same [OK]
Common Mistakes:
  • Thinking phone number is replaced
  • Misreading regex pattern
  • Assuming no replacement happens
4. You wrote this code to redact phone numbers:
import re
text = 'Call 555-1234 or 555-5678.'
redacted = re.sub(r'\d{3}-\d{4}', '<PHONE_REDACTED>', text)
print(redacted)

But the output is:
'Call 555-1234 or 555-5678.'
What is the likely error?
medium
A. The regex pattern is incorrect and does not match the phone numbers
B. The re.sub function is missing the text argument
C. The print statement is missing parentheses
D. The text variable is empty

Solution

  1. Step 1: Check regex pattern against phone format

    The pattern '\d{3}-\d{4}' matches numbers like '555-1234', but the phone numbers might have different formats or extra spaces.
  2. Step 2: Confirm if pattern matches text

    If the phone numbers have area codes or spaces, the pattern won't match, so no replacement occurs.
  3. Final Answer:

    The regex pattern is incorrect and does not match the phone numbers -> Option A
  4. Quick Check:

    Regex mismatch causes no replacement [OK]
Hint: Check regex matches exact phone format in text [OK]
Common Mistakes:
  • Assuming re.sub syntax error
  • Forgetting parentheses in print (Python 3+)
  • Thinking text is empty without checking
5. You want to redact both emails and phone numbers in a text using Python. Which combined regex pattern correctly matches emails and US phone numbers like '123-456-7890'?
hard
A. r'\d{3}-\d{4}|\S+@\S+\.\S+'
B. r'\S+@\S+\.\S+|\d{3}-\d{3}-\d{4}'
C. r'\S+@\S+\.\S+\d{3}-\d{3}-\d{4}'
D. r'\S+@\S+\.\S+&\d{3}-\d{3}-\d{4}'

Solution

  1. Step 1: Understand regex for emails and phones

    The email pattern '\S+@\S+\.\S+' matches emails; '\d{3}-\d{3}-\d{4}' matches US phone numbers like '123-456-7890'.
  2. Step 2: Combine patterns with OR operator

    Using '|' between patterns matches either emails or phone numbers separately.
  3. Step 3: Evaluate options

    r'\S+@\S+\.\S+|\d{3}-\d{3}-\d{4}' correctly uses '|' to combine patterns; r'\d{3}-\d{4}|\S+@\S+\.\S+' reverses order but still works; r'\S+@\S+\.\S+\d{3}-\d{3}-\d{4}' concatenates patterns (wrong); r'\S+@\S+\.\S+&\d{3}-\d{3}-\d{4}' uses '&' which is invalid in regex.
  4. Final Answer:

    r'\S+@\S+\.\S+|\d{3}-\d{3}-\d{4}' -> Option B
  5. Quick Check:

    Use '|' to combine regex patterns [OK]
Hint: Use '|' to combine email and phone regex patterns [OK]
Common Mistakes:
  • Concatenating patterns without '|'
  • Using invalid regex operators like '&'
  • Mixing order but forgetting OR operator