from mlfeatures import Recipe, StepDropCorr, StepDropNearZeroVariance, StepDropZeroVariance
from mlfeatures import Selectors as s
from mlfeatures.data import ames_mini, beansDropping columns
Dropping columns removes model variables that might lead to underidentified models, or models that take a long time to fit. mlfeatures has three filter steps for it: one for correlated columns and two for columns with little or no variance.
- StepDropCorr drops one column from each highly correlated pair (default threshold 0.9), which keeps a linear model from fitting redundant columns.
- StepDropNearZeroVariance drops columns that are almost constant, and StepDropZeroVariance only those that are fully constant or all missing.
- Filters are not a stage of the eight-step order; they run after stage 1 and again after the dummy step.
Setup
Drop columns with little or no variance
StepDropNearZeroVariance(columns) drops columns that are nearly constant, which a model can only overfit to. Street is the case here: 12 of 2,930 houses are on a gravel road.
recipe = Recipe(data=ames_mini, target="Sale_Price").add(
StepDropNearZeroVariance(s.features())
)
fitted = recipe.fit(ames_mini)
fitted.transform(ames_mini).columns['Neighborhood',
'Bldg_Type',
'Exterior_1st',
'Gr_Liv_Area',
'Year_Built',
'Garage_Cars',
'Garage_Area',
'Latitude',
'Longitude',
'Sale_Price']
StepDropZeroVariance is the strict version: it drops only columns that are completely constant or all missing. Its usual place is right after a dummy step, where a level that is present in the schema but absent from the training rows becomes an all-zero indicator column.
Missing values are a row problem
Filters remove columns. Rows with missing values are a different problem, handled by imputation rather than removal, and they are covered on Ensure robust to new data.