Feature Engineering for Machine Learning: Selection, Scaling, Encoding and Transformation

Imagine a student opening a historical house-sale spreadsheet. It contains property size, building age, basement space, neighbourhood labels, sale months and prices. Some columns look numerical, while others use words such as “Detached” or “TwoStory”. There are blanks, dates represented as numbers and variables that may be useful only in combination. Could the student turn this collection of raw measurements into more helpful inputs for a machine learning model—and prove that the changes improve predictions rather than merely adding complexity?

This is the purpose of feature engineering for machine learning. In the complete project, you will prepare numerical and categorical variables, create building-age, combined-area, quality–area and cyclical month features, fit transformations within Scikit-learn Pipelines, compare three Ridge Regression workflows with five-fold cross-validation, and evaluate a winner on an untouched test set. We use the historical Ames Housing dataset, not a live real-estate feed. This lesson builds on Topic 89: Hyperparameter Tuning while shifting the focus from model settings to model inputs.

Verification disclosure — 25 November 2026: The formulas and example calculations in this lesson were checked, and the supplied Scikit-learn preprocessing and feature-selection pipeline was smoke-tested using independently generated fictional input records. The real Ames Housing download was unavailable from the authoring environment; consequently, no Ames cross-validation MAE, final test MAE, RMSE, R², winning configuration or exact transformed-column count is claimed here. The supplied Python notebook downloads OpenML dataset 42165 when run with internet access and writes real results. Do not mistake the arithmetic exercises, fictional CSV or conceptual visualizations for the actual Ames model output.

Feature engineering workflow with housing input data, construction, encoding, scaling, selection and a conceptual price chart
Original editorial illustration of a feature-engineering workflow. The on-screen chart is conceptual—not an Ames model result.

What is feature engineering?

Feature engineering is the process of constructing, representing, transforming or selecting the input information a model receives. A feature can be a recorded measurement, a category or a quantity computed from several recorded fields. For example, GrLivArea is a raw measurement of above-ground living area, while HouseAgeAtSale = YrSold − YearBuilt is an engineered feature. A good feature reflects something informative that is available when a prediction must be made.

Creating ten new columns is not automatically ten improvements. An unnecessary column can add noise; a misleading column can make validation results look stronger than real deployment; a target-derived column can invalidate the entire experiment. The appropriate question is whether a candidate representation reliably improves the stated modelling objective under a defensible validation design. Domain knowledge and measured evidence should guide each change.

Raw, constructed, transformed and selected features

A raw feature comes directly from the data source, such as MoSold. A constructed feature combines source values, such as sale year minus building year. A transformed feature changes scale or representation, such as standardizing living area or one-hot encoding neighbourhoods. A selected feature is one retained after a defined selection procedure.

These labels overlap in practical workflows. A constructed feature can be scaled and then selected; a single categorical input can expand into several one-hot indicator columns. In our project the original table contains ten chosen explanatory variables, but the model can receive many more transformed columns. Count the transformed columns only after fitting the relevant preprocessing transformer on the training data.

Feature engineering versus data cleaning

Data cleaning addresses inaccurate, inconsistent, missing or unusable source values. A sale month coded 19 is invalid and must be investigated or appropriately marked missing. A price recorded in an inconsistent currency needs documented reconciliation. Feature engineering instead changes the usable representation: encoding valid months on a circle, computing an age or combining area measurements.

There is a practical overlap. Imputing a missing value prepares the dataset and changes the numerical information given to the model; creating a missingness indicator can make the absence itself available as an input. Yet that missingness may reflect recording procedures rather than a property characteristic. Avoid assuming that a blank field always means the same thing in every column.

Feature engineering versus feature selection

Engineering creates or transforms candidate predictors; selection chooses a subset. For example, adding QualityAreaInteraction engineers a column. Applying SelectKBest(f_regression, k=15) inside training folds can reduce the resulting encoded matrix to 15 transformed columns. The procedure may select one neighbourhood indicator and not another, so selecting 15 transformed columns does not mean keeping 15 original variables.

Feature selection can improve clarity and reduce computational cost, but a model may become worse if useful information is removed. A single-variable selection score can miss interactions and may favour one of several correlated variables. Therefore, selection is itself a modelling decision to test using the same cross-validation method as the raw and engineered alternatives.

Understand numerical, nominal, ordinal and temporal features

Numerical features represent quantities: above-ground area, basement area and calendar year are examples, although a calendar year is not a measure of physical size. Nominal categories represent different named groups without an intrinsic ranking, such as neighbourhoods or house styles. Ordinal categories have a meaningful order, such as the ordered quality rating OverallQual. Binary categories have two states, such as central air availability.

Treating a coded ordinal scale as continuous is a modelling assumption: moving from quality rating 4 to 5 need not have the same substantive effect as moving from 8 to 9. Record identifiers should normally be excluded unless there is a clear, defensible predictive purpose. Dates deserve special treatment because cyclic patterns and chronological availability differ from ordinary continuous measurements.

Define the Ames Housing prediction task carefully

