Text Classification with Linear Models
Routing support tickets to the right team, flagging abusive comments, tagging news by topic, detecting the sentiment of a review: all are text classification, assigning one of labels to a document. Fine-tuned transformers are the strongest tool for it today, and this course gets there in Fine-Tuning BERT for Text Classification. But a sparse linear model on bag-of-words or TF-IDF features trains in a second, runs on any CPU, can be read weight by weight, and is often within a few points of the transformer. Every text classification project should start with one: it is the baseline that tells you whether the expensive model is worth it, and its errors tell you what is wrong with the data.
This lesson trains three such models on an original dataset of support tickets: multinomial naive Bayes from scratch, then TF-IDF with logistic regression and with a linear SVM. It evaluates them with macro-F1 and a confusion matrix, reads their weights, does an error analysis, and finally sets the baseline on real movie reviews that later lessons compare against.
The data: generated support tickets
Real ticket data is private, so the example generates it. Each ticket comes from one of four topics (billing, hardware, app, account) with six templates per topic. Slots are filled with synonyms ("charged", "billed", "debited"), half the tickets get a greeting, 30% get a second issue from another topic appended with "and" (the label stays the first issue's topic, as a triage rule would decide), about 20% contain a typo (two letters swapped), and 4% of the labels are replaced by a random one, as happens when agents file tickets in a hurry. Several words are shared across topics on purpose: "charge" is a fee in billing and a battery state in hardware, "update", "locked" and "card" occur in several topics. The split is stratified, 70% training and 30% test.
Multinomial naive Bayes from scratch
Multinomial Naive Bayes for Text derives the model; here is the short version. Each class has a prior and a distribution over the vocabulary words, estimated with Laplace smoothing from the word counts of the class's training documents. A document with counts is assigned the class with the largest log posterior, which is linear in the counts:
In matrix form, prediction is one sparse product: the count matrix () times the transposed matrix of log-probabilities, plus the log priors. The example fits it with NumPy on the sparse counts and checks it against scikit-learn's MultinomialNB.
import re
import numpy as np
from sklearn.model_selection import train_test_split
def make_tickets(n=900, seed=0, label_noise=0.04):
"""Templated support tickets: 4 topics, synonyms, mixed issues, typos, wrong labels."""
rng = np.random.default_rng(seed)
T = {"billing": ["i was {paid} twice for {ride}", "please refund the {fee} on my {card}",
"the app {paid} me for a ride i never took", "my {card} was declined in the app",
"the {pass} price is wrong", "why did the {fee} go up after the update"],
"hardware": ["the {part} on {bike} is broken", "{bike} has a flat tyre",
"the battery on {bike} will not charge", "the lock on {bike} is stuck",
"the app says the lock is open but it is stuck", "the display on {bike} shows no battery"],
"app": ["the app {crash} when i open the map", "i cannot see {bike} in the app",
"the app shows a wrong {fee} for {ride}", "after the update the app {crash}",
"the qr code will not scan in the app", "i cannot pay in the app it {crash}"],
"account": ["i cannot log in to my account", "please delete my account and data",
"my password reset link expired", "someone else used my account for {ride}",
"how do i change the {card} in my account", "my account is locked after the update"]}
S = {"paid": "charged billed debited", "ride": "one_ride my_trip a_ride_yesterday",
"fee": "fee charge extra_charge late_fee", "card": "card credit_card bank_card",
"pass": "day_pass monthly_pass", "part": "brake chain bell pedal seat",
"bike": "my_bike bike_4512 the_e-bike", "crash": "crashes freezes closes"}
fill = "hi hello please_help thanks asap again today urgent".split()
topics, texts, labels = list(T), [], []
for _ in range(n):
y = int(rng.integers(4))
t = str(rng.choice(T[topics[y]]))
for k, opts in S.items():
while "{" + k + "}" in t:
t = t.replace("{" + k + "}", str(rng.choice(opts.split())), 1)
if rng.random() < 0.3: # a second, secondary issue
other = str(rng.choice(T[topics[(y + int(rng.integers(1, 4))) % 4]]))
t += " and " + re.sub(r"\{(\w+)\}", lambda m: S[m.group(1)].split()[0], other)
w = t.replace("_", " ").split()
if rng.random() < 0.5: w = [str(rng.choice(fill)).replace("_", " ")] + w
i = int(rng.integers(len(w)))
if rng.random() < 0.2 and len(w[i]) > 3: # typo: swap two letters
j = int(rng.integers(len(w[i]) - 1)); w[i] = w[i][:j] + w[i][j + 1] + w[i][j] + w[i][j + 2:]
if rng.random() < label_noise: y = int(rng.integers(4)) # wrong label
texts.append(" ".join(w)); labels.append(y)
return texts, np.array(labels), topics
texts, y, topics = make_tickets()
X_tr, X_te, y_tr, y_te = train_test_split(texts, y, test_size=0.3, stratify=y, random_state=0)
print(len(X_tr), "train,", len(X_te), "test; classes:", topics)
print("train counts per class:", np.bincount(y_tr).tolist())
for t, l in list(zip(X_tr, y_tr))[:6]:
print(f" {topics[l]:9} | {t}")
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import accuracy_score, f1_score
cv = CountVectorizer().fit(X_tr)
C_tr, C_te = cv.transform(X_tr), cv.transform(X_te)
def fit_nb(X, y, alpha=1.0):
K = y.max() + 1
log_prior = np.log(np.bincount(y, minlength=K) / len(y))
N = np.vstack([np.asarray(X[y == k].sum(axis=0)).ravel() for k in range(K)]) # word counts per class
log_theta = np.log((N + alpha) / (N.sum(axis=1, keepdims=True) + alpha * X.shape[1]))
return log_prior, log_theta
def predict_nb(X, log_prior, log_theta):
return np.asarray(X @ log_theta.T + log_prior).argmax(axis=1)
lp, lt = fit_nb(C_tr, y_tr)
pred = predict_nb(C_te, lp, lt)
sk = MultinomialNB(alpha=1.0).fit(C_tr, y_tr)
print("vocabulary:", C_tr.shape[1], "| same predictions as MultinomialNB:", bool((sk.predict(C_te) == pred).all()))
print(f"test accuracy {accuracy_score(y_te, pred):.3f}, macro-F1 {f1_score(y_te, pred, average='macro'):.3f}")630 train, 270 test; classes: ['billing', 'hardware', 'app', 'account']
train counts per class: [139, 145, 169, 177]
account | my account is locked after the update and please refund the fee on my card
billing | i cannot see my bike in the app
hardware | thanks the lock on bike 4512 is stuck
app | the app shows a wrong late fee for my trip
account | i cannot log in to my account and the day pass price is wrong
app | the qr code will not scan in the app
vocabulary: 153 | same predictions as MultinomialNB: True
test accuracy 0.807, macro-F1 0.810
The class counts in the training split are reasonably balanced (139 to 177). The sample shows all the noise sources: two tickets with a second issue, and a wrong label in the second line (an app problem labelled billing). The from-scratch model makes exactly the same predictions as MultinomialNB, with 0.807 accuracy and 0.810 macro-F1 on the 270 test tickets.
The metric matters. Macro-F1 computes the F1 score of each class separately and averages them with equal weight:
where and are the precision and recall of class . Accuracy is dominated by the large classes; macro-F1 drops sharply when any class, however small, is handled badly. With balanced classes, as here, the two are close; on real ticket queues, where one category can be 50 times rarer than another, report macro-F1 (and the per-class scores, Classification Metrics).
TF-IDF with logistic regression and a linear SVM
Naive Bayes assumes the words of a document are independent given the class. Discriminative linear models make no such assumption: they fit one weight per feature and class to separate the classes directly. Logistic regression (multinomial, softmax over the class scores; see Softmax Regression) minimises the cross-entropy plus an L2 penalty whose strength is . A linear SVM minimises the hinge loss, which ignores examples that are already classified with a margin. Both work best on TF-IDF features with unigrams and bigrams and sublinear tf. All of the preprocessing goes inside a Pipeline, so the vectoriser is fitted on the training tickets only.
import re
import numpy as np
from sklearn.model_selection import train_test_split
def make_tickets(n=900, seed=0, label_noise=0.04):
"""Templated support tickets: 4 topics, synonyms, mixed issues, typos, wrong labels."""
rng = np.random.default_rng(seed)
T = {"billing": ["i was {paid} twice for {ride}", "please refund the {fee} on my {card}",
"the app {paid} me for a ride i never took", "my {card} was declined in the app",
"the {pass} price is wrong", "why did the {fee} go up after the update"],
"hardware": ["the {part} on {bike} is broken", "{bike} has a flat tyre",
"the battery on {bike} will not charge", "the lock on {bike} is stuck",
"the app says the lock is open but it is stuck", "the display on {bike} shows no battery"],
"app": ["the app {crash} when i open the map", "i cannot see {bike} in the app",
"the app shows a wrong {fee} for {ride}", "after the update the app {crash}",
"the qr code will not scan in the app", "i cannot pay in the app it {crash}"],
"account": ["i cannot log in to my account", "please delete my account and data",
"my password reset link expired", "someone else used my account for {ride}",
"how do i change the {card} in my account", "my account is locked after the update"]}
S = {"paid": "charged billed debited", "ride": "one_ride my_trip a_ride_yesterday",
"fee": "fee charge extra_charge late_fee", "card": "card credit_card bank_card",
"pass": "day_pass monthly_pass", "part": "brake chain bell pedal seat",
"bike": "my_bike bike_4512 the_e-bike", "crash": "crashes freezes closes"}
fill = "hi hello please_help thanks asap again today urgent".split()
topics, texts, labels = list(T), [], []
for _ in range(n):
y = int(rng.integers(4))
t = str(rng.choice(T[topics[y]]))
for k, opts in S.items():
while "{" + k + "}" in t:
t = t.replace("{" + k + "}", str(rng.choice(opts.split())), 1)
if rng.random() < 0.3: # a second, secondary issue
other = str(rng.choice(T[topics[(y + int(rng.integers(1, 4))) % 4]]))
t += " and " + re.sub(r"\{(\w+)\}", lambda m: S[m.group(1)].split()[0], other)
w = t.replace("_", " ").split()
if rng.random() < 0.5: w = [str(rng.choice(fill)).replace("_", " ")] + w
i = int(rng.integers(len(w)))
if rng.random() < 0.2 and len(w[i]) > 3: # typo: swap two letters
j = int(rng.integers(len(w[i]) - 1)); w[i] = w[i][:j] + w[i][j + 1] + w[i][j] + w[i][j + 2:]
if rng.random() < label_noise: y = int(rng.integers(4)) # wrong label
texts.append(" ".join(w)); labels.append(y)
return texts, np.array(labels), topics
texts, y, topics = make_tickets()
X_tr, X_te, y_tr, y_te = train_test_split(texts, y, test_size=0.3, stratify=y, random_state=0)
from sklearn.pipeline import make_pipeline
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.svm import LinearSVC
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import f1_score, accuracy_score, confusion_matrix
models = {
"naive Bayes, words": make_pipeline(CountVectorizer(), MultinomialNB()),
"naive Bayes, 1-2grams": make_pipeline(CountVectorizer(ngram_range=(1, 2)), MultinomialNB()),
"tf-idf + logistic": make_pipeline(TfidfVectorizer(ngram_range=(1, 2), sublinear_tf=True),
LogisticRegression(C=10, max_iter=1000)),
"tf-idf + linear SVM": make_pipeline(TfidfVectorizer(ngram_range=(1, 2), sublinear_tf=True),
LinearSVC(C=1.0)),
}
for name, m in models.items():
p = m.fit(X_tr, y_tr).predict(X_te)
print(f"{name:21} accuracy {accuracy_score(y_te, p):.3f} macro-F1 {f1_score(y_te, p, average='macro'):.3f}")
p = models["tf-idf + logistic"].predict(X_te)
print("confusion matrix (rows = true, columns = predicted):", topics)
print(confusion_matrix(y_te, p))naive Bayes, words accuracy 0.807 macro-F1 0.810
naive Bayes, 1-2grams accuracy 0.848 macro-F1 0.850
tf-idf + logistic accuracy 0.930 macro-F1 0.931
tf-idf + linear SVM accuracy 0.948 macro-F1 0.949
confusion matrix (rows = true, columns = predicted): ['billing', 'hardware', 'app', 'account']
[[57 1 0 1]
[ 2 57 0 3]
[ 1 1 67 4]
[ 3 0 3 70]]
| Model | Accuracy | Macro-F1 |
|---|---|---|
| naive Bayes, word counts | 0.807 | 0.810 |
| naive Bayes, unigram + bigram counts | 0.848 | 0.850 |
| TF-IDF (1-2 grams) + logistic regression, | 0.930 | 0.931 |
| TF-IDF (1-2 grams) + linear SVM, | 0.948 | 0.949 |
Bigrams help naive Bayes (0.810 to 0.850 macro-F1), and the discriminative models are clearly better again. The reason is the mixed tickets: naive Bayes adds up the evidence of every word, so a ticket with a billing issue and an equally long hardware issue is a coin toss, while logistic regression and the SVM can learn which features decide the label. The hyperparameters were not tuned; with 270 test tickets, a difference of 0.018 between the two linear models is 5 tickets and within noise. Choose between them with cross-validation on the training data, never on the test split.
The confusion matrix (logistic regression; rows are true classes, columns predictions) shows where the 19 errors go: no class is systematically confused with one other class, as would happen if two topics overlapped; the largest off-diagonal cell is 4 app tickets predicted as account, and most errors involve the account class in one direction or the other.
Reading the weights and the errors
A linear model's weights can be read directly: for each class, the features with the largest positive weight push a ticket towards it. Then look at the misclassified tickets themselves, with the model's confidence. This is error analysis, and it is the most valuable hour in any classification project.
import re
import numpy as np
from sklearn.model_selection import train_test_split
def make_tickets(n=900, seed=0, label_noise=0.04):
"""Templated support tickets: 4 topics, synonyms, mixed issues, typos, wrong labels."""
rng = np.random.default_rng(seed)
T = {"billing": ["i was {paid} twice for {ride}", "please refund the {fee} on my {card}",
"the app {paid} me for a ride i never took", "my {card} was declined in the app",
"the {pass} price is wrong", "why did the {fee} go up after the update"],
"hardware": ["the {part} on {bike} is broken", "{bike} has a flat tyre",
"the battery on {bike} will not charge", "the lock on {bike} is stuck",
"the app says the lock is open but it is stuck", "the display on {bike} shows no battery"],
"app": ["the app {crash} when i open the map", "i cannot see {bike} in the app",
"the app shows a wrong {fee} for {ride}", "after the update the app {crash}",
"the qr code will not scan in the app", "i cannot pay in the app it {crash}"],
"account": ["i cannot log in to my account", "please delete my account and data",
"my password reset link expired", "someone else used my account for {ride}",
"how do i change the {card} in my account", "my account is locked after the update"]}
S = {"paid": "charged billed debited", "ride": "one_ride my_trip a_ride_yesterday",
"fee": "fee charge extra_charge late_fee", "card": "card credit_card bank_card",
"pass": "day_pass monthly_pass", "part": "brake chain bell pedal seat",
"bike": "my_bike bike_4512 the_e-bike", "crash": "crashes freezes closes"}
fill = "hi hello please_help thanks asap again today urgent".split()
topics, texts, labels = list(T), [], []
for _ in range(n):
y = int(rng.integers(4))
t = str(rng.choice(T[topics[y]]))
for k, opts in S.items():
while "{" + k + "}" in t:
t = t.replace("{" + k + "}", str(rng.choice(opts.split())), 1)
if rng.random() < 0.3: # a second, secondary issue
other = str(rng.choice(T[topics[(y + int(rng.integers(1, 4))) % 4]]))
t += " and " + re.sub(r"\{(\w+)\}", lambda m: S[m.group(1)].split()[0], other)
w = t.replace("_", " ").split()
if rng.random() < 0.5: w = [str(rng.choice(fill)).replace("_", " ")] + w
i = int(rng.integers(len(w)))
if rng.random() < 0.2 and len(w[i]) > 3: # typo: swap two letters
j = int(rng.integers(len(w[i]) - 1)); w[i] = w[i][:j] + w[i][j + 1] + w[i][j] + w[i][j + 2:]
if rng.random() < label_noise: y = int(rng.integers(4)) # wrong label
texts.append(" ".join(w)); labels.append(y)
return texts, np.array(labels), topics
texts, y, topics = make_tickets()
X_tr, X_te, y_tr, y_te = train_test_split(texts, y, test_size=0.3, stratify=y, random_state=0)
from sklearn.pipeline import make_pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
clf = make_pipeline(TfidfVectorizer(ngram_range=(1, 2), sublinear_tf=True),
LogisticRegression(C=10, max_iter=1000)).fit(X_tr, y_tr)
vec, lr = clf.named_steps["tfidfvectorizer"], clf.named_steps["logisticregression"]
names = vec.get_feature_names_out()
for k, t in enumerate(topics):
top = np.argsort(-lr.coef_[k])[:5]
print(f"{t:9}", [names[j] for j in top])
j = list(names).index("charge")
print("weight of 'charge' per class:", np.round(lr.coef_[:, j], 2).tolist())
pred = clf.predict(X_te)
proba = clf.predict_proba(X_te)
wrong = np.flatnonzero(pred != y_te)
print(len(wrong), "errors of", len(y_te))
for i in wrong[:8]:
print(f" true {topics[y_te[i]]:9} pred {topics[pred[i]]:9} p={proba[i].max():.2f} | {X_te[i]}")billing ['wrong and', 'was', 'and how', 'my credit', 'debited']
hardware ['stuck and', 'tyre and', 'the bike', 'bike', 'charge and']
app ['app and', 'the app', 'app', 'hello someone', 'map and']
account ['account and', 'account', 'my account', 'and the', 'expired and']
weight of 'charge' per class: [0.2, -0.07, 0.38, -0.52]
19 errors of 270
true billing pred account p=0.95 | please help pelase delete my account and data
true app pred account p=0.47 | hi i cannot pay in the app it crashes and someone else used my account for one ride
true account pred billing p=0.52 | someone else used my account for a ride yesterday and the app charged me for a ride i never took
true app pred account p=0.97 | how do i change the cadr in my account
true hardware pred billing p=0.72 | the battery on my bike will not hcarge and the app charged me for a ride i never took
true hardware pred account p=0.51 | the brake on bike 4512 is broken and i cannot log in to my account
true account pred app p=0.99 | i cannot pay in the app it closes
true hardware pred account p=0.87 | someone else used my account for my trip and the display on my bike shows no battery
The top features hold a surprise. Many of them end in "and": "stuck and", "app and", "account and", "wrong and". The model has discovered how the data were made: the main issue comes first and the secondary one follows "and", so the last word before "and" identifies the label. That is a shortcut, a feature that works on this dataset because of how it was produced, and it would break on real tickets where people mention the main problem last. Generated and templated datasets are full of such artefacts, and so are real ones (a signature, a form field, the agent who filed the ticket); reading the top weights is how you find them. "hello someone" for the app class is a different problem: a few noisy labels taught the model that one greeting-plus-template combination means "app". The ambiguous word "charge" gets small weights in all classes (0.2, -0.07, 0.38, -0.52): it is not evidence for one topic, and its bigrams ("charge and", "the charge") carry the context.
The errors fall into two groups, and the predicted probability separates them:
- High-confidence errors are label errors. "please help pelase delete my account and data" labelled billing (predicted account, ), "how do i change the cadr in my account" labelled app (), "i cannot pay in the app it closes" labelled account (): the model is right and the label is wrong. In this generated data we know that 4% of the labels are noise; in real data, sorting the test errors by confidence is the quickest way to find mislabelled examples, and fixing them is often worth more than a better model.
- Low-confidence errors are genuinely ambiguous. Tickets with two issues of similar length get probabilities around 0.5 (, 0.51, 0.52). A typo makes it worse: in "the battery on my bike will not hcarge and the app charged me...", the swapped letters hide "charge", so the billing clause wins. Better models will not fix these; a rule for mixed tickets, or multi-label classification, would.
A real baseline: Rotten Tomatoes reviews
Generated data is good for seeing mechanisms, but not for judging a method. The rotten_tomatoes dataset (Pang and Lee's movie-review sentences, already lower-cased and tokenised with spaces; label 1 is positive) is a real, harder task: sentiment depends on negation, irony and on phrases spread over the sentence. The example uses a seeded subset of 2,000 training and 500 validation sentences, the same subset as the later lessons of this course, so their scores are comparable. It needs the Hugging Face datasets library, so it is a recorded example.
import numpy as np
from datasets import load_dataset
from sklearn.pipeline import make_pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import accuracy_score, f1_score
ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
train = ds["train"].shuffle(seed=0).select(range(2000))
val = ds["validation"].shuffle(seed=0).select(range(500))
print("train", len(train), "positive share", round(float(np.mean(train["label"])), 3),
"| validation", len(val), "positive share", round(float(np.mean(val["label"])), 3))
print("example:", train[0]["text"][:90], "->", train[0]["label"])
models = {
"tf-idf + naive Bayes": make_pipeline(TfidfVectorizer(ngram_range=(1, 2), min_df=2), MultinomialNB(alpha=0.5)),
"tf-idf + logistic": make_pipeline(TfidfVectorizer(ngram_range=(1, 2), min_df=2, sublinear_tf=True),
LogisticRegression(C=10, max_iter=1000)),
}
for name, m in models.items():
m.fit(train["text"], train["label"])
p = m.predict(val["text"])
print(f"{name:21} validation accuracy {accuracy_score(val['label'], p):.3f}, "
f"macro-F1 {f1_score(val['label'], p, average='macro'):.3f}")
clf = models["tf-idf + logistic"]
vec, lr = clf.named_steps["tfidfvectorizer"], clf.named_steps["logisticregression"]
names, w = vec.get_feature_names_out(), lr.coef_[0]
print("vocabulary:", len(names))
print("most positive:", [names[j] for j in np.argsort(-w)[:8]])
print("most negative:", [names[j] for j in np.argsort(w)[:8]])
for s in ["not bad at all", "the plot is not good", "a dull , lifeless film"]:
print(f" P(positive | {s!r}) = {clf.predict_proba([s])[0, 1]:.2f}")train 2000 positive share 0.486 | validation 500 positive share 0.494
example: this is pure , exciting moviemaking . you won't exactly know what's happening but you'll b -> 1
tf-idf + naive Bayes validation accuracy 0.702, macro-F1 0.700
tf-idf + logistic validation accuracy 0.696, macro-F1 0.696
vocabulary: 6123
most positive: ['still', 'their', 'enjoyable', 'you', 'mood', 'human', 'beautifully', 'solid']
most negative: ['too', 'dull', 'exercise', 'silly', 'bad', 'worst', 'doesn', 'thing']
P(positive | 'not bad at all') = 0.12
P(positive | 'the plot is not good') = 0.14
P(positive | 'a dull , lifeless film') = 0.05
The baseline: TF-IDF + logistic regression reaches 0.696 validation accuracy (500 sentences, 2,000 training sentences). Naive Bayes is slightly ahead at 0.702, a common result with little training data; the difference is 3 sentences. Both are far below the 0.93 to 0.95 of the linear models on the ticket data: sentiment is harder than topic. The learned weights explain why. Next to sensible words ("enjoyable", "beautifully", "dull", "worst", "silly") the list contains "their", "you", "exercise" and "thing", words that happen to be more frequent in one class in 2,000 sentences. And negation is not understood: "not bad at all" gets , because the weight of "bad" outweighs a bigram "not bad" that is rare in the training subset. A model that reads the whole sentence in context fixes exactly this, and Fine-Tuning BERT measures how much it gains on the same subset. (Later lessons refit their own TF-IDF baseline with slightly different settings next to each model, and get 0.702; differences of a few sentences between such settings are noise.)
Pitfalls
- Vectoriser fitted outside the pipeline. Fit the vocabulary and idf on training data only; cross-validate the whole pipeline.
- Accuracy on imbalanced classes. A model that never predicts the rare class can score 95%; report macro-F1 and per-class recall.
- Tuning on the test split. Comparing many models and settings on one test split overfits it; use cross-validation for choices and the test split once.
- Shortcuts. Check the top weights for features that should not decide the label (template words, signatures, ticket IDs, dataset artefacts).
- Trusting labels. High-confidence errors are often label errors; review them before blaming the model.
- Calibrated-looking probabilities. Naive Bayes is overconfident on long documents, and an SVM has no probabilities at all; calibrate if decisions use thresholds (Calibration).
Practice
- In the from-scratch naive Bayes, what happens to the log-probability of a class if and a test ticket contains a word never seen in that class's training tickets?
- Two classes have F1 0.95 and 0.40. What is the macro-F1? Why can the accuracy still be 0.93?
- Why did naive Bayes gain from bigrams on the ticket data, and why do the linear models still beat it?
- Name one way to remove the "X and" shortcut from the ticket generator, and how you would check that the model no longer uses it.
- A colleague reports 0.73 validation accuracy on the Rotten Tomatoes subset after trying 40 hyperparameter settings and keeping the best validation score. Is that comparable with the 0.696 baseline?
Answers
- for that word, so and the class gets a log posterior of : one unseen word rules the class out, whatever the rest of the ticket says.
- . If the class with F1 0.40 is rare (say 5% of tickets), the many correct predictions of the large class keep accuracy high.
- Bigrams such as "app and" or "will not" carry information about order and context that single words lack. Naive Bayes still adds up all the evidence with independence assumptions, so the second issue in a mixed ticket competes on equal terms; logistic regression and the SVM learn weights that separate the classes, including the features that mark the main issue.
- Put the main issue first or last at random (or join the clauses in random order with different connectives), so that position no longer reveals the label. Check that the features ending in "and" disappear from the top weights, and that accuracy on mixed tickets drops to what the words themselves support.
- No. Picking the best of 40 settings on the validation split overfits it, so 0.73 is optimistic. The comparison needs the setting chosen by cross-validation on the training data, scored once on validation, or a separate test split.
Test yourself
Why is multinomial naive Bayes a linear classifier?
- It uses gradient descent
- Its log posterior is plus a sum of counts times fixed weights
- It only works with two classes
- It uses a linear kernel
On the ticket data, which model had the highest macro-F1?
- Naive Bayes on word counts (0.810)
- Naive Bayes on 1-2 grams (0.850)
- TF-IDF + logistic regression (0.931)
- TF-IDF + linear SVM (0.949)
Several misclassified tickets have predicted probability above 0.95. What are they most likely?
- Tickets with two issues
- Tickets with a wrong label
- Tickets with a typo
- Tickets from the smallest class
What validation accuracy did TF-IDF + logistic regression reach on the Rotten Tomatoes subset (2,000 training, 500 validation sentences)?
- 0.594
- 0.696
- 0.807
- 0.931
The top weights of a ticket classifier include stuck and, app and and account and. What does this suggest?
- The model is underfitting
- Bigrams should be removed from every model
- The model found a dataset artefact (the main issue comes before "and") that may not hold on real tickets
- The stop-word list is missing "and"