Lecture 5: More preprocessing: categorical features and text

Varada Kolhatkar

Focus on the breath!

Check-in

How is the course going for you so far?

Select all that apply.

    1. I feel comfortable with both the concepts and the lab work.
    1. There is a lot of new material and terminology, but I’m keeping up.
    1. I follow the concepts, but struggle to apply them independently in labs.
    1. I feel lost and need help getting back on track 😞.

Announcements

  • Check out my handwritten notes for Lecture 4.
  • Lab 3 repositories have been released.
  • For this week’s quizzes:
    • Practice questions are available on PrairieLearn.
    • Use the learning objectives from Lectures 1–4 to guide your review.
    • Try active recall: close your notes, explain a concept or solve a problem, then check your understanding.
  • Extra office hours today: 12:30–1:30 PM in ICCS 237. Bring your questions, or come work through something you’re finding difficult.

This is a demanding week, and it’s understandable to feel overwhelmed. Take it one step at a time. Make room for breaks that help you recharge. Reach out if you find yourself lost. We are here to help.

iClicker: Lecture 4 recap

Select all of the following statements which are TRUE.

    1. A ColumnTransformer can scale numeric features and one-hot encode categorical features, then feed an estimator in a single Pipeline.
    1. A scikit-learn Pipeline can split the input data into training and test sets.
    1. The order of transformations and the estimator in a Pipeline matters.
    1. In cross-validation of a prediction pipeline, preprocessing is fitted on each training fold and only applied to the validation fold.
    1. A ColumnTransformer must preserve the original column order in its output.

Today’s big questions

  • Which rows may each preprocessing step learn from?
  • How should we handle unseen and rare categories?
  • How do we encode text as numerical features?
  • How do we evaluate the complete prediction pipeline?

Mistake 1: fitting train and test separately

What’s wrong here? Assume we have already split the data.

train_scaler = StandardScaler()
train_scaled = train_scaler.fit_transform(X_train)

test_scaler = StandardScaler()
test_scaled = test_scaler.fit_transform(X_test)

Same age, different coordinates

Suppose age is our only feature:

Fit the scaler on… Ages Mean Standard deviation
Training set 20, 40 30 10
Test set 40, 60 50 10

For a 40-year-old:

  • Training scaler: \((40 - 30) / 10 = +1\)
  • Separate test scaler: \((40 - 50) / 10 = -1\)

Should the same age have different coordinates in training and test?

Mistake 2: fitting on train and test together

What’s wrong here?

X_all = np.vstack([X_train, X_test])
scaler = StandardScaler().fit(X_all)

train_scaled = scaler.transform(X_train)
test_scaled = scaler.transform(X_test)

Mistake 3: fitting before cross-validation

The test set is untouched. Is this evaluation valid?

scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)

cross_val_score(
    KNeighborsClassifier(), X_train_scaled, y_train
)

Where the leakage happens

The scaler’s fit includes the validation fold. ❌

Which rows may each step learn from?

Within each fold, preprocessing and the model fit on the same training rows. ✅

The repair: cross-validate the whole pipeline

from sklearn.pipeline import make_pipeline
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import cross_val_score

pipe = make_pipeline(StandardScaler(), KNeighborsClassifier())
cross_val_score(pipe, X_train, y_train)
  • Pass raw features and the whole pipeline to CV.
  • Each fold fits its own preprocessing and classifier.
  • Validation rows receive transform, then predict.

Feature meaning still matters

A pipeline fits the steps we specify. We must choose sensible steps.

Feature Question to ask
Nominal category Do integer codes invent an order or distance?
Numeric identifier Does numerical proximity mean anything useful?
Target-derived feature Would this information exist when predicting?

Example: sale price per square foot reveals the target when combined with floor area.

Unknown categories

Training majors: Computer Science, History.

New majors: Biology, Physics, History.

encoder = OneHotEncoder(sparse_output=False)
encoder.fit(training_majors)
encoder.transform(new_majors)  # ValueError: unknown categories