The main project uses the historical OpenML house_prices dataset (ID 42165), commonly described as containing 1,460 sales and 79 explanatory variables, with SalePrice as the target. It concerns Ames, Iowa, approximately 2006–2010, and therefore does not describe today’s global property market. We choose six numerical inputs—GrLivArea, TotalBsmtSF, OverallQual, YearBuilt, YrSold and MoSold—and four categorical inputs—Neighborhood, HouseStyle, CentralAir and GarageType.

Our question is retrospective: can the recorded house characteristics, together with sale month and year, explain historical sale prices in previously unseen records? A pre-listing model may not know the eventual sale month or year; such features must be removed or replaced for that different prediction problem. A model trained here is educational, not a current property appraisal service. Consult the source data dictionary and dataset reuse terms rather than assuming downloadable data have unrestricted redistribution permission.

Input fieldType / meaningImportant caution
GrLivAreaNumeric above-ground living areaDo not equate with basement area
TotalBsmtSFNumeric basement areaMissing and zero can differ
OverallQualOrdinal overall quality ratingNumeric differences are assumptions
YearBuiltConstruction yearMay produce age at sale
YrSold, MoSoldYear and month of historical saleOnly known for retrospective use
Neighborhood, HouseStyleNominal text categoriesNo arbitrary rank order
CentralAirBinary categoryEncode consistently
GarageTypeCategory with possibly missing valuesMissing may indicate no garage

A leakage-resistant workflow begins before preprocessing

The most damaging mistake is using evaluation information to build features. If a student scales all 1,460 observations before splitting, the test observations help define training means and standard deviations. If a student selects columns according to their relationship with price across the entire dataset, test targets influence feature selection. Target encoding using full-data sale-price averages is a more direct case of leakage. All such learned operations belong inside the training partition and, for cross-validation, inside each training fold.

A trustworthy sequence is: identify the intended prediction time, validate source columns, separate target and identifiers, reserve the test sample, build feature-construction and preprocessing Pipelines, compare candidates with training-only cross-validation, select the winner, and evaluate once on untouched test observations. Deterministic row-wise arithmetic without fitted statistics is less vulnerable to this specific leakage, but keeping it inside the same Pipeline aids reproducibility and auditing.

How numerical feature scaling works

Models such as distance-based classifiers, regularized linear regression and support vector machines may respond differently if one input spans thousands of units and another spans 1–10. Scaling modifies numerical representation without changing the underlying real-world measurement. A Ridge Regression model typically benefits from appropriate scaling before its regularization penalty is applied. Standard, min–max and robust scaling use different reference statistics and respond differently to outliers.

Tree and Random Forest methods generally do not need numerical scaling because they split on ordered thresholds, rather than distance or a coefficient penalty affected in the same way. Therefore, a useful feature-engineering recipe depends partly on the estimator. Never apply a scaler to the complete dataset and then cross-validate as though each fold were independent of preprocessing.

StandardScaler and z-score standardization

The standardization formula is z = (x − μ) / σ, where μ is the training mean and σ is the training standard deviation. If a variable has mean 70 and standard deviation 10, an observation of 85 receives (85−70)/10 = 1.5. It is 1.5 standard deviations above the specified mean, not “1.5 percent above average”.

Scikit-learn’s StandardScaler estimates its own statistics during fit and then reuses them for validation and test inputs. Its conventional variance calculation corresponds to the population-style denominator for fitted values, so classroom examples should not silently switch between sample and population standard-deviation definitions. Outliers can strongly affect the estimated mean and standard deviation.

MinMaxScaler: transform relative to a training range

For default 0–1 scaling, x_scaled = (x − x_min)/(x_max − x_min). If the training minimum is 20, maximum 80 and the value is 50, the result is (50−20)/(80−20) = 0.5. This represents the point halfway across the learned training range. It does not say the value has a 50% probability or a 50th-percentile rank.

An observation above the fitted maximum can transform to a number greater than one; the default scaler does not promise that every future observation remains between zero and one. Extreme training values can also compress the rest of the distribution. The word “normalization” is sometimes used for min–max scaling, but vector normalization and probability normalization are different mathematical operations.

RobustScaler and resistant summaries

A common robust-scaling convention subtracts the median and divides by the interquartile range, IQR = Q3 − Q1. If the median is 70, Q1 is 50, Q3 is 80 and x = 85, the result is (85−70)/(80−50) = 0.5. Because the median and quartiles are less sensitive than the mean to certain extreme observations, the transformation can be useful for skewed measurements.

Robust scaling is not the same as deleting or solving outliers; it also does not guarantee superior predictions. Quartile calculation conventions and other optional scaler settings should be recorded when exact reproducibility matters. As with StandardScaler, medians and quartiles must be learned from each relevant training fold.

MethodFitted referenceExample resultCaution
StandardScalerMean and standard deviation1.5Sensitive to extremes
MinMaxScalerTraining minimum and maximum0.5New inputs may fall outside 0–1
RobustScalerMedian and interquartile range0.5Does not remove outliers

Handle missing data according to its meaning

Missing numerical features can be filled by a training-fold median using SimpleImputer(strategy='median'). For categorical fields, a most-frequent level or explicit placeholder may be more appropriate. In Ames Housing, absence of GarageType can indicate that no garage exists rather than that the homeowner forgot to respond. Read the data dictionary before deciding whether to call a value unknown, absent, not applicable or invalid.

