Sub topic 15
Building a simple rule-based intent classifier
This chapter turns the intent types from earlier chapters into a small Python program. The program labels a keyword using the words in the query. It is a first-pass tool for sorting long keyword lists. It does not replace the SERP check.
You should already know the four intent types and the wording signals for each. You should also be able to read simple Python: functions, lists, loops, and the re module.
What a rule-based classifier does
A rule-based classifier applies a fixed list of checks to a query. The first check that matches decides the label. If no check matches, the query gets the label unclear.
This approach has three useful properties:
- It is transparent. You can see which rule fired and fix it.
- It is cheap. It needs no training data, so it runs on thousands of keywords in seconds.
- It is predictable. The same query always gets the same label.
Its main weakness is that it only sees words. It cannot see what Google shows for the query, and that is the best evidence of intent. Treat its output as a draft label that you confirm for the keywords that matter.
The design
The classifier uses four word lists and one decision order.
| List | Intent it signals | Example terms |
|---|---|---|
| `COMMERCIAL` | commercial | best, review, vs, alternative |
| `TRANSACTIONAL` | transactional | buy, coupon, download, near me |
| `INFORMATIONAL` | informational | what, how, guide, tutorial |
| `brands` | navigational | slack, github |
The brand list is passed in as an argument because it differs for every project. The other lists are fixed.
The order of the checks matters because one query can contain terms from several lists. The code checks commercial first, then transactional, then informational, then brand names.
Brands come last because brand names are common inside other queries. "Slack vs Teams" is a comparison, not a search for the Slack site. If the brand check ran first, it would label that query navigational.
The code
Save this as intent_rules.py.
import re
COMMERCIAL = ["best", "top", "review", "reviews", "vs", "compare", "comparison", "alternative", "alternatives"]
TRANSACTIONAL = ["buy", "order", "coupon", "discount", "download", "sign up", "free trial", "near me"]
INFORMATIONAL = ["what", "why", "how", "guide", "tutorial", "examples", "meaning", "definition"]
def has_term(query, terms):
return any(re.search(r"\b" + re.escape(t) + r"\b", query) for t in terms)
def classify(query, brands):
q = query.lower().strip()
if has_term(q, COMMERCIAL):
return "commercial"
if has_term(q, TRANSACTIONAL):
return "transactional"
if has_term(q, INFORMATIONAL):
return "informational"
if has_term(q, brands):
return "navigational"
return "unclear"
if __name__ == "__main__":
brands = ["slack", "github"]
for q in [
"what is search intent",
"slack login",
"best project management software",
"buy standing desk",
"standing desk",
]:
print(q, "->", classify(q, brands))Running it prints:
what is search intent -> informational
slack login -> navigational
best project management software -> commercial
buy standing desk -> transactional
standing desk -> unclearWhy `has_term` uses word boundaries
The pattern \b marks a word boundary. Without it, a plain substring test would find top inside laptop and how inside showcase. Both would give wrong labels. With \b, only whole words match.
re.escape protects terms that contain regex characters. Multi-word terms such as sign up and near me work with this approach, because the boundaries sit at the start of the first word and the end of the last.
Why the query is lowercased
Searchers type in any case. Lowercasing once at the top means every list can be written in lowercase. The brand list must be lowercase too, or GitHub in your list would never match.
Measuring the classifier
A classifier you have not tested is a guess. Build a small labeled set where you set the label from the SERP check, not from the wording. Then compare the classifier against it.
from intent_rules import classify
BRANDS = ["slack", "github"]
LABELED = [
("what is search intent", "informational"),
("slack login", "navigational"),
("best project management software", "commercial"),
("buy standing desk", "transactional"),
("standing desk", "unclear"),
("best buy store hours", "navigational"),
("github pricing", "commercial"),
("how to cancel slack subscription", "informational"),
("slack vs microsoft teams", "commercial"),
("download github desktop", "transactional"),
]
correct = 0
for query, expected in LABELED:
predicted = classify(query, BRANDS)
if predicted == expected:
correct += 1
else:
print(f"MISS: {query!r} expected {expected}, got {predicted}")
print(f"accuracy: {correct}/{len(LABELED)} = {correct / len(LABELED):.2f}")Running it prints:
MISS: 'best buy store hours' expected navigational, got commercial
MISS: 'github pricing' expected commercial, got navigational
accuracy: 8/10 = 0.80The two misses show the typical failure modes.
- "best buy store hours" is a search for a retailer called Best Buy. The word
besttriggers the commercial rule. The fix is to put multi-word brand names into the brand list and check brands first for exact brand matches. - "github pricing" contains a brand, so the brand rule fires. The searcher is evaluating cost, which is commercial. The fix is to add
pricingandpricetoCOMMERCIAL.
Fixing one miss can break another case, so rerun the whole labeled set after every change. This is the same loop as a software test suite.
Limits you should expect
| Limit | Example | What happens |
|---|---|---|
| Rule order decides mixed queries | "how to buy a standing desk" | Labeled transactional because `buy` is checked before `how`. The SERP may show guides. |
| Words with several meanings | "best buy store hours" | The word `best` fires the commercial rule. |
| Brand names look like ordinary words | "apple pie recipe" | `apple` in a brand list gives a navigational label. |
| No word signal at all | "standing desk" | Labeled unclear, though the SERP may show clear intent. |
| Language and spelling | "comprar escritorio" | No English term matches. |
| Intent changes over time | "election results" | The same words mean different things in different weeks. |
Most of these limits share one cause. The classifier reads the query but never the SERP. A rule list cannot learn that Google now shows shopping results for "standing desk".
Using the classifier in a workflow
A practical workflow combines the tool with the checks you already know:
- Run the classifier on the whole keyword list and write the label to a column.
- Sort out the
unclearrows. These always need a SERP check. - Sample 20 to 30 rows from each other label and check them against the SERP, using the checklist from the process chapter.
- Count how many of the sampled rows were wrong, and which rule caused each error. Fix the rule, and rerun.
- For high-value keywords, check the SERP for every row, whatever the classifier said.
The output works well as the intent column of the labeled keyword sheet from the previous chapter. In that sheet, a human-confirmed label overrides the classifier's label, and the notes column records the evidence.
Extending the design
You can extend this design without changing its structure:
- Add a
mixedresult. If two or more lists match, returnmixedplus the matched labels instead of picking the first. This replaces rule order with an explicit signal for human review. - Load lists from a file. A CSV of terms and labels lets an SEO specialist adjust rules without editing code.
- Add scores. Count matches per intent and take the highest. This helps with queries such as "best free trial project software", which hits two lists.
If you reach the point of needing many such changes, a trained text classifier may serve you better. It would still need the same labeled set to learn from and to be tested against, so the labeling work in this chapter is not wasted.
Exercise
The classifier labels "how to download slack" as transactional, because download is checked before how. Name two different ways to change the design so that the label is more useful, and say what each one costs.
Show answer
First, return a mixed result when more than one list matches, here transactional and informational, so a person reviews the row. This costs extra manual review time. Second, add more specific rules, such as treating "how to" followed by a transactional term as informational. This handles the case but adds a rule that may break other queries, so you must rerun the labeled set after the change. A SERP check is still the final test either way.
Exercise
You add pricing to the commercial list. Why should you rerun the whole labeled set and not just check "github pricing"?
Show answer
A new term can change the label of other queries that contain it, for example "slack pricing plans" or a query that was correctly labeled before. Rerunning the full set shows whether the change fixed one miss and caused another. It also shows whether accuracy improved overall.