Module 6 of 6 · 50 minutes

NLP in practice

Real NLP systems discover themes, feed dashboards and handle personal data. This module brings it together responsibly.

By · Last updated

Learning objectives

  • Discover topics with NMF and name them
  • Track predicted categories over time
  • Redact personal data before analysis
  • Plan evaluation, routing and monitoring for production NLP
  • Choose a sample size for checking accuracy
  • Detect language drift from the share of unseen words
Setup: the data and models from earlier modules (runs automatically when you press Run on any cell)
Python · setupimport random
import re
import numpy as np
import pandas as pd

random.seed(7)
templates = {
    "delivery": ["My parcel arrived {d} days late and the box was crushed",
                 "Delivery took {d} days and the courier left it in the rain",
                 "Still waiting for my order after {d} days, no update",
                 "The tracking link never updated and delivery was {d} days late"],
    "product":  ["The {p} broke after a week",
                 "Love the {p}, great quality and well made",
                 "The {p} is much smaller than the photos suggest",
                 "Excellent {p}, works perfectly"],
    "billing":  ["I was charged twice for order {o}",
                 "Refund for order {o} still not received",
                 "The discount code did not apply at checkout",
                 "Invoice for order {o} shows the wrong amount"],
}
products = ["chopping board", "kettle", "desk lamp", "backpack", "water bottle"]
rows = []
for i in range(400):
    cat = random.choice(list(templates))
    msg = random.choice(templates[cat]).format(
        d=random.randint(2, 9), p=random.choice(products), o="GFY-%05d" % random.randint(10000, 99999))
    label = cat if random.random() > 0.08 else random.choice(list(templates))  # ~8% noisy labels
    rows.append({"text": msg, "category": label})
messages = pd.DataFrame(rows)

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LogisticRegression

X_train, X_test, y_train, y_test = train_test_split(
    messages["text"], messages["category"], test_size=0.25, random_state=0, stratify=messages["category"])
clf = make_pipeline(TfidfVectorizer(ngram_range=(1, 2), min_df=2, sublinear_tf=True),
                    LogisticRegression(max_iter=1000))
clf.fit(X_train, y_train)

def route(texts, threshold=0.7):
    probs = clf.predict_proba(texts)
    out = pd.DataFrame({"text": list(texts),
                        "predicted": clf.classes_[probs.argmax(axis=1)],
                        "confidence": probs.max(axis=1).round(2)})
    out["needs_review"] = out["confidence"] < threshold
    return out

6.1 Discovering topics without labels

When you don't know the categories in advance — open-ended survey comments, for example — topic modelling groups words that tend to appear together. Non-negative matrix factorisation (NMF) on TF-IDF is a simple, effective method:

from sklearn.decomposition import NMF

topic_vec = TfidfVectorizer(stop_words="english", min_df=3)
Xt = topic_vec.fit_transform(messages["text"])
nmf = NMF(n_components=3, random_state=0, max_iter=500).fit(Xt)
terms = topic_vec.get_feature_names_out()
for i, comp in enumerate(nmf.components_):
    print(f"Topic {i}:", ", ".join(terms[comp.argsort()[-6:][::-1]]))

Topics are lists of words that a human must interpret and name. Clustering embeddings (Module 3) is a modern alternative, and an LLM can suggest names for each cluster — which a person should then check.

Compare the three word lists with the three categories you know are in the data. They don't line up neatly: billing gets a topic, delivery is split across two, and product reviews get none. Change n_components to 4 or 5 and run it again to see whether a product topic appears. There is no "correct" number of topics: you choose the level of detail that is useful, and the method will always return as many topics as you ask for, whether or not they mean anything.

Topic 0late, delivery,days, courierhuman names itDelivery delaysTopic 1order, refund,charged, invoicehuman names itBilling problemsTopic 2broke, quality,works, photoshuman names itProduct quality
Topic modelling finds groups of words that occur together. A person (or an LLM, checked by a person) turns them into meaningful names.

6.2 Tracking language over time

rng = np.random.default_rng(0)
messages["week"] = rng.integers(1, 9, len(messages))
messages["predicted"] = clf.predict(messages["text"])
trend = pd.crosstab(messages["week"], messages["predicted"], normalize="index").round(2)
trend["messages"] = messages["week"].value_counts().sort_index()
print(trend)

Dashboards of predicted categories or sentiment by week turn thousands of messages into a signal managers can act on — "billing complaints doubled after the price change". Always show volumes alongside percentages, and remember the model has errors of its own.

In this practice data the weeks were assigned at random, so the wobble you see from week to week is pure chance — with about 50 messages a week, shares move by several points for no reason at all. Keep that in mind before reporting a "trend" from a small weekly sample.

6.3 Personal data in text

Free text is full of personal data: names, emails, phone numbers, addresses, and sometimes health or financial details customers volunteer. Under data protection law (such as UK and EU GDPR), processing it needs a lawful basis, minimisation and security. Redact what you don't need before analysis or sending text to an external API:

def redact(text):
    text = re.sub(r"[\w.+-]+@[\w-]+\.[\w.]+", "[EMAIL]", text)
    text = re.sub(r"\b(?:\+44\s?7\d{3}|07\d{3})\s?\d{3}\s?\d{3}\b", "[PHONE]", text)
    return text

print(redact("Call me on 07700 900123 or email [email protected] about GFY-48213"))
print(redact("This is Sam Lee from 12 Mill Lane, my number is oh seven seven double-oh..."))