Our project uses an explicit 'Missing' categorical placeholder in an instructional Pipeline and documents that this simplifies several possible meanings. A missingness indicator equals one when the original value is absent and zero otherwise. Such a feature may add predictive value, but could also reflect the record-collection process. Imputation and missing-indicator decisions should be compared under validation instead of introduced without checking.

One-hot encoding: categories without false numerical order

Suppose CentralAir is either Y or N. One-hot encoding can create separate indicators, with Y represented as (0,1) and N as (1,0), subject to the encoder’s learned column ordering. This representation avoids treating two nominal labels as if one were inherently larger. It also permits linear models to estimate distinct contributions for the categories.

In the main Scikit-learn Pipeline, OneHotEncoder(handle_unknown='ignore', sparse_output=False) learns category columns from training data, then handles categories unseen at prediction time without throwing an unknown-label error. However, an unseen category is effectively represented by zeros in its relevant one-hot block under that setting; this does not create knowledge about its behaviour. Neighbourhoods and house styles can expand into many columns, increasing model dimension.

Unknown and infrequent categorical values

One-hot encoding a category that appears only once can create a highly sparse column, making overfitting or memory requirements more important. Scikit-learn also has options for grouping infrequent categories, which should be tuned and validated in context. Frequencies and category vocabularies are learned from the training partition; fitting them using the entire dataset can leak evaluation information.

An encoder must define what happens when a new neighbourhood or unusual house style appears. A test row might have a category never observed in training because the training sample was small, or because the population changed. Document whether such levels are ignored, grouped, assigned a fallback or rejected for further review.

Ordinal and frequency encoding

An ordered quality scale such as Low, Medium and High could be coded 1, 2 and 3 when that sequence is genuinely meaningful. However, those codes impose a numerical representation; equal differences between neighbouring codes do not necessarily correspond to equal economic effects. The existing OverallQual column already uses ordered numerical ratings, and using it as a numeric predictor is a modelling decision.

Frequency encoding represents a category by its training frequency, for instance A → 0.40, B → 0.35 and C → 0.25 in a hypothetical sample. This can reduce dimensionality, but two categories may have the same frequency despite different meanings, and frequency need not predict sale price. Unseen levels require explicit treatment; frequency mappings should be fitted within the relevant training folds.

Target encoding and why cross-fitting matters

Target encoding substitutes a category-related summary of the target, such as a smoothed average sale price, for a category label. This can be powerful when there are many categories, but encoding all observations with category price averages estimated using their own labels may allow the model to memorize rare categories. Using full training-and-test price averages is an even more serious leakage error.

Proper target encoding separates the examples used to calculate encodings from those using them for fitting, applies smoothing and has well-defined unknown-category behaviour. Scikit-learn’s TargetEncoder uses an internal cross-fitting procedure during fit_transform, which differs materially from a separate fit followed by transform. Keep this as an advanced extension and do not replace neighbourhood names with global sale-price averages.

Logarithmic and power transformations

A nonnegative numerical feature with a long right tail might be compressed using log1p(x) = ln(1+x). For x = 99, log1p(99) = ln(100) ≈ 4.6052; the inverse expm1(4.6052) returns approximately 99. This can reduce the influence of large values but cannot magically eliminate all skewness or prove a linear relationship.

A direct log1p transform is inappropriate when the input is at or below −1. Box–Cox transformations generally require strictly positive data; Yeo–Johnson can accommodate zero and negative inputs under its definition. Any estimated transformation parameter must be learned within the training fold. A transformed model should be evaluated using the same primary metric as the alternatives.

Binning, polynomial terms and interactions

Binning converts a continuous measurement into intervals such as newer, middle-aged and older buildings. Domain thresholds may be meaningful, while quantile thresholds learned from data must be estimated within training. Binning can simplify relationships but discards variation inside bins. Polynomial expansion creates powers such as x² or interaction terms x₁x₂, allowing a linear model to represent some nonlinear structure at the cost of greater complexity.

For our housing example, QualityAreaInteraction = GrLivArea × OverallQual. A home with 1,500 square feet of above-ground area and quality rating 8 receives 1,500×8 = 12,000 square-foot–rating units. This is an interaction feature, not a currency amount. It may help Ridge Regression model a quality-dependent size effect, but the product can also increase collinearity or add little extra predictive information.

Ratio features and safe denominators

Ratios can describe meaningful relationships that absolute totals obscure. If a home has 1,600 square feet of living area and eight suitable rooms, a hypothetical AreaPerRoom value is 1,600/8 = 200 square feet per room. However, ratio construction must verify units, confirm whether the denominator is appropriate, and handle zero or missing denominators without silently generating infinities.

A ratio can inadvertently reveal a target or use information unavailable at prediction time. It may also behave erratically when denominators are small. Domain knowledge is necessary: a per-room area ratio can be interpretable, while dividing two unrelated variables merely to generate more columns has no defensible justification.

Build house age using the available calendar fields

Our first main constructed input is HouseAgeAtSale = YrSold − YearBuilt. For a house constructed in 1998 and sold in 2008, the calendar-year difference is 10 years. This is an approximation, not an exact age measured to the day, because the full construction and transaction dates are not supplied.

