

How is the course going for you so far?
Select all that apply.
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.
Select all of the following statements which are TRUE.
ColumnTransformer can scale numeric features and one-hot encode categorical features, then feed an estimator in a single Pipeline.Pipeline can split the input data into training and test sets.Pipeline matters.ColumnTransformer must preserve the original column order in its output.What’s wrong here? Assume we have already split the data.
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:
Should the same age have different coordinates in training and test?
What’s wrong here?
The test set is untouched. Is this evaluation valid?

The scaler’s fit includes the validation fold. ❌

Within each fold, preprocessing and the model fit on the same training rows. ✅
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.
Training majors: Computer Science, History.
New majors: Biology, Physics, History.
A category can first appear in a validation fold or after deployment.
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.
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.
A feature has high cardinality when it has many distinct values.
Sparse storage reduces memory use. Grouping changes which distinctions the model can learn.
| 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.
Downtown, Kitsilano, and Mount Pleasant keep their own columns.
The other nine categories share one infrequent column.
| 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.
Suppose Dunbar and Marpole have very different typical housing prices.
Select all statements that are TRUE.
handle_unknown="ignore" creates a column for each unseen category.
With handle_unknown="ignore", different unseen categories receive the same representation for that feature.
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.
Grouping can remove useful distinctions between categories.
| Message | Target |
|---|---|
| URGENT! Claim your free prize now! | spam |
| Are we still meeting for lunch tomorrow? | ham |
How can different messages share useful features?
Each distinct message becomes its own category.
We need recurring units smaller than the complete message.
| 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 countfit learns the vocabulary. transform counts those tokens.
The output is a sparse matrix, which stores nonzero counts efficiently.
Vocabulary: free, lunch, meeting, now, prize
What rows does vec.transform(...) produce for:
Unknown tokens are ignored. The learned columns stay fixed.
| 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.
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.
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] |
Presence keeps whether a token occurred and removes how often it occurred.
Stop words are words we choose to exclude from the vocabulary, often common words such as the, is, and and.
“the lunch is free” → lunch, free
stop_words="english" for a built-in list.stop_words=None, keeps these words.not.Treat stop-word removal as a modelling choice, not automatic cleanup.
“the food was good, not bad”
“the food was bad, not good”
These have the same unigram counts, but different meanings.
not bad and not good.Include unigrams (single tokens) and bigrams (adjacent pairs).
The vectors now differ, but the vocabulary grows and patterns become rarer.
prize and reward get separate features.A classifier cannot recover a distinction absent from its inputs.
Compare “free prize” and “free free prize”.
Which representation makes their rows identical, assuming all relevant tokens and sequences are in the vocabulary?
Default unigram counts
Unigrams with binary=True
Counts with ngram_range=(1, 2)
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.
Each fold learns its vocabulary from its training messages only.
Compare with the majority-class baseline.
Use the test score for final evaluation of the fixed workflow.
A published list of Canadian provinces and territories can define categories before seeing the dataset.
Distinguish a predefined domain from categories discovered by inspecting validation or test rows.
| 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.
Most words in the vocabulary do not occur in any one message.
CountVectorizer returns a sparse matrix storing nonzero values and their locations.
Inspect small slices or nonzero entries instead of calling .toarray() on a large matrix.
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.
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?
Normalizer processes each row independently.Compare normalized and unnormalized pipelines using training-data CV.
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.
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.
Task: infer a respondent’s like / dislike label from their completed survey.
As we build the column transformer:
# 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.
