Objectives: LO-5.1, LO-5.2, LO-5.3
Prerequisites: the Module 5 reading and Lab 4
Time: about 2.5 hours
In this lab you treat the shop’s 24 labeled tickets as a pool of examples. You put examples in their own tagged section, audit the pool’s labels and lengths, and turn tickets into word sets. Then you rank the pool by Jaccard similarity to a new ticket, and compare the nearest examples with a fixed, balanced set by the labels each covers.
The tickets come from data/tickets.json. No cell sends anything over the network or calls a
model.
Use a fresh kernel and run the cells from top to bottom. Fill each answer cell, then run its
check, which prints passed or fails with a message that says what is wrong. The checks fail
on purpose until their exercises are complete.
Setup¶
import sys
import re
from collections import Counter
from xml.etree import ElementTree
from promptlab import load_json
pool = load_json("tickets.json")
print("Python", sys.version.split()[0])Contrast cases¶
The same word can appear in tickets for different queues. This cell prints every ticket that contains “brake”, with its label: the word appears in both repair and billing tickets.
print([(row["text"], row["label"]) for row in pool if "brake" in row["text"].lower()][:4])Exercise L5.1 (LO-5.1, ★★, about 25 minutes)¶
Put examples in their own section. Write examples_xml(rows), which returns XML with an
examples root element. For each row, add an example element containing an input element,
with the ticket’s text, and an output element. The output uses Label: <queue>. Write your
own contrast pair in your notes before checking.
def examples_xml(rows):
raise NotImplementedError("L5.1")tree = ElementTree.fromstring(examples_xml([pool[0], pool[13]]))
assert tree.tag == "examples", f"Name the root element examples, not {tree.tag!r}."
assert [e.tag for e in tree] == ["example", "example"], \
f"Add one example element per row; got {[e.tag for e in tree]}."
assert [e.findtext("output") for e in tree] == ["Label: repair", "Label: billing"], \
"Write each output as 'Label: ' and the row's label."
assert [e.findtext("input") for e in tree] == [pool[0]["text"], pool[13]["text"]], \
"Put each row's exact text in its input element."
print("passed")Exercise L5.2 (LO-5.2, ★★, about 25 minutes)¶
Audit labels and lengths. Write coverage(rows), which returns two dictionaries: the count
of each label, and the count of "short" and "long" examples. Split each text on whitespace.
A short example has at most nine words. Compare the first four rows with the full pool, and
identify the missing queues.
def coverage(rows):
raise NotImplementedError("L5.2")labels, lengths = coverage(pool)
assert labels == {"repair": 8, "billing": 8, "account": 8}, f"Got label counts {labels}."
assert lengths["short"] + lengths["long"] == 24, "Count every row as short or long."
assert {size: n for size, n in lengths.items() if n} == {"short": 23, "long": 1}, \
f"Got {lengths}: a short text has at most nine words, so nine words is still short."
first_four = {label: n for label, n in coverage(pool[:4])[0].items() if n}
assert first_four == {"repair": 4}, f"The first four rows are all repair; got {first_four}."
print("passed")Exercise L5.3 (LO-5.3, ★★, about 25 minutes)¶
Tokenize into word sets. Write words(text), which returns the set of lowercased
alphabetic runs matched by the regular expression [a-z]+. Keep unique words only.
def words(text):
raise NotImplementedError("L5.3")assert words("Brake, BRAKE! Pad") == {"brake", "pad"}, \
f"Got {words('Brake, BRAKE! Pad')!r}: lowercase first, and return a set of unique words."
assert words("$20") == set(), f"Digits and symbols aren't words; got {words('$20')!r}."
print("passed")Exercise L5.4 (LO-5.3, LO-5.2, ★★, about 25 minutes)¶
Compare fixed and dynamic selections. Write pick(text, rows, k), which ranks rows by the
Jaccard similarity of their word sets to the word set of text, and returns the first k
rows. Break ties by ascending ID. If both sets are empty, score zero. Raise ValueError when
k is outside the available range. Compare the label counts of the dynamic results with a
hand-picked balanced set for three new queries. Hold the prompt template constant when you
compare selections.
def pick(text, rows, k):
raise NotImplementedError("L5.4")query = "How do I update the email on my profile?"
nearest = pick(query, pool, 3)
assert nearest[0]["id"] == "T17", \
f"T17 has exactly the query's words, so it ranks first; got {nearest[0]['id']}."
assert pick("", pool[:3][::-1], 2) == pool[:2], \
"With every score 0, break ties by ascending ID: T01, then T02."
for k in (-1, len(pool) + 1):
try:
pick(query, pool, k)
except ValueError:
pass
else:
raise AssertionError(f"k={k} doesn't fit a pool of {len(pool)} rows: raise ValueError.")
print("Fixed set:", coverage([pool[0], pool[8], pool[16]])[0])
print("Nearest set:", coverage(nearest)[0])
print("passed")Summary¶
You built and inspected a pool of examples. The nearest examples and a balanced set serve different aims: the first finds tickets that look like the input, and the second shows every label.