# Install required packages (no fragile extras: active learning and weak supervision are written by hand)
!pip install -q scikit-learn pandas numpy matplotlib seaborn
!pip install -q cleanlab
!pip install -q google-genai # For Gemini APIWeek 4 Lab: Optimizing the Labeling Process
CS 203: Software Tools and Techniques for AI
IIT Gandhinagar
Learning Objectives
By the end of this lab, you will be able to:
- Implement Active Learning with uncertainty sampling from scratch (numpy + scikit-learn)
- Write and apply labeling functions for Weak Supervision, and combine them with majority and accuracy-weighted votes
- Use LLMs (like Gemini) to generate labels programmatically
- Detect and handle noisy labels with cleanlab
- Compare the cost and quality trade-offs of different labeling approaches
Netflix Movie Theme
We need to label 100,000 movie reviews for sentiment analysis. Manual labeling would cost $30,000 and take months. Let’s use smarter approaches!
Part 1: Environment Setup
# Import libraries
import re
import json
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, classification_report
np.random.seed(42)
print("All imports successful!")Part 2: Create Movie Review Dataset
# Create a synthetic movie review dataset with plenty of variety:
# 1-3 opinions per review about random aspects, random adjectives and intensifiers,
# some negations ("the plot was not dull"), mixed reviews ("..., but the ending was flat"),
# and ~3% annotator mistakes in the given label.
rng = np.random.default_rng(42)
movies = ['Inception', 'The Matrix', 'Avatar', 'Titanic', 'Interstellar', 'The Godfather',
'Pulp Fiction', 'Parasite', 'Joker', 'Gladiator', 'Dune', 'Oppenheimer',
'RRR', 'Lagaan', 'Dangal', '3 Idiots']
aspects = ['acting', 'plot', 'script', 'soundtrack', 'cinematography', 'pacing', 'dialogue',
'ending', 'visual effects', 'direction', 'characters', 'editing', 'humour', 'climax']
pos_adj = ['brilliant', 'superb', 'gripping', 'moving', 'stunning', 'clever',
'delightful', 'memorable', 'well-crafted', 'charming', 'powerful', 'fresh']
neg_adj = ['dull', 'clumsy', 'tedious', 'forgettable', 'messy', 'lifeless',
'predictable', 'shallow', 'bland', 'confusing', 'weak', 'flat']
openers = ['', '', 'Watched {movie} last night. ', 'Saw {movie} with friends. ',
'Finally caught {movie}. ', 'So, {movie}. ']
intensifiers = ['', '', 'really ', 'quite ', 'very ', 'somewhat ']
def make_clause(mood):
"""One opinion about one aspect; it usually (80%) agrees with the review's overall mood."""
aspect = rng.choice(aspects)
verb = 'were' if aspect in ('characters', 'visual effects') else 'was'
polarity = mood if rng.random() < 0.8 else -mood
if rng.random() < 0.1: # negation: "not dull" is a positive opinion
adj = rng.choice(neg_adj if polarity == 1 else pos_adj)
return f"the {aspect} {verb} not {adj}", polarity
adj = rng.choice(pos_adj if polarity == 1 else neg_adj)
return f"the {aspect} {verb} {rng.choice(intensifiers)}{adj}", polarity
def make_review():
mood = rng.choice([1, -1])
n_clauses = rng.choice([1, 2, 3], p=[0.3, 0.4, 0.3])
parts, score = [], 0.0
for j in range(n_clauses):
text, polarity = make_clause(mood)
score += (1 + 0.5 * j) * polarity # later opinions count more ("..., but ...")
parts.append(text.capitalize() if j == 0 else rng.choice([', and ', ', but ', '; ']) + text)
opener = rng.choice(openers).format(movie=rng.choice(movies))
return opener + ''.join(parts) + '.', int(score > 0)
def generate_reviews(n_samples=3000, noise_rate=0.03):
df = pd.DataFrame([make_review() for _ in range(n_samples)], columns=['review', 'true_label'])
flip = rng.random(n_samples) < noise_rate # annotators make mistakes
df['label'] = np.where(flip, 1 - df['true_label'], df['true_label'])
return df
# Generate dataset (label: 1 = positive, 0 = negative)
df = generate_reviews(n_samples=3000)
print(f"Generated {len(df)} reviews ({df['review'].nunique()} unique texts)")
print(f"\nLabel distribution:")
print(df['label'].value_counts())
print(f"\nSample reviews:")
df.head()# Binary classification: positive (1) vs negative (0)
df_binary = df.copy()
print(f"Binary dataset size: {len(df_binary)}")
# Split the TEXT first, so the test set never influences the features
train_df, test_df = train_test_split(df_binary, test_size=0.2, random_state=42,
stratify=df_binary['label'])
# Fit TF-IDF on the training pool only (it uses no labels), then just transform the test set
vectorizer = TfidfVectorizer(ngram_range=(1, 2), min_df=2)
X_pool = vectorizer.fit_transform(train_df['review'])
X_test = vectorizer.transform(test_df['review'])
y_pool = train_df['label'].values # the "annotator" labels we can ask for
y_test = test_df['true_label'].values # a carefully checked gold test set
print(f"Pool size: {X_pool.shape[0]}")
print(f"Test size: {X_test.shape[0]}")
full = LogisticRegression(C=10, max_iter=1000).fit(X_pool, y_pool)
print(f"Reference: accuracy with ALL {X_pool.shape[0]} pool labels = {full.score(X_test, y_test):.2%}")Part 3: Active Learning from Scratch
3.1 The Active Learning Loop
No special library is needed. An active learner is just: train → score the unlabeled pool → pick the most uncertain → ask a human for those labels → repeat.
# Start with a small seed set (simulating initial labeled data): 10 positive + 10 negative
n_initial = 20
seed_rng = np.random.default_rng(0)
initial_idx = np.concatenate([
seed_rng.choice(np.where(y_pool == c)[0], size=n_initial // 2, replace=False) for c in (0, 1)
])
print(f"Initial labeled set: {len(initial_idx)}")
print(f"Remaining pool: {X_pool.shape[0] - len(initial_idx)}")Question 3.1 (Solved): Uncertainty Sampling and an Initial Model
# SOLVED: Query strategy + initial model
def make_model():
return LogisticRegression(C=10, max_iter=1000)
def uncertainty_sampling(model, X_unlabeled, n_instances=1):
"""Least-confidence sampling: pick the rows whose top class probability is lowest."""
probs = model.predict_proba(X_unlabeled)
uncertainty = 1 - probs.max(axis=1)
return np.argsort(-uncertainty)[:n_instances] # positions in X_unlabeled
# Check initial performance
model = make_model().fit(X_pool[initial_idx], y_pool[initial_idx])
initial_accuracy = model.score(X_test, y_test)
print(f"Initial accuracy with {n_initial} samples: {initial_accuracy:.2%}")Question 3.2 (Solved): Run Active Learning Loop
# SOLVED: Active Learning Loop
def run_active_learning(query_fn, n_rounds=30, batch_size=10):
"""Train, let query_fn pick batch_size examples, reveal their labels, repeat.
Returns the number of labels and the test accuracy after every round."""
labeled = list(initial_idx)
unlabeled = np.setdiff1d(np.arange(X_pool.shape[0]), labeled)
n_labels, accuracies = [], []
for r in range(n_rounds + 1):
model = make_model().fit(X_pool[labeled], y_pool[labeled])
n_labels.append(len(labeled))
accuracies.append(model.score(X_test, y_test))
if r == n_rounds:
break
picked = query_fn(model, X_pool[unlabeled], batch_size) # positions in `unlabeled`
labeled += list(unlabeled[picked]) # the "human" labels these rows
unlabeled = np.delete(unlabeled, picked)
return n_labels, accuracies
n_labels_al, acc_al = run_active_learning(uncertainty_sampling)
for n, acc in list(zip(n_labels_al, acc_al))[::5]:
print(f"{n:4d} labels: Accuracy = {acc:.2%}")
print(f"\nFinal accuracy: {acc_al[-1]:.2%} with {n_labels_al[-1]} labels")Question 3.3: Compare with Random Sampling
# TODO: Implement random sampling baseline and compare with active learning
# It must have the same signature as uncertainty_sampling, so it plugs into run_active_learning.
def random_sampling(model, X_unlabeled, n_instances=1):
"""Random query strategy for baseline comparison (ignores the model)."""
# Your code here
pass
# Run random sampling loop and collect performance:
# n_labels_rand, acc_rand = run_active_learning(random_sampling)
# Your code hereQuestion 3.4: Plot Learning Curves
# TODO: Plot learning curves for Active Learning vs Random Sampling
# X-axis: Number of labeled samples (n_labels_al)
# Y-axis: Test accuracy (acc_al vs acc_rand)
# Tip: random sampling is noisy; average acc_rand over a few random seeds for a fair comparison
# Your code hereQuestion 3.5: Try Different Query Strategies
Compare uncertainty sampling, margin sampling, and entropy sampling.
# TODO: Compare different query strategies
# Write margin_sampling and entropy_sampling with the same signature as uncertainty_sampling:
# margin: smallest gap between the top-2 class probabilities
# entropy: largest -sum(p * log2(p))
# Run run_active_learning() with each and plot all three on the same graph.
# Question: with only 2 classes, all three pick the same examples. Why?
# Your code herePart 4: Weak Supervision from Scratch
4.1 Understanding Labeling Functions
A labeling function (LF) is just a Python function: one review in, POSITIVE / NEGATIVE / ABSTAIN out.
# Constants for labels
POSITIVE = 1
NEGATIVE = 0
ABSTAIN = -1
# Weak supervision works on raw text. Use the training pool and pretend its labels are unknown.
# (Row i of df_ws is row i of X_pool.)
df_ws = train_df.reset_index(drop=True)
print(f"Dataset size: {len(df_ws)}")
df_ws.head()Question 4.1 (Solved): Write Labeling Functions
# SOLVED: Labeling Functions for Sentiment Analysis
def lf_brilliant_superb(text):
"""'brilliant' or 'superb' -> positive."""
return POSITIVE if re.search(r'\b(brilliant|superb)\b', text.lower()) else ABSTAIN
def lf_dull_tedious(text):
"""'dull' or 'tedious' -> negative."""
return NEGATIVE if re.search(r'\b(dull|tedious)\b', text.lower()) else ABSTAIN
def lf_stunning_gripping(text):
"""'stunning' or 'gripping' -> positive."""
return POSITIVE if re.search(r'\b(stunning|gripping)\b', text.lower()) else ABSTAIN
def lf_forgettable_lifeless(text):
"""'forgettable' or 'lifeless' -> negative."""
return NEGATIVE if re.search(r'\b(forgettable|lifeless)\b', text.lower()) else ABSTAIN
def lf_moving_memorable(text):
"""'moving' or 'memorable' -> positive."""
return POSITIVE if re.search(r'\b(moving|memorable)\b', text.lower()) else ABSTAIN
def lf_messy_clumsy(text):
"""'messy' or 'clumsy' -> negative."""
return NEGATIVE if re.search(r'\b(messy|clumsy)\b', text.lower()) else ABSTAIN
def lf_negated_praise(text):
"""'not brilliant', 'not gripping', ... -> negative."""
return NEGATIVE if re.search(r'\bnot (' + '|'.join(pos_adj) + r')\b', text.lower()) else ABSTAIN
def lf_after_but(text):
"""The opinion after ', but' usually decides the review."""
if ', but ' not in text:
return ABSTAIN
after = text.lower().split(', but ')[-1]
if ' not ' in after:
return ABSTAIN
if any(w in after for w in pos_adj):
return POSITIVE
if any(w in after for w in neg_adj):
return NEGATIVE
return ABSTAIN
# Collect all LFs
lfs = [
lf_brilliant_superb, lf_dull_tedious, lf_stunning_gripping,
lf_forgettable_lifeless, lf_moving_memorable, lf_messy_clumsy,
lf_negated_praise, lf_after_but
]
print(f"Created {len(lfs)} labeling functions")Question 4.2: Apply Labeling Functions
# Apply every LF to every review -> label matrix L (rows = reviews, columns = LFs)
def apply_lfs(lfs, texts):
return np.array([[lf(t) for lf in lfs] for t in texts])
L_train = apply_lfs(lfs, df_ws['review'])
print(f"Label matrix shape: {L_train.shape}")
print(f"Labels (first 5 rows):\n{L_train[:5]}")Question 4.3 (Solved): Analyze Labeling Functions
# SOLVED: Analyze LF performance (what Snorkel's LFAnalysis reports, in a few lines)
def lf_summary(L, lfs, y=None):
fires = L != ABSTAIN
rows = []
for j, lf in enumerate(lfs):
others = np.delete(L, j, axis=1)
others_fire = others != ABSTAIN
row = {
'lf': lf.__name__,
'coverage': fires[:, j].mean(), # how often it votes
'overlaps': (fires[:, j] & others_fire.any(axis=1)).mean(), # another LF also votes
'conflicts': (fires[:, j] & (others_fire & (others != L[:, [j]])).any(axis=1)).mean(),
}
if y is not None: # only possible here because we secretly know the labels
row['emp_accuracy'] = (L[fires[:, j], j] == y[fires[:, j]]).mean()
rows.append(row)
return pd.DataFrame(rows).set_index('lf').round(3)
analysis = lf_summary(L_train, lfs, y=df_ws['label'].values)
print("Labeling Function Analysis:")
analysisQuestion 4.4: Combine the LFs (Label Model)
# Label model 1 (SOLVED): majority vote over the LFs that fired
def majority_vote(L):
"""1 or 0 per row; ABSTAIN if no LF fired or the vote is tied."""
n_pos = (L == POSITIVE).sum(axis=1)
n_neg = (L == NEGATIVE).sum(axis=1)
return np.where(n_pos > n_neg, POSITIVE, np.where(n_neg > n_pos, NEGATIVE, ABSTAIN))
mv = majority_vote(L_train)
covered = mv != ABSTAIN
print(f"Majority vote: coverage {covered.mean():.1%}, "
f"accuracy on covered rows {(mv[covered] == df_ws['label'].values[covered]).mean():.1%}")
# TODO: Label model 2: accuracy-weighted vote (from the lecture)
# 1. Estimate each LF's accuracy alpha_j. Pretend you hand-labeled a small dev set of 300 reviews:
# dev = np.arange(300); for LF j, compare L_train[dev, j] with df_ws['label'].values[dev] where it fired
# 2. Weight w_j = log(alpha_j / (1 - alpha_j)) (clip alpha_j to [0.55, 0.95] first: small dev sets are noisy)
# 3. For each review: S_pos = sum of w_j over LFs voting POS, S_neg = same for NEG
# P(POS) = 1 / (1 + exp(-(S_pos - S_neg))) # a sigmoid
# 4. Compare accuracy and coverage with majority vote
def weighted_vote_proba(L, alphas):
"""Return P(POS) for every row (0.5 where no LF fired)."""
# Your code here
passQuestion 4.5: Write More Labeling Functions
Create 3 additional labeling functions to improve coverage.
# TODO: Write 3 more labeling functions
# Consider: word patterns, punctuation, sentence structure
def lf_your_function_1(text):
"""Description"""
# Your code here
return ABSTAIN
def lf_your_function_2(text):
"""Description"""
# Your code here
return ABSTAIN
def lf_your_function_3(text):
"""Description"""
# Your code here
return ABSTAINQuestion 4.6: Train Downstream Model with Weak Labels
# TODO: Train a classifier using the weak labels from your label model
# Compare performance with a model trained on true labels (y_pool). Evaluate on X_test, y_test.
#
# Option A (hard labels): keep rows where majority_vote(L_train) != ABSTAIN and train on those labels
# Option B (soft labels, as in the lecture): p = weighted_vote_proba(L_train, alphas); add every row
# twice, as POS with sample_weight p and as NEG with sample_weight 1 - p:
# from scipy.sparse import vstack
# n = X_pool.shape[0]
# make_model().fit(vstack([X_pool, X_pool]), np.r_[np.ones(n), np.zeros(n)], sample_weight=np.r_[p, 1 - p])
# Your code herePart 5: LLM-Based Labeling
5.1 Setting Up Gemini API
import os
MODEL = "gemini-flash-latest"
# API key: set GEMINI_API_KEY in your environment, or on Colab add it under Secrets (key icon).
# Never paste the key into the notebook.
try:
from google.colab import userdata
os.environ.setdefault('GEMINI_API_KEY', userdata.get('GEMINI_API_KEY'))
except Exception:
pass # not on Colab, or the secret is not set
client = None
try:
from google import genai
client = genai.Client() # reads GEMINI_API_KEY from the environment
print("Gemini client initialized!")
except Exception as e:
print(f"Error: {e}")
print("Set GEMINI_API_KEY to use LLM labeling (the mock labeler below works without it)")Question 5.1 (Solved): Create LLM Labeling Function
# SOLVED: LLM Labeling Function (falls back to a keyword mock when no API key is set)
def label_with_llm(review, use_api=False):
"""
Label a movie review using an LLM.
Args:
review: The review text
use_api: If True, call the actual API; else use the mock
Returns:
dict with 'label' and 'confidence'
"""
if use_api and client is not None:
prompt = f"""
Classify the following movie review as POSITIVE or NEGATIVE.
Review: "{review}"
Respond with JSON format:
{{"label": "POSITIVE" or "NEGATIVE", "confidence": 0.0-1.0}}
"""
response = client.models.generate_content(
model=MODEL,
contents=prompt,
config={"response_mime_type": "application/json"},
)
return json.loads(response.text)
else:
# Mock implementation based on keywords (ignores negation, so it makes mistakes)
words = re.findall(r"[a-z-]+", review.lower())
pos_count = sum(w in pos_adj for w in words)
neg_count = sum(w in neg_adj for w in words)
confidence = min(0.5 + 0.2 * abs(pos_count - neg_count), 0.95)
if pos_count > neg_count:
return {'label': 'POSITIVE', 'confidence': confidence}
elif neg_count > pos_count:
return {'label': 'NEGATIVE', 'confidence': confidence}
else:
return {'label': 'POSITIVE', 'confidence': 0.5} # Default
# Test
test_review = "The acting was brilliant, and the soundtrack was really moving."
result = label_with_llm(test_review)
print(f"Review: {test_review}")
print(f"Label: {result['label']}, Confidence: {result['confidence']:.2f}")Question 5.2: Batch Label with LLM
# TODO: Label a batch of reviews using the LLM function
# Track time and estimated cost
sample_reviews = df_binary['review'].head(20).tolist()
# Your code hereQuestion 5.3: Evaluate LLM Labels Against Ground Truth
# TODO: Calculate accuracy, precision, recall of LLM labels
# Compare with human labels (ground truth)
# Your code hereQuestion 5.4: Hybrid Labeling Strategy
# TODO: Implement hybrid labeling
# - Use LLM for high-confidence labels
# - Send low-confidence examples to human review
def hybrid_labeling(reviews, confidence_threshold=0.8):
"""
Label reviews using hybrid approach.
Returns:
llm_labeled: Reviews labeled by LLM
human_queue: Reviews needing human review
"""
# Your code here
passPart 6: Noisy Label Detection with cleanlab
6.1 Setting Up cleanlab
from cleanlab.filter import find_label_issues # plain `pip install cleanlab` is enough
from sklearn.model_selection import cross_val_predict
from sklearn.pipeline import make_pipeline
# Use the training-pool texts and flip 10% MORE labels to simulate a sloppy annotator
texts_noisy = train_df['review'].values
y_noisy = train_df['label'].values.copy() # note: already contains ~3% natural annotator mistakes
noise_idx = np.random.default_rng(1).choice(len(y_noisy), size=int(0.1 * len(y_noisy)), replace=False)
y_noisy[noise_idx] = 1 - y_noisy[noise_idx] # Flip labels
print(f"Added noise to {len(noise_idx)} labels ({len(noise_idx)/len(y_noisy):.1%})")Question 6.1 (Solved): Find Label Issues
# SOLVED: Use cleanlab to find label issues
# Out-of-fold predictions: each review is scored by a model that never saw its (maybe wrong) label.
# The pipeline refits TF-IDF inside every fold, so nothing leaks across folds.
clf = make_pipeline(TfidfVectorizer(ngram_range=(1, 2), min_df=2),
LogisticRegression(C=10, max_iter=1000))
pred_probs = cross_val_predict(clf, texts_noisy, y_noisy, cv=5, method='predict_proba')
# Find label issues: returns a BOOLEAN mask with one entry per review
is_issue = find_label_issues(labels=y_noisy, pred_probs=pred_probs)
print(f"Flagged {is_issue.sum()} reviews ({is_issue.mean():.1%}) as likely label errors")Question 6.2: Analyze Detected Issues
# Look at the flagged reviews: given label vs the model's out-of-fold confidence
issues = pd.DataFrame({'review': texts_noisy, 'given_label': y_noisy,
'p_positive': pred_probs[:, 1].round(2), 'is_label_issue': is_issue})
print("\nLabel Issues:")
print(f"Found {is_issue.sum()} potential label errors")
print(issues[issues['is_label_issue']].head(10).to_string())
# TODO: Calculate precision/recall of cleanlab's detection
# How many of the actual noisy labels (noise_idx) did it find?
# How many false positives? (Some may be the ~3% natural mistakes: compare with train_df['true_label'])
# Your code hereQuestion 6.3: Train on Clean Data
# TODO: Compare model performance (evaluate with clf.score(test_df['review'], y_test)):
# 1. Trained on all data (with noise): texts_noisy, y_noisy
# 2. Trained on clean data: drop detected issues with the BOOLEAN mask
# texts_noisy[~is_issue], y_noisy[~is_issue]
# 3. Trained on true clean data (oracle): texts_noisy, train_df['true_label'].values
# Your code herePart 7: Cost Comparison
Question 7.1: Calculate Labeling Costs
# Calculate and compare costs of different approaches
def calculate_costs(n_items, method):
"""
Calculate estimated cost for different labeling methods.
Args:
n_items: Number of items to label
method: 'manual', 'active_learning', 'weak_supervision', 'llm', 'hybrid'
Returns:
dict with cost, time, quality estimates
"""
costs = {
'manual': {
'cost_per_item': 0.30, # USD
'time_per_item': 0.1, # minutes
'quality': 0.95, # accuracy
'items_needed': n_items
},
'active_learning': {
'cost_per_item': 0.30,
'time_per_item': 0.1,
'quality': 0.90,
'items_needed': n_items // 3 # 3x reduction
},
'weak_supervision': {
'cost_per_item': 0.0, # Just engineer time
'setup_cost': 500, # Writing LFs
'time_per_item': 0.0,
'quality': 0.80,
'items_needed': 0
},
'llm': {
'cost_per_item': 0.0001, # API cost: small LLM, ~100-token review (Nov 2026; check pricing pages)
'time_per_item': 0.01, # minutes
'quality': 0.85,
'items_needed': n_items
},
'hybrid': {
'cost_per_item': 0.05, # Average
'time_per_item': 0.02,
'quality': 0.90,
'items_needed': n_items
}
}
method_info = costs[method]
total_cost = method_info['cost_per_item'] * method_info['items_needed']
if 'setup_cost' in method_info:
total_cost += method_info['setup_cost']
total_time = method_info['time_per_item'] * method_info['items_needed']
return {
'method': method,
'total_cost': total_cost,
'total_time_hours': total_time / 60,
'expected_quality': method_info['quality']
}
# Compare all methods for 100,000 items
n_items = 100000
methods = ['manual', 'active_learning', 'weak_supervision', 'llm', 'hybrid']
print(f"Cost comparison for {n_items:,} items:\n")
print(f"{'Method':<20} {'Cost ($)':<12} {'Time (hrs)':<12} {'Quality':<10}")
print("-" * 54)
for method in methods:
result = calculate_costs(n_items, method)
print(f"{result['method']:<20} ${result['total_cost']:>10,.2f} {result['total_time_hours']:>10,.1f} {result['expected_quality']:>8.0%}")Challenge Problems
Challenge 1: Batch Active Learning
# Challenge: Implement batch active learning with diversity
# Query 10 samples at a time, ensuring diversity using clustering
from sklearn.cluster import KMeans
def diversity_uncertainty_sampling(classifier, X_pool, n_instances=10):
"""
Select n_instances that are both uncertain AND diverse.
Strategy:
1. Get uncertainty scores for all samples
2. Cluster samples into n_instances clusters
3. Pick most uncertain sample from each cluster
"""
# Your code here
passChallenge 2: Combine All Methods
# Challenge: Build a complete labeling pipeline that:
# 1. Uses weak supervision for initial bulk labels
# 2. Uses LLM to label uncertain examples
# 3. Uses active learning for remaining hard cases
# 4. Uses cleanlab to detect and fix errors
class SmartLabelingPipeline:
def __init__(self, labeling_functions, llm_client=None, confidence_threshold=0.8):
self.lfs = labeling_functions
self.llm_client = llm_client
self.threshold = confidence_threshold
def label(self, data):
"""
Label data using the hybrid pipeline.
Returns:
labels: Final labels
sources: Source of each label (weak/llm/human)
confidence: Confidence scores
"""
# Your code here
passChallenge 3: Active Learning with Human-in-the-Loop UI
# Challenge: Create an interactive labeling interface
# Use ipywidgets to create a simple annotation UI
try:
import ipywidgets as widgets
from IPython.display import display, clear_output
# Create interactive labeling widget
# Your code here
except ImportError:
print("Install ipywidgets for interactive labeling: pip install ipywidgets")Summary
In this lab, you learned:
- Active Learning: Query strategies (uncertainty, margin, entropy) to label smarter
- Weak Supervision: Writing labeling functions to generate noisy but cheap labels
- LLM Labeling: Using GPT/Gemini as automated annotators
- Noisy Label Detection: Using cleanlab to find and fix label errors
- Cost Comparison: Trade-offs between different labeling approaches
Key Takeaways
| Method | Best When | Typical Savings |
|---|---|---|
| Active Learning | Limited budget | 2-10x |
| Weak Supervision | Patterns exist | 10-100x |
| LLM Labeling | Well-defined task | 10-50x |
| Hybrid | Large scale projects | 5-20x |
Next Week
Week 5: Data Augmentation - Create more training data without any labeling!