Maximizing a Fixed Linear SVM Through Better Features and Validation
Machine LearningModel answerLast updated
Raise held-out accuracy of a fixed LinearSVC classifier using preprocessing, feature engineering and leak-free tuning, then justify the improvement credibly without touching the test set.
You receive a labeled tabular dataset that may contain numeric, categorical and free-text columns. The estimator is fixed: the final classifier must be scikit-learn's LinearSVC. A hidden test set will be used to check whether your accuracy exceeds a baseline you cannot see.
You may change only preprocessing, feature construction and training hyperparameters. Swapping in another estimator is not allowed.
Write a model answer covering the following:
- Interface. Implement
train(X_train, y_train), which fits the whole pipeline, andtest(X_test), which returns predictions for unseen rows. Explain how accuracy would be reported when labels are available. - Data-centric improvements. Name the changes you would try (scaling, outlier handling, text vectorization, categorical encoding, feature selection or reduction, interactions, deduplication and label-noise cleanup, imbalance handling) and explain why each helps a linear large-margin model. State whether data changes or model changes should move accuracy more, and how you would show it.
- Mixed column types. Describe one pipeline that sends numeric, categorical and text columns through the right transformations.
- Tuning without peeking. Describe a validation scheme that lets you tune and decide you have beaten the baseline using only training data, then freeze the configuration. Explain how you prevent leakage.
- Reproducibility and measurement. Explain how you would make the work repeatable (seeds, saved artifacts, experiment log) and how you would estimate generalization (CV mean and spread, confidence intervals, robustness checks).
Include code, complexity or cost considerations where relevant, and the common mistakes to avoid.
Hints
Hint 1
Think about what LinearSVC optimizes (hinge loss plus an L2 penalty on the weights). What does that imply about feature scale, non-linear structure, and outliers?
Hint 2
Put every transformation inside a single Pipeline/ColumnTransformer so that imputers, scalers and vocabularies are fit only on the training part of each fold. Remove exact duplicates before splitting.
Hint 3
Use stratified k-fold with a grid search for tuning, and nested CV to get an unbiased estimate of the whole procedure. Claim a win only if the lower end of the estimate clears the baseline, then freeze the configuration and refit on all training data.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Framing
With the estimator fixed, the work is in representation and validation. LinearSVC learns sign(w·x + b) by minimizing hinge loss plus an L2 penalty on w. Three consequences drive the design:
- Scale matters. The penalty treats all coordinates equally, so a feature in dollars swamps one in ratios unless standardized. Badly scaled features also slow liblinear convergence.
- The boundary is linear. Any non-linearity must be supplied through features: one-hot levels, n-grams, bins, crosses.
- Outliers and mislabeled rows pull the margin. Hinge loss grows linearly with violation, so extreme or wrong-label points become support vectors and tilt
w.
Expect data-side changes to dominate. Typically, scaling raw tabular features is worth several points up to tens of points, TF-IDF with bigrams beats raw counts by a few points on text, and tuning C once features are right is worth about a point or less. Back this claim with your own ablation table rather than asserting it.
Pipeline for mixed types
Use one ColumnTransformer inside a Pipeline, so every step is fit per training fold.
- Numeric: median imputation with a missing-indicator (missingness is often predictive),
RobustScaler(median/IQR) so outliers do not set the scale, then clip to about ±5. - Categorical: most-frequent imputation, then
OneHotEncoder(handle_unknown="ignore", min_frequency=k). One-hot is the linear equivalent of a lookup table; grouping rare levels cuts noise and handles unseen categories at test time. For very high cardinality use hashing or frequency encoding. - Text:
TfidfVectorizer(ngram_range=(1,2), sublinear_tf=True, min_df=2). IDF down-weights uninformative tokens, sublinear TF tames long documents, bigrams add local order (a cheap non-linearity), and the default L2 row normalization suits a linear SVM. - Optional: low-degree interaction terms on a few key numeric columns,
SelectKBest(chi2)orTruncatedSVDwhen features far outnumber rows. - Hygiene before splitting: drop exact duplicates (they leak across folds and inflate CV) and inspect conflicting duplicates (same features, different labels) as label noise.
- Imbalance: try
class_weight="balanced", and since the metric is accuracy, optionally tune a bias ondecision_functionusing out-of-fold scores. Balanced weighting can lower raw accuracy, so keep it only if CV supports it.
Validation without peeking
- Tuning: stratified 5-fold CV with the entire pipeline inside
GridSearchCV, searchingC(log grid, e.g. 0.01 to 10) andclass_weight. - Unbiased estimate: the best CV score from a search is optimistically biased. Wrap the search in an outer CV (nested CV): the inner loop picks hyperparameters, the outer loop scores the selection procedure.
- Decision rule: declare "beats baseline" only if outer-CV mean minus roughly two standard errors exceeds the baseline estimate or target. Then freeze the configuration and refit on all training data. Never touch the test set for selection.
- Structure-aware splits: if rows are grouped (same user) or ordered in time, use
GroupKFoldorTimeSeriesSplit; random splits leak.
Code
import random, json, time
import numpy as np, pandas as pd, joblib
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import RobustScaler, OneHotEncoder, FunctionTransformer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import StratifiedKFold, GridSearchCV, cross_val_score
from sklearn.svm import LinearSVC
SEED = 42
random.seed(SEED); np.random.seed(SEED)
_model = None
def _split_cols(X, min_tokens=4.0):
num = X.select_dtypes(include="number").columns.tolist()
obj = [c for c in X.columns if c not in num]
text = [c for c in obj
if X[c].dropna().astype(str).str.split().str.len().mean() >= min_tokens]
cat = [c for c in obj if c not in text]
return num, cat, text
def _pipeline(X):
num, cat, text = _split_cols(X)
parts = []
if num:
parts.append(("num", make_pipeline(
SimpleImputer(strategy="median", add_indicator=True),
RobustScaler(),
FunctionTransformer(np.clip, kw_args={"a_min": -5, "a_max": 5})), num))
if cat:
parts.append(("cat", make_pipeline(
SimpleImputer(strategy="most_frequent"),
OneHotEncoder(handle_unknown="ignore", min_frequency=5)), cat))
for c in text: # 1-D column name for the vectorizer
parts.append((f"txt_{c}", make_pipeline(
FunctionTransformer(lambda s: s.fillna("").astype(str)),
TfidfVectorizer(ngram_range=(1, 2), sublinear_tf=True, min_df=2)), c))
prep = ColumnTransformer(parts, sparse_threshold=0.3)
clf = LinearSVC(dual="auto", max_iter=20000, random_state=SEED)
return Pipeline([("prep", prep), ("clf", clf)])
def train(X_train, y_train, n_splits=5):
global _model
X = pd.DataFrame(X_train).reset_index(drop=True)
y = pd.Series(np.asarray(y_train))
keep = ~X.astype(str).assign(_y=y.astype(str)).duplicated()
X, y = X[keep.values].reset_index(drop=True), y[keep.values].reset_index(drop=True)
grid = {"clf__C": [0.01, 0.1, 1.0, 10.0],
"clf__class_weight": [None, "balanced"]}
inner = StratifiedKFold(n_splits, shuffle=True, random_state=SEED)
outer = StratifiedKFold(n_splits, shuffle=True, random_state=SEED + 1)
search = GridSearchCV(_pipeline(X), grid, cv=inner,
scoring="accuracy", n_jobs=-1, refit=True)
scores = cross_val_score(search, X, y, cv=outer, scoring="accuracy") # nested
search.fit(X, y) # freeze + refit
_model = search.best_estimator_
joblib.dump(_model, "model.joblib")
with open("experiments.jsonl", "a") as f:
f.write(json.dumps({"ts": time.time(), "params": search.best_params_,
"nested_mean": float(scores.mean()),
"nested_std": float(scores.std(ddof=1))}) + "\n")
return scores.mean(), scores.std(ddof=1)
def test(X_test, y_test=None):
preds = _model.predict(pd.DataFrame(X_test))
if y_test is not None:
return preds, float((preds == np.asarray(y_test)).mean())
return preds
Cost: nested CV with a grid of 8 settings and 5x5 folds is about 200 fits of a near-linear-time solver, which is fine for tens of thousands of rows. Cut the grid or use fewer folds for larger data.
Reproducibility and measurement
- Fixed seeds for splits and the estimator, pinned library versions, and the fitted pipeline saved with
joblib. - An append-only experiment log (config, feature set, CV mean and std, runtime) so each claim in the ablation table is traceable.
- Report CV mean ± std, a bootstrap or normal-approximation confidence interval, and robustness checks: different seeds, repeated CV, performance by subgroup, and sensitivity to dropping a feature block.
- Ablations: baseline (raw features, default
C), plus each change added in turn, to show data tweaks outweigh model tweaks.
Common mistakes
- Fitting scalers or vocabularies on the full data before CV (leakage).
- Reporting the best grid-search score as the generalization estimate.
- Leaving duplicates or same-group rows spread across folds.
- Forgetting
handle_unknown="ignore", so unseen categories crash inference. - Using
class_weight="balanced"by default when the metric is plain accuracy. - Ignoring convergence warnings instead of scaling features or raising
max_iter. - Tuning repeatedly against the hidden test set, which turns it into a validation set.