A category can first appear in a validation fold or after deployment.

Ignoring unknown categories

With OneHotEncoder(handle_unknown="ignore"):

Major Computer Science History
Computer Science 1 0
History 0 1
Biology (unseen) 0 0
Physics (unseen) 0 0

Biology and Physics become indistinguishable using this feature.

(Optional) Dropping a binary indicator

drop="if_binary" keeps one column for a two-category feature. With handle_unknown="ignore", suppose No is dropped:

Value Yes indicator
No 0
Yes 1
Unknown value 0

An unknown value and the dropped category now share a representation.

High-cardinality features

A feature has high cardinality when it has many distinct values.

  • A postal code may contain useful geographic information.
  • A unique transaction ID may offer little for new transactions.
  • Rare categories may have too little evidence to learn reliable patterns.

Sparse storage reduces memory use. Grouping changes which distinctions the model can learn.

Grouping infrequent neighbourhoods

Training neighbourhoods Occurrences per category
Downtown 40
Kitsilano 25
Mount Pleasant 15
Marpole, Renfrew 4 each
Kerrisdale, Fairview 3 each
Sunset, Hastings-Sunrise 2 each
Dunbar, Point Grey, Oakridge 1 each

12 categories, with a long tail of rare values.

From 12 columns to 4

rare_encoder = OneHotEncoder(
    min_frequency=5,
    handle_unknown="infrequent_if_exist",
    sparse_output=False,
)
rare_encoder.fit(training_neighbourhoods)
rare_encoder.get_feature_names_out()

Downtown, Kitsilano, and Mount Pleasant keep their own columns.

The other nine categories share one infrequent column.

What happens to an unseen neighbourhood?

New value Downtown Kitsilano Mount Pleasant Infrequent
Downtown 1 0 0 0
Dunbar 0 0 0 1
Marpole 0 0 0 1
West End (unseen) 0 0 0 1

If no infrequent group was learned, an unknown receives all zeros.

Your turn: what did grouping remove?

Suppose Dunbar and Marpole have very different typical housing prices.

  1. Can the grouped neighbourhood feature express that difference?
  2. Does reducing the number of columns justify grouping?
  3. How would you assess whether grouping helps?

iClicker: Exercise 5.1

Select all statements that are TRUE.

  1. handle_unknown="ignore" creates a column for each unseen category.

  2. With handle_unknown="ignore", different unseen categories receive the same representation for that feature.

  3. We should use category frequencies from the entire training set to decide which categories to group, then use those same groups in every cross-validation fold.

  4. Grouping can remove useful distinctions between categories.

Encoding text data

Text as a feature: SMS spam

Message Target
URGENT! Claim your free prize now! spam
Are we still meeting for lunch tomorrow? ham

How can different messages share useful features?

Why not one-hot encode whole messages?

Each distinct message becomes its own category.

  • Most complete messages appear only once.
  • Similar messages do not share word-level features.
  • A new message is an unknown category.

We need recurring units smaller than the complete message.

Bag of words: build the count matrix

Document free lunch meeting now prize
Free prize prize 1 0 0 0 2
free lunch now 1 1 0 1 0
Lunch meeting 0 1 1 0 0

One row per document, one column per vocabulary token.

Each entry counts occurrences. Default lowercasing merges Free and free.

CountVectorizer: learn and count

from sklearn.feature_extraction.text import CountVectorizer

small_messages = [
    "Free prize prize", "free lunch now", "Lunch meeting"
]
vec = CountVectorizer()
counts = vec.fit_transform(small_messages)
vec.get_feature_names_out()
# ['free', 'lunch', 'meeting', 'now', 'prize']

fit learns the vocabulary. transform counts those tokens.

The output is a sparse matrix, which stores nonzero counts efficiently.

Your turn: unseen tokens

Vocabulary: free, lunch, meeting, now, prize

What rows does vec.transform(...) produce for:

  1. “Free meeting tomorrow”
  2. “Tomorrow only”
  1. [1, 0, 1, 0, 0]
  2. [0, 0, 0, 0, 0]