Negative age values would require investigation: they might reflect an inconsistent row, unusual source conventions or simply a mistaken field mapping. Do not quietly clip them to zero or delete the record without recording why. In a prospective model, building age must be calculated relative to a genuinely known prediction date, not an unknown future sale date.

Combine above-ground and basement area cautiously

We also create CombinedLivingAndBasementSF = GrLivArea + TotalBsmtSF. If above-ground area is 1,500 square feet and basement area is 400 square feet, the constructed figure is 1,900 square feet. It may summarize total recorded area in a way that benefits a simple model, and it is easy for a student to calculate and verify.

Yet basement space is not necessarily equivalent in usability, regulations or market value to above-ground living space. This derived variable must not be described as formal total habitable area. Keeping the two original features alongside the combined measure also creates correlation, so useful validation evidence rather than intuition determines whether the engineering is worthwhile.

Why calendar months require a circular representation

Month numbers are not genuinely a linear distance scale: December is month 12 and January is month 1, but they are adjacent in the annual cycle. For a month m, define MonthSin = sin(2π(m−1)/12) and MonthCos = cos(2π(m−1)/12). The paired values map months around a unit circle, preserving the fact that neighbouring months have nearby positions.

Under this convention, January (m=1) becomes (0,1), while December (m=12) becomes approximately (−0.5, 0.8660). Sine and cosine both matter because a single trigonometric coordinate does not uniquely describe the month. Creating these features does not prove the presence of housing seasonality; it only provides the model with a representation that could express a seasonal association.

import numpy as np
def months_on_circle(month):
    angle = 2 * np.pi * (month - 1) / 12
    return np.sin(angle), np.cos(angle)
print(months_on_circle(1))   # (0.0, 1.0)
print(months_on_circle(12))  # approximately (-0.5, 0.8660)

Feature selection: filter, wrapper and embedded methods

A filter method ranks or removes columns using a statistical score or predefined criterion before final model fitting. Examples include variance screening, univariate correlations, mutual information and SelectKBest. A wrapper method repeatedly assesses feature subsets with an estimator, including recursive feature elimination and sequential selection. An embedded method incorporates shrinkage or selection into the estimator, such as L1 regularization or a model-based selection step.

The alternatives differ in cost and assumptions. Univariate f_regression measures particular one-feature linear relationships with a numerical target and can miss interactions. Wrappers may be computationally expensive and unstable with correlated predictors. Embedded importance is model-dependent and does not prove causal influence. Any method learned from features and target belongs inside cross-validation, never fitted once using the full dataset before validation.

Multicollinearity and interpretation

Feature construction often creates correlated predictors. If CombinedLivingAndBasementSF includes GrLivArea, those columns naturally share information; the engineered interaction with area can increase the relationship further. Under multicollinearity, fitted linear coefficients can be unstable, hard to interpret or sensitive to sampling differences. Ridge regularization can reduce some instability by shrinking coefficients.

But correlated features are not automatically redundant for all models or all objectives. Discarding every pair of correlated predictors is rarely justified without considering domain meaning and the intended task. Predictive usefulness, coefficient interpretability and causal inference are distinct research objectives.

Why feature importance does not establish causation

An input may strongly predict prices because it is associated with other variables or with historic social and economic processes. Neighbourhood names can act as proxies for multiple local characteristics, and may correlate with historical inequalities. A statistically useful feature does not demonstrate that the category label itself causes an outcome; feature attribution depends on the model, dataset and correlations among inputs.

In practical work, record possible proxies and fairness concerns, consider whether sensitive information is genuinely necessary and avoid using a classroom model to make consequential housing or credit decisions. This lesson supports statistical learning, not property valuation, fairness certification or causal claims about communities.

Use Pipelines to make feature engineering reproducible

A Scikit-learn Pipeline groups transformation and prediction steps into a single estimator interface. A FunctionTransformer can add deterministic, row-wise derived columns. A ColumnTransformer can separately apply median imputation and standardization to numeric columns, and a missing-category policy plus one-hot encoding to categorical columns. A final Ridge estimator learns from the resulting numeric matrix.

During cross-validation, each fitting fold learns imputation values, scaler statistics, category vocabularies and any SelectKBest rankings only from that fold’s fitting observations. This design limits several common forms of leakage. But a Pipeline cannot prevent using future-only source features, wrongly identifying the target, retaining duplicated subjects across splits or repeatedly tuning against final test labels.

How ColumnTransformer and FunctionTransformer fit together

Our FunctionTransformer first copies an input DataFrame and adds five engineered columns: age at sale, combined area, quality–area interaction, sine of sale month and cosine of sale month. The function does not modify the original data or refer to the price target. Then ColumnTransformer routes selected numerical columns through a median imputer and scaler, while routing four categorical columns through an explicit missing-label imputer and one-hot encoder.

After the transformer is fitted, get_feature_names_out() identifies the encoded and numerical features actually supplied to the regressor. The length depends on the distinct categories learned from the training partition; it should be measured, not guessed. When SelectKBest(k=15) follows the transformer, it chooses 15 of those transformed columns, rather than 15 original source fields.

Complete reproducible Python project

