Sparse feature pipelines
Quick answer
A feature pipeline fits preprocessing on training data and applies exactly the same transformations to later rows. Sparse matrices store mostly nonzero entries and their positions instead of allocating a dense value for every cell. One-hot encoded data often benefits from sparse storage, but a pipeline must still be compatible with its downstream estimator. All examples use synthetic inputs and local scikit-learn 1.8.0 where imported; ByteMind package execution is unverified.
Combine numeric and categorical branches
The first column contains weight in kg and the second is shipping method. Train on three rows; transform an unknown method and missing weight.
import numpy as npfrom sklearn.compose import ColumnTransformerfrom sklearn.impute import SimpleImputerfrom sklearn.preprocessing import OneHotEncodertrain = np.array([[2.,'road'],[4.,'air'],[np.nan,'road']], dtype=object)p = ColumnTransformer([('weight',SimpleImputer(strategy='median'),[0]),('method',OneHotEncoder(handle_unknown='ignore'),[1])], sparse_threshold=1.0)p.fit(train)out = p.transform(np.array([[np.nan,'rail'],[8.,'air']],dtype=object))print(p.get_feature_names_out().tolist())print(out.toarray().tolist())Expected output:
['weight__x0', 'method__x1_air', 'method__x1_road'][[3.0, 0.0, 0.0], [8.0, 1.0, 0.0]]The new row keeps the same three columns. The small toarray call is for inspection only; the learned combined output is sparse in this fixture.
How it works
ColumnTransformer applies different steps to designated columns; Pipeline chains steps so imputation can precede scaling and model fitting. Fit the combined pipeline within each training fold to prevent leakage. CSR (compressed sparse row) stores data values, column indices, and row pointers. Its nnz counts stored entries, including explicit zeros; eliminate explicit zeros before interpreting stored density as mathematical nonzero density. Centering sparse features subtracts a mean from implicit zeros and can make them nonzero; use StandardScaler(with_mean=False) for sparse scaling if appropriate. ColumnTransformer combines sparse and dense outputs according to its sparse_threshold and measured density; if every branch returns dense it remains dense. With 1,000 rows and 10,000 float64 features a dense array requires 80 million bytes just for values. Do not densify large matrices casually. Check estimator support, data types, feature names, unknown rates and output shape; sparse format is not guaranteed by requesting one sparse branch.
Scale sparse data without centering
Inspect a small sparse matrix with two nonzero entries. The first feature is [0,2] and the second is [3,0].
from scipy.sparse import csr_matrixfrom sklearn.preprocessing import StandardScalerx = csr_matrix([[0.,3.],[2.,0.]])y = StandardScaler(with_mean=False).fit_transform(x)print(y.toarray().tolist())print(y.nnz)Expected output:
[[0.0, 2.0], [2.0, 0.0]]2Scaling divides by fitted standard deviations without changing implicit zeros.
Common mistakes
Never call fit_transform on test data. Do not assume all scikit-learn models accept sparse input or that all transformations preserve sparsity. Avoid centering CSR matrices and blindly calling toarray. A missing numeric value and an unseen category need different policies. Explicitly test fit/transform shape, feature order, empty columns and production missingness rates. Keep the training-fitted transformer together with the model and load only trusted artifacts.
Practice and recap
Try count nonzero features by row. Input is a rectangular list of integer rows. Return [row_counts,total_nonzero] counting mathematical nonzero values, including negatives. Empty input returns [[],0]; rows of width zero have count zero. This is pure Python reasoning, not a sparse library exercise. Then explain the preprocessing assumptions before choosing a transformation. Next: feature engineering and feature selection.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Sparse feature pipelines — knowledge check
Apply the preprocessing concept to small synthetic data and diagnose mistakes.
Why can sparse centering cause a memory problem?
What does CSR nnz count?
How should a pipeline be fitted in cross-validation?
Does a sparse OneHotEncoder guarantee sparse combined output?
What should remain fixed when transforming a new row?