Unknown tokens are ignored. The learned columns stay fixed.

From messages to predictions

text_pipe = make_pipeline(CountVectorizer(), SVC())
  1. The vectorizer turns raw messages into token counts.
  2. The classifier uses those counts to predict spam or ham.

Vocabulary settings

Setting Choice Possible cost
min_df Remove tokens in too few documents Lose rare signals
max_df Remove tokens in too many documents Lose useful common words
max_features Cap vocabulary by total term frequency Frequency is not predictive value
stop_words Remove specified common words Lose meaning such as negation

max_df=0.8 excludes tokens in more than 80% of training documents.

Learn vocabulary filtering inside each CV fold.

Occurrence count versus document frequency

Corpus: “Free prize prize”, “Free lunch now”, “Lunch meeting”.

Token Total occurrences Documents containing token
free 2 2
prize 2 1
lunch 2 2

With min_df=2, free and lunch survive. prize is removed.

Repeating prize more within one document does not increase its document frequency.

With max_df=0.5, tokens in more than half the documents are removed: free and lunch.

Counts versus presence

For the vocabulary free, lunch, meeting, now, prize:

Representation of “Free prize prize” Vector
Default counts [1, 0, 0, 0, 2]
binary=True [1, 0, 0, 0, 1]
binary_vec = CountVectorizer(binary=True)

Presence keeps whether a token occurred and removes how often it occurred.

Removing stop words

Stop words are words we choose to exclude from the vocabulary, often common words such as the, is, and and.

vec = CountVectorizer(stop_words=["the", "is", "and"])

“the lunch is free” → lunch, free

  • Use a custom list or stop_words="english" for a built-in list.
  • The default, stop_words=None, keeps these words.
  • Removing common words can remove useful signals: “good” and “not good” become identical if we remove not.

Treat stop-word removal as a modelling choice, not automatic cleanup.

What does bag of words lose?

“the food was good, not bad”

“the food was bad, not good”

These have the same unigram counts, but different meanings.

  • Word order is lost.
  • Counts alone do not capture context or meaning.
  • Bigrams can retain adjacent pairs such as not bad and not good.

Bigrams retain some local order

vec = CountVectorizer(ngram_range=(1, 2))

Include unigrams (single tokens) and bigrams (adjacent pairs).

  • “the food was good, not bad” contains not bad.
  • “the food was bad, not good” contains not good.

The vectors now differ, but the vocabulary grows and patterns become rarer.

What bag of words cannot tell us

  • Similar meanings such as prize and reward get separate features.
  • Different meanings of the same token share a feature.
  • Unseen tokens contribute nothing.

A classifier cannot recover a distinction absent from its inputs.

iClicker: Exercise 5.2

Compare “free prize” and “free free prize”.

Which representation makes their rows identical, assuming all relevant tokens and sequences are in the vocabulary?

  1. Default unigram counts

  2. Unigrams with binary=True

  3. Counts with ngram_range=(1, 2)

SMS classification: split first

Lab connection: You’ll use this SMS dataset with an SVM and randomized search to tune hyperparameters.

Here, we build the pipeline you’ll tune: raw messages \(\to\) token features \(\to\) SVM.

Input: a Series of raw message strings. Target: spam or ham.

X_sms_train, X_sms_test, y_sms_train, y_sms_test = train_test_split(
    sms_df["sms"], sms_df["target"],
    test_size=0.2, random_state=123,
    stratify=sms_df["target"],
)

Cross-validate raw message strings

text_pipe = make_pipeline(CountVectorizer(), SVC())
scores = cross_val_score(
    text_pipe, X_sms_train, y_sms_train, cv=5
)
print(f"Mean validation accuracy: {scores.mean():.3f}")
print(f"Always predict ham: {(y_sms_train == 'ham').mean():.3f}")

Each fold learns its vocabulary from its training messages only.

Compare with the majority-class baseline.