Install the packages with python -m pip install numpy pandas scikit-learn matplotlib jupyter. The downloadable notebook and source script contain the full executable implementation of the following workflow. They call fetch_openml(data_id=42165, as_frame=True), verify the required columns and 1,460 expected rows, reserve a test set with seed 90, generate engineered features, fit alternative Pipelines, and run the same five-fold KFold procedure for every model.

A network connection is required for OpenML data on first use. The code raises a clear error if required columns are missing rather than silently substituting a different dataset. Because the real download did not succeed in this authoring environment, the code’s substantive execution on Ames is a reproducible exercise for the reader, not a performance claim made in advance.

from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split, KFold
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.compose import ColumnTransformer

ames = fetch_openml(data_id=42165, as_frame=True)
df = ames.frame.copy()
numeric_raw = ["GrLivArea","TotalBsmtSF","OverallQual",
               "YearBuilt","YrSold","MoSold"]
categorical_raw = ["Neighborhood","HouseStyle","CentralAir","GarageType"]
X = df[numeric_raw + categorical_raw].copy()
y = pd.to_numeric(df["SalePrice"], errors="raise")
assert len(df) == 1460
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=.20, random_state=90
)
cv = KFold(n_splits=5, shuffle=True, random_state=90)
# Continue with the supplied complete notebook and script.

The four model workflows being compared

The median DummyRegressor predicts a single training-derived target median, providing a simple baseline. The raw-feature Ridge model fits standardized numerical variables and one-hot categorical variables. The engineered Ridge model adds five derived numerical columns to the same representation. The engineered plus selection model adds SelectKBest(f_regression, k=15) after encoding and scaling, keeping fifteen transformed columns.

All three Ridge candidates use the same training partition, identical five-fold KFold splitting and Ridge(alpha=20.0). The baseline is fit separately on the training targets. This controlled comparison isolates the effect of the chosen feature representation better than using unrelated models, different data splits and incompatible scores for each approach.

How to conduct the five-fold comparison correctly

After reserving 20% of the expected 1,460 rows, the development set contains 1,168 and the final test contains 292. Scikit-learn’s KFold splitter with five folds, shuffling and seed 90 generates five training/validation partitions of the development set. For each Pipeline, cross_val_score(..., scoring='neg_mean_absolute_error') yields negative values because the scoring API is oriented toward larger-is-better scores. Negate the returned values to report positive errors.

The mean of the five positive MAEs ranks candidate workflows; lower mean MAE is better under this criterion. The fold-to-fold standard deviation describes variation across those particular partitions, but is not automatically an independent confidence interval for future deployment. The selected Pipeline is cloned and fitted on the entire development set, then assessed once using untouched test data.

A separately verified cross-validation calculation

Consider hypothetical five-fold MAEs of $20,000, $22,000, $19,000, $21,000 and $23,000. Their sum is $105,000 and their mean is $21,000. This arithmetic demonstrates how to average validation error across folds. It is not an observed result from the Ames experiment and should never be copied into a project report as if produced by Python.

If a second workflow has a slightly lower average but much greater variability, the choice may warrant further investigation. Differences among folds can arise because available properties differ, outcomes vary and the sample is limited. For serious conclusions, examine the context, model complexity and stability rather than treating tiny differences in rounded scores as definitive.

How to interpret MAE, RMSE and R-squared

Mean Absolute Error (MAE) is the mean of |actual−predicted| and has the same units as sale price. RMSE takes the square root of the mean squared error, giving more influence to relatively large mistakes; it also uses price units. R² = 1 − SSE/SST measures predictive fit relative to a constant mean-based reference on the evaluated data, subject to standard caveats. An R² score can be negative on test data if the predictions are particularly poor.

The final report should include MAE, RMSE and R² for the preselected candidate, together with the median baseline. Errors should be interpreted as historical-model errors, not promised appraisal accuracy for a current property. Inspect residuals against predicted prices and large errors instead of relying on an impressive-looking coefficient of determination alone.

What can be reported now, and what must be measured on Ames?

The source specification gives 1,460 expected rows and, under an 80/20 split, the intended 1,168/292 partition. The local smoke test confirms that the three feature-preparation Pipelines and the 15-column feature-selection step run on a separately generated fictional dataset. That test checks implementation compatibility only; it is not evidence that one method improves real Ames pricing predictions.

Therefore, the following results table deliberately avoids invented prices or winners. Running the included script on OpenML data prints and saves the measured CV MAE, fold variation, selected model, held-out MAE/RMSE/R², transformed-column count and package versions. Once available, those values should replace “Run dataset experiment” in the article; model selection must remain based on the training folds.

WorkflowCV MAE (actual Ames)Test MAESelection status
Median DummyRegressorBaseline not yet evaluated on AmesPending real runReference
Raw RidgeRun dataset experimentOnly if selectedPending CV
Engineered RidgeRun dataset experimentOnly if selectedPending CV
Engineered Ridge + SelectKBestRun dataset experimentOnly if selectedPending CV

Inspect transformed names and selected columns

The source script retrieves names using selected.named_steps['preprocess'].get_feature_names_out() after fitting. If the selected estimator contains the 'select' step, its get_support() mask can be applied to the names to identify the transformed features retained. This is more defensible than saying that every original column has one counterpart in the fitted matrix.

