liveBook · Manning

Constant feature

As explained in Machine Learning for Tabular Data: XGBoost, Deep Learning, and AI

A feature whose value is identical for every observation in a dataset.

A constant feature has the same value for every observation, so it provides no variation from which a machine-learning model can learn. In a tabular dataset, remove it during exploration rather than carrying it through later numerical processing. section 2.2.1

Use these checks to distinguish useless columns from merely low-variation columns:

  • For numeric features, treat variance approximately equal to zero as a warning sign. section 2.2.1
  • For categorical features, investigate a majority class above 99.9%; this indicates a quasi-constant column. section 2.2.1
  • Drop constant and quasi-constant columns because constant values add processing burden, while tiny nonconstant parts can encourage overfitting. section 2.2.1
Listing 2.2 Dropping zero variance features
import pandas as pd
from sklearn.preprocessing import OrdinalEncoder
from sklearn.feature_selection import VarianceThreshold
 
data = pd.DataFrame({"feature_1":['A' for i in range(15)],
                     "feature_2":['B' if i%2==0 else 'C' 
                                  for i in range(15)],
                     "feature_3":[i**2 for i in range(15)]})
ord_enc = OrdinalEncoder()                                  #1
data[data.columns] = ord_enc.fit_transform(data)
var_threshold = VarianceThreshold(threshold=0)              #2
 
clean_data = var_threshold.fit_transform(data)
print(var_threshold.variances_)                             #3
print(clean_data.shape)

Encode categorical values numerically, apply scikit-learn's zero-variance threshold, inspect the computed variances, and retain only varying columns. section 2.2.1

How Machine Learning for Tabular Data: XGBoost, Deep Learning, and AI covers it

How deep it goes
Explains zero variance, categorical dominance, modeling risks, and removal, then demonstrates automated filtering without developing variance mathematics.
Examples
Demonstrates a constant string column alongside alternating categorical values and squared numeric values in a pandas DataFrame.
What it assumes
Assumes basic tabular columns and categorical-versus-numeric distinctions while demonstrating encoding before automated variance filtering.
What you can do after
Diagnose and remove zero-variance columns with pandas, OrdinalEncoder, and scikit-learn's VarianceThreshold.
How it connects
Connects constant features with quasi-constant features, categorical features, exploratory data analysis, feature selection, and overfitting.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Machine Learning for Tabular Data: XGBoost, Deep Learning, and AI. The section links point to the parts of the book it draws on.