Regex redaction catches well-formed patterns but misses names and free-form details, as the second line shows: the name, the address and the spelled-out phone number all pass straight through. Dedicated PII-detection tools (and checking samples by hand) are needed for higher-risk data. See Responsible AI for the wider picture.

Call me on 07700 900123 or email [email protected] about GFY-48213redact()Call me on [PHONE] or email [EMAIL] about GFY-48213keep what the task needs (the order ID); remove what it doesn't
Redact personal data before analysis or before sending text to an external API.

6.4 Bias, language and fairness

  • Models trained mostly on standard English may perform worse on dialects, non-native writing or other languages — measure accuracy by group
  • Sentiment and toxicity models have been shown to score some identity terms as negative regardless of context
  • Keep a human route for customers whose messages the system misunderstands
  • Document intended use, languages covered and known weaknesses

6.5 Putting an NLP system into production

  • Evaluate on a held-out, hand-checked sample that reflects real traffic
  • Route low-confidence or high-risk cases to people
  • Monitor category mix, confidence and error rates — language drifts with new products, campaigns and slang
  • Re-label and retrain regularly; keep a log of label guideline changes
  • Protect personal data at every step, especially before calling external APIs

6.6 How big a sample do you need to check?

"Evaluate on a hand-checked sample" raises an obvious question: how many messages? The answer depends on how precisely you need to know the accuracy. If you check n messages and the system gets a share p right, the true accuracy is probably within the margin below:

Python · the margin of error on a measured accuracyp = 0.90                                   # accuracy you measured on the sample
for n in [20, 50, 100, 400, 1000]:
    margin = 1.96 * (p * (1 - p) / n) ** 0.5       # 95% margin of error
    print(f"checked {n:5} messages: accuracy {p:.0%} ± {margin:.1%}")

Twenty messages can't distinguish a system that is 77% accurate from one that is perfect. A few hundred gives a figure you can plan around. Halving the margin takes four times the sample, so decide how precise you need to be before you start checking — and choose the sample at random, not the first hundred in the file.

6.7 Noticing when the language changes

A classifier only knows the words it was trained on. When customers start writing about something new, it doesn't fail loudly; it quietly files the new messages under whatever category looks nearest. A simple early warning is the share of words the model has never seen.

Python · share of unseen words, this week against lastknown = set(clf.named_steps["tfidfvectorizer"].vocabulary_)
tokenise = clf.named_steps["tfidfvectorizer"].build_analyzer()

def unseen_share(texts):
    tokens = [t for text in texts for t in tokenise(text) if " " not in t]     # single words only
    return round(sum(t not in known for t in tokens) / len(tokens), 2)

usual = list(X_test.head(50))
new_product_week = usual[:35] + ["The air fryer basket coating is peeling",
                                 "Air fryer timer dial fell off",
                                 "My air fryer smells of burning plastic"] * 5

print("Usual week:      ", unseen_share(usual), "of words unseen")
print("New-product week:", unseen_share(new_product_week), "of words unseen")
print(route(["My air fryer smells of burning plastic"]).to_string(index=False))

In a usual week a few words are new, mostly order numbers. The week the air fryer launches, the share jumps. The last line shows why it matters: the model files a burning air fryer under delivery. Its confidence happens to be low enough here to send the message for review, but you can't rely on that: a new product described in familiar words would pass straight through. The jump in unseen words is the more dependable signal that it is time to label some of the new messages and retrain.

Exercise: a weekly insight brief

Combine what you've built: for the latest week in messages, report the number of messages, the share of each predicted category, the most common product mentioned (search for each name in products), and how many messages would need human review using route().

Your turn# Write your code here, then press Run
Show a solution
latest = messages[messages["week"] == messages["week"].max()]
print("Messages:", len(latest))
print(latest["predicted"].value_counts(normalize=True).round(2))
mentions = {p: int(latest["text"].str.contains(p, case=False).sum()) for p in products}
print("Most mentioned product:", max(mentions, key=mentions.get), mentions)
print("Needs review:", int(route(latest["text"])["needs_review"].sum()))
Exercise: redact postcodes too

Extend redaction to UK postcodes such as "SW1A 1AA" or "M1 1AE": one or two letters, a digit, an optional letter or digit, a space, then a digit and two letters. Write redact_more(text) that applies redact and then replaces postcodes with [POSTCODE]. Test it on the starter sentence.

Your turnsentence = "Deliver to M1 1AE not SW1A 1AA, and email [email protected] about GFY-48213"

# Write your code here, then press Run
Show a solution
sentence = "Deliver to M1 1AE not SW1A 1AA, and email [email protected] about GFY-48213"

def redact_more(text):
    text = redact(text)
    return re.sub(r"\b[A-Z]{1,2}\d[A-Z\d]?\s?\d[A-Z]{2}\b", "[POSTCODE]", text, flags=re.IGNORECASE)

print(redact_more(sentence))
# Order number GFY-48213 is untouched: it doesn't fit the postcode pattern.
# Always test a redaction rule on text it should NOT change as well as text it should.

Key takeaways

  • Topic models find word groups; humans name them.
  • Trends need volumes and known error rates.
  • Redact personal data you don't need — especially before external APIs.
  • Measure performance across dialects and languages.
  • Route low-confidence cases, monitor drift, retrain.
  • Twenty checked messages tell you little; a few hundred give a usable margin of error.
  • A rising share of unseen words is an early warning that the model needs new labels.