One-hot encoding can create several columns from Neighborhood. Consequently, if only some of those indicators are retained, interpretation can become fragmented. Grouped category-level selection and stability analyses are advanced alternatives. Avoid presenting a ranking of selected neighbourhood indicators as proof of fundamental price differences among communities.

Charts that support scientific interpretation

A useful student report includes a source-data distribution plot, missingness counts, a numeric scatter plot, a month-circle diagram, and a training-only CV MAE comparison. Once the real dataset is executed, plot held-out predicted versus observed prices and a residual histogram or residual-versus-predicted scatter. Labels must distinguish United States dollar values, square feet, years, categorical counts and dimensionless scaling results.

Do not produce a synthetic chart and call it an actual Ames result. Our companion package includes a month-cycle illustration that demonstrates the mathematical mapping and a fictional practice dataset for independent exercises. The actual performance charts should be generated after running the real notebook, so any plotted score is traceable to real computation.

How feature engineering choices depend on the model

A regularized linear model can benefit from appropriate numerical scaling, category indicators and interactions that expose relationships the model cannot otherwise represent. K-nearest neighbours are particularly sensitive to feature scale and encoded distance. A decision tree can learn threshold-based nonlinearities without scaling, while Random Forests often capture some interactions without explicit polynomial multiplication. There is no one preprocessing recipe suited to every estimator.

For a controlled extension, compare Ridge Regression with a tree-based regressor using the same training split and a fixed appropriate evaluation metric. If differences arise, ask which representation suits which learning mechanism and whether the gain justifies increased complexity. Do not conclude that every engineered feature helps every algorithm or that a forest’s feature importance demonstrates causation.

Classification, rare events and chronological modelling

Feature engineering also applies beyond housing regression. A classifier may use encoded categories, interaction features and feature selection, but should be evaluated with classification measures such as macro F1 or Average Precision rather than price-prediction MAE. For imbalanced tasks, any sampling step belongs inside the relevant training fold. Topic 88: Imbalanced Datasets explains that danger.

Time-dependent features require particular care: lagged variables must refer to information that would genuinely be available at the forecast origin, grouped records must stay together where appropriate, and the intended horizon should determine the validation split. A future value accidentally embedded in an engineered column can make an otherwise elegant Pipeline invalid. Data leakage is often a design problem, not merely a software bug.

Responsible feature engineering across different populations

Historical datasets reflect specific places, periods, collection systems and social contexts. A model calibrated to older Ames sales should not be treated as current evidence for housing markets in London, Nairobi, Accra or Toronto. Area units, construction codes, neighbourhood conventions, building regulations and price distributions differ. Generalization requires suitably representative data, revalidation and correct feature definitions.

Location and housing characteristics can also act as proxies for socioeconomic inequalities. A model’s association with a neighbourhood label does not establish an inherent cause, nor does high predictive performance guarantee equitable decisions. Explain the source, transformations, limitations and intended educational use, and avoid deploying the classroom experiment for individual financial or housing decisions.

Ten-task student capstone: a reproducible feature-engineering investigation

Tasks 1–3: obtain OpenML 42165 on a connected computer; verify 1,460 rows, source information and all required names; define retrospective prediction timing; inspect missing categories, impossible months and quality ratings. Task 4: reserve the 80/20 test set with random seed 90 and fit the median-only baseline from training data. Task 5: fit the raw-feature Ridge Pipeline with training-fold imputation, standardization and one-hot encoding.

Tasks 6–8: implement five deterministic engineered features, compare engineering and SelectKBest alternatives on identical five-fold CV partitions, and record each candidate’s mean and fold variability. Task 9: select the minimum-mean-MAE configuration without consulting test data, refit on all 1,168 development rows, and calculate final held-out MAE, RMSE and R². Task 10: write a report describing data provenance, features, transformations, versions, results, limitations, failure cases, fairness concerns and why tuning or engineering does not guarantee improvement.

Thirty original student practice questions and worked answers

Answer the first ten questions to build vocabulary, the next ten to practise calculations, and the final ten to reason about modelling choices. Use the expandable answers after attempting each one independently. The numerical questions are fictional mathematics exercises, not measurements of Ames model performance.

Question 1: Define feature engineering.

Worked answer: Creating, representing, transforming or selecting model inputs for an intended prediction task.

Question 2: How does feature selection differ from feature construction?

Worked answer: Selection retains candidate columns; construction creates new quantities from available values.

Question 3: What is a raw feature?

Worked answer: A directly recorded input such as GrLivArea.

Question 4: Is Neighborhood nominal or ordinal?

Worked answer: Nominal: its names lack an inherent rank.

Question 5: What type is OverallQual?

Worked answer: An ordinal rating already encoded numerically; equal code gaps are a modelling assumption.

Question 6: What is one-hot encoding?

Worked answer: Representing categories as separate indicator columns learned from training data.

Question 7: What is a missingness indicator?

Worked answer: An indicator typically equal to one where the source field was missing, otherwise zero.

Question 8: Does feature scaling help every estimator equally?

Worked answer: No. It often matters more for regularized or distance-based models than ordinary trees.

