Sub topic 3
A First Look at Text Features
Assume you know Python, pandas, supervised learning, scikit-learn pipelines, and basic statistics. This chapter focuses on features that require special care because they can leak information or behave differently in production.
Text and target encoding
Text must become numbers before most models can use it. A common first step is TF-IDF, which gives higher weight to words that are frequent in one document but uncommon across documents. A vectorizer learns its vocabulary from training data only.
Target encoding replaces a category with a statistic of the target, such as the average purchase rate for each city. It works well for high-cardinality columns, but it can leak labels. Compute the statistic for each validation row using only the corresponding training fold. Smoothing toward the global mean also reduces noise for rare categories.
Pipelines and mixed columns
A ColumnTransformer applies different transformations to different columns. Put it inside a Pipeline with the model so fitting happens in the correct order.
from sklearn.compose import ColumnTransformer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder
preprocess = ColumnTransformer([
("text", TfidfVectorizer(min_df=2), "review"),
("city", Pipeline([
("impute", SimpleImputer(strategy="most_frequent")),
("encode", OneHotEncoder(handle_unknown="ignore")),
]), ["city"]),
])
model = Pipeline([
("features", preprocess),
("classifier", LogisticRegression(max_iter=1000)),
])
model.fit(X_train, y_train)
predictions = model.predict(X_test)Measure feature changes
Compare a baseline with the new feature using the same split, metric, and cross-validation folds. Use cross_val_score(model, X, y, cv=5, scoring="roc_auc"). A higher mean score matters only when its variation and practical cost are acceptable.
Select features and reduce dimensions
Feature selection can remove noise and reduce computation.
| Method | Main idea | Common caution |
|---|---|---|
| Filter | Rank features with a statistical test | May ignore interactions |
| Wrapper | Search feature subsets using model scores | Expensive and leakage-prone |
| Embedded | Select during model fitting | Depends on the model |
PCA is dimensionality reduction: it replaces correlated numeric features with fewer components that preserve as much variance as possible. Scale numeric inputs first, and fit PCA inside the pipeline.
Keep training and serving consistent
Train-serving skew occurs when production applies different parsing, vocabulary, missing-value rules, or category handling than training. Save and deploy the fitted pipeline, pin dependency versions, and test it with real-shaped requests.
Exercise
Why must a vectorizer, target encoder, or PCA transformer be fitted inside cross-validation?
Show answer
Each validation fold must be processed using information from its training fold only; otherwise the score can be inflated by leakage.