Fit, predict, and evaluate once

text_pipe.fit(X_sms_train, y_sms_train)
text_pipe.predict([
    "Are we still meeting for lunch tomorrow?",
    "URGENT! Claim your free prize now!",
])
text_pipe.score(X_sms_test, y_sms_test)

Use the test score for final evaluation of the fixed workflow.

Summary

  • Reuse fitted transformations and keep validation rows out of learned preprocessing.
  • Unknown handling and rare grouping determine which categories remain distinguishable.
  • Bag of words shares token features across documents.
  • Binary counts, filters, and n-grams change the information available.
  • Cross-validate the complete pipeline and compare with a baseline.

Extra optional material

Backup: categories known independently of the data

A published list of Canadian provinces and territories can define categories before seeing the dataset.

encoder = OneHotEncoder(categories=[province_territory_names])

Distinguish a predefined domain from categories discovered by inspecting validation or test rows.

Optional: choosing a column scale

Transformer Learned centre Learned scale
StandardScaler Mean Standard deviation
MinMaxScaler Minimum Range
RobustScaler Median Interquartile range

Reuse training quantities for new rows. Min–max-scaled unseen values may fall outside [0, 1].

Robust scaling reduces the influence of extreme values on the fitted centre and scale. It does not remove or clip outliers.

Backup: why sparse storage?

Most words in the vocabulary do not occur in any one message.

CountVectorizer returns a sparse matrix storing nonzero values and their locations.

counts.shape       # documents, vocabulary terms
counts.nnz         # number of nonzero entries

Inspect small slices or nonzero entries instead of calling .toarray() on a large matrix.

Optional: centring sparse features

StandardScaler normally subtracts a feature’s mean.

What happens to its zeros when the mean is nonzero?

They become nonzero. Centring destroys sparsity and can greatly increase memory use.

StandardScaler(with_mean=False) preserves zeros when scaling sparse features.

Optional: normalize document rows

Vocabulary: free, prize, meeting.

Count row Euclidean length Normalized row
[1, 2, 0] \(\sqrt{5}\) \([1/\sqrt{5}, 2/\sqrt{5}, 0]\)
[2, 4, 0] \(2\sqrt{5}\) \([1/\sqrt{5}, 2/\sqrt{5}, 0]\)

Normalizer() divides each nonzero row by its own length.

What distinction has disappeared?

Optional: evaluate normalization

normalized_text_pipe = make_pipeline(
    CountVectorizer(), Normalizer(), SVC()
)
  • Column scalers learn statistics across training rows.
  • Normalizer processes each row independently.
  • Vocabulary learning still belongs inside each CV fold.

Compare normalized and unnormalized pipelines using training-data CV.

Backup: deciding which features belong

Feature availability alone does not establish suitability.

Consider sensitive attributes, proxy variables, measurement quality, fairness goals, and the consequences of errors in the application.

Dropping a sensitive column does not guarantee fairness.

Backup: preprocessing the target

Classification estimators can usually accept string labels directly.

One-hot encoding the target is unnecessary for the classifiers used here.

Regression targets may be transformed, but predictions must return to the original scale for interpretation.

Backup: combine the survey features

Open the preprocessing demo

Task: infer a respondent’s like / dislike label from their completed survey.

As we build the column transformer:

  1. Trace which columns enter each branch.
  2. Inspect the transformed feature names and shape.
  3. Cross-validate the complete prediction pipeline.

Backup: text with other columns

# First replace missing comments with empty strings.
X_train = X_train.assign(comments=X_train["comments"].fillna(""))

preprocessor_with_text = make_column_transformer(
    (numeric_pipe, ["age", "n_people", "price"]),
    (categorical_pipe, ["food_type", "north_america"]),
    (ordinal_pipe, ["noise_level"]),
    (CountVectorizer(), "comments"),
)
pipe = make_pipeline(preprocessor_with_text, SVC())

Use "comments", not ["comments"]: the vectorizer expects a 1D sequence of strings.