Question 9: Why not fit a scaler on the entire dataset?

Worked answer: Test-set statistics would influence the training representation, causing leakage.

Question 10: Can predictive importance prove causation?

Worked answer: No; model associations do not establish causal effects.

Question 11: Standardize x=85 with mean 70 and standard deviation 10.

Worked answer: (85−70)/10 = 1.5.

Question 12: Min-max scale 50 using minimum 20 and maximum 80.

Worked answer: (50−20)/(80−20) = 0.5.

Question 13: Robust-scale 85 with median 70, Q1=50 and Q3=80.

Worked answer: (85−70)/(80−50) = 0.5.

Question 14: Calculate log1p(99).

Worked answer: ln(100) ≈ 4.6052.

Question 15: Find house age if built in 1998 and sold in 2008.

Worked answer: 2008−1998 = 10 calendar years.

Question 16: Combine above-ground area 1,500 and basement area 400.

Worked answer: 1,500+400 = 1,900 square feet; not necessarily formal habitable area.

Question 17: Calculate quality–area interaction for 1,500 sqft and quality 8.

Worked answer: 1,500×8=12,000 square-foot–rating units.

Question 18: Find area per room for 1,600 sqft and eight rooms.

Worked answer: 1,600/8=200 square feet per room.

Question 19: What are January’s sine/cosine month coordinates?

Worked answer: Month 1 gives sin(0)=0 and cos(0)=1.

Question 20: Average hypothetical fold MAEs 20k, 22k, 19k, 21k and 23k.

Worked answer: Sum 105k divided by five gives mean 21k price units.

Question 21: Why should SelectKBest be inside CV?

Worked answer: Its relationship-to-target scores must be learned using only each training fold.

Question 22: What if an engineered age is negative?

Worked answer: Investigate source accuracy or conventions; do not silently clip or delete.

Question 23: What problem can target encoding create?

Worked answer: Leakage and category memorization without cross-fitting and smoothing.

Question 24: Why might a scaler transform a test value above one using min-max?

Worked answer: It lies above the training maximum and clipping was not enabled.

Question 25: Why are January and December numerically misleading?

Worked answer: Month codes 1 and 12 are far apart linearly despite being adjacent cyclically.

Question 26: What does k=15 in SelectKBest mean after one-hot encoding?

Worked answer: Choose 15 transformed columns, not necessarily 15 raw source variables.

Question 27: When would you use GroupKFold?

Worked answer: When related observations must be kept from appearing in both fitting and validation subsets.

Question 28: How do you pick the final model?

Worked answer: Compare training-only CV MAE with the same folds; choose the minimum under the predefined rule.

Question 29: What is wrong with using sale month for a pre-listing quote?

Worked answer: The actual future transaction month may be unknown at quote time.

Question 30: How should real Ames results be reported?

Worked answer: Run OpenML 42165, record versions and splits, report measured CV scores and untouched test metrics, and disclose limitations.

Which feature engineering choice would you make? Eight interactive scenarios

Try the following classroom decisions. They are intentionally short so that students can compare their reasoning with the explanation. More than one solution can sometimes be defensible if the prediction objective, sample size or domain constraints change.

Scenario 1: A student uses all sale prices to compute neighbourhood averages before splitting.

Reasoning: Stop: that leaks targets into training. Split first and use appropriate cross-fitting or another encoding.

Scenario 2: A 10,000-column sparse one-hot matrix overwhelms the available memory.

Reasoning: Consider infrequent-level grouping or suitable sparse representations, learned inside training folds; test alternatives.

Scenario 3: A test property has a new neighbourhood name.

Reasoning: Use the documented unknown-category policy; with handle_unknown=’ignore’ the relevant one-hot indicators become zero.

Scenario 4: Model performance improves on training data but deteriorates on validation.

Reasoning: The change may overfit. Compare across folds, remove unnecessary complexity or regularize.

Scenario 5: A student rescales the whole dataset before KFold.

Reasoning: Move the scaler inside a Pipeline so its parameters are learned separately on training folds.

Scenario 6: The model relies on a future sale month for a quote made today.

Reasoning: Redefine the inputs: an unavailable future feature must be removed or replaced with information available at prediction time.

Scenario 7: A correlated engineered area sum changes Ridge coefficients.

Reasoning: This may reflect multicollinearity; inspect validation, stability and interpretability rather than inferring causation.

Scenario 8: Engineered Ridge has slightly worse CV MAE than raw Ridge.

Reasoning: Select the raw version under the predefined MAE criterion; engineering does not guarantee improvement.

Common mistakes: an audit checklist for student projects

Before publication, look for these avoidable errors: (1) adding arbitrary columns; (2) keeping identifiers as measurements; (3) encoding nominal categories as ordered integers; (4) assuming ordinal steps are equally meaningful; (5) treating missing as unknown when it means not applicable; (6) imputing with test statistics; (7) scaling the full dataset; (8) selecting features before cross-validation; (9) target encoding without cross-fitting; (10) using future-only features; (11) mixing months indexed 0–11 and 1–12; (12) using a sine month representation without cosine; (13) creating unstable ratios with zero denominators; (14) applying log1p to invalid negative inputs; (15) interpreting a derived area sum as legally habitable area.

Continue the audit: (16) assuming every estimator needs scaling; (17) adding excessive polynomial degrees; (18) interpreting correlation as cause; (19) removing all correlated variables without justification; (20) assuming selection always improves accuracy; (21) confusing encoded columns with original fields; (22) ignoring unknown categories; (23) ignoring category cardinality; (24) choosing a model by test-set error; (25) reporting a negative scoring-interface value as negative absolute error; (26) inventing performance scores; (27) omitting random seeds; (28) omitting software versions; (29) failing to check data licences; (30) treating historic local prices as current global valuations. Each is addressed by explicit data definitions, training-only transformations, suitable metrics, verified outputs and transparent limitations.

Feature-engineering formula cheat sheet

Standard score: (x−μ)/σ. Min-max: (x−minimum)/(maximum−minimum). Robust scaling: (x−median)/(Q3−Q1). Logarithmic transform: ln(1+x) for admissible x; inverse exp(z)−1. House age: sale year−construction year. Combined area: above-ground area+basement area. Quality interaction: above-ground area×ordinal quality code.

Ratio: numerator/valid nonzero denominator. Month sine and cosine: sin(2π(m−1)/12) and cos(2π(m−1)/12). MAE: average absolute prediction error. RMSE: square root of average squared prediction error. R²: one minus squared residual sum relative to total target variation around its evaluation mean. The downloadable resource package includes this formula list with example values.

Four-week learning roadmap

Week 1: learn the dataset fields, variable types, prediction timing, missingness and source documentation; calculate age, area and category examples. Week 2: compare StandardScaler, MinMaxScaler and RobustScaler on practice values, and implement one-hot encoding and missing-value strategies within Pipelines.

Week 3: construct quality–area and cyclical-month features; learn the difference between filter, wrapper and embedded selection; compare KFold candidate MAEs without touching test labels. Week 4: run the OpenML project, produce a CV comparison and held-out diagnostic charts, and write a responsible machine-learning experiment report with code versions, caveats and limitations.

Frequently asked questions

What is feature engineering in machine learning?

It is the disciplined creation, representation, transformation or selection of inputs for a given predictive task.

What is the difference between feature engineering and selection?

Engineering changes or creates candidate features; selection retains a subset.

Why should numerical features be scaled?

Some models compare distances or penalize coefficients in ways sensitive to relative feature magnitude.

Is min-max scaling the same as standardization?

No. Min-max uses a range; standardization uses mean and standard deviation.

Do all machine learning algorithms need scaling?

No. Ordinary decision trees and Random Forests often work without numerical scaling.

Should every categorical field use ordinal encoding?

No. Arbitrary numeric ordering can misrepresent nominal categories.

Can one-hot encoding handle unseen categories?

Yes, with a documented unknown-category policy such as handle_unknown=’ignore’.

How do I create time-based features safely?

Use only available timestamps; respect time ordering and consistent calendar conventions.

Does SelectKBest always improve prediction?

No. It may discard useful information and miss interactions; validate it.

Why must feature selection be inside cross-validation?

Selection scores estimated using validation targets produce leakage.

Do derived features prove causal relationships?

No. Predictive association is not causal evidence.

Are Ames Housing results included as verified metrics?

Not yet. The downloadable script computes them once the actual dataset can be fetched and evaluated.

Can the Ames model value my home today?

No. It is a retrospective historical educational exercise from a particular location and period.

Why is ColumnTransformer useful?

It applies appropriate pipelines to numerical and categorical subsets consistently.

Can engineered features make a model worse?

Yes. They may add noise, collinearity, impossible values, leakage or excessive complexity.

Related lessons and trustworthy technical sources

For prerequisite practice, review Data Quality Explained (Topic 83), Student Grade Prediction (Topic 86), Machine Learning Classification (Topic 87) and Hyperparameter Tuning (Topic 89). These related tutorials extend different parts of the modelling workflow instead of duplicating a related-post list.

Authoritative resources include Scikit-learn preprocessing, ColumnTransformer, Pipeline, feature selection, data leakage and common pitfalls, TargetEncoder and the OpenML Ames Housing source.

Conclusion: improve the information, then test the improvement

Feature engineering is not a competition to produce the most columns or the most complex Pipeline. It is a reasoned process for representing the information genuinely available at a prediction point. For the historical housing exercise, age, area combinations, interactions, category indicators and cyclical months are plausible candidates to investigate. They do not become proven improvements merely because we can calculate them. Every learned transformation and selection step must be assessed in training-only validation before a model is evaluated on untouched observations.

The most valuable habit to develop is to separate what the feature means, how it is calculated, when the information is available, and what reliable evidence shows about its effect. The accompanying executable source and notebook let students complete the evidence-producing Ames experiment once the OpenML download is available. Report whatever the measurements show—even if raw inputs perform better—and write the final limitations as carefully as the code.

Companion resources: A downloadable ZIP package has been prepared containing the executable Python script, Jupyter notebook, dataset-source guide, fictional practice CSV, leakage checklist, formula sheet, reproducibility notes and original month-cycle visualization. The original Ames Housing records have intentionally not been redistributed; learners can retrieve them directly from OpenML using the supplied code.