Artificial Intelligence • Data Engineering and Preparation • 17 min read

Feature Engineering, Encoding, and Scaling

A machine-learning model receives an input representation, not the original meaning of a real-world situation. A record such as “customer joined in March, uses a basic plan, and has made three support requests” must be represented in a way that an algorithm can process. How that representation is constructed can substantially affect performance, interpretability, cost, and reliability.

Three closely related activities are feature engineering, encoding, and scaling. Feature engineering selects or derives useful variables; encoding represents values such as categories as numbers; and scaling adjusts the numerical range or distribution of features. These activities belong to the same preparation process, but they solve different problems.

This article follows Data Cleaning and Preprocessing. Its focus is building useful model inputs from valid records. The next article, Data Splitting, Labeling, and Leakage, treats data partitioning and evaluation contamination in detail.

First intuition: models need usable representations

Suppose a delivery model receives this order: “placed on Monday, distance 12 km, transport type bicycle.” A basic numerical model cannot use the sentence directly. We might derive day_of_week = Monday, keep distance_km = 12, and encode the transport type into numerical columns. We might then scale distance because its magnitude differs from binary indicators.

These steps answer different questions:

  • Feature engineering: Which facts about the order might help predict delivery time?
  • Encoding: How should a category like bicycle be represented numerically?
  • Scaling: How should numerical magnitudes be adjusted for algorithms sensitive to scale?

For example, a one-hot encoding of transport_type creates indicator columns such as is_bicycle and is_car. The model can then learn different associations without pretending that one transport type is numerically “greater” than another. Transformations must be fitted on training data alone to avoid data leakage.

1. From observations to model features

A feature is a measurable or computed characteristic used as an input to a model. A target (or label in a supervised task) is the quantity the model is supposed to predict. A feature vector contains the values of the selected features for one example; a feature matrix arranges many examples into rows and features into columns.

For a subscription-cancellation prediction task, raw fields might include the date an account opened, the plan name, monthly charges, number of support tickets, and cancellation status.

Raw fieldPotential model representationRole
Signup dateAccount age in days at prediction timeNumeric feature
Plan nameEncoded plan categoryCategorical feature
Monthly chargeAmount in a consistent currencyNumeric feature
Support ticketsCount during the preceding 30 daysNumeric feature
Cancellation status in next 30 days0 or 1Target

The phrase at prediction time is critical. A feature must be available when the system makes its real prediction. A support-ticket count from the future would make a training dataset appear unusually informative, but the deployed system could not use it.

Raw customer record flows into feature construction, categorical encoding, numerical scaling, and an input vector
Preparation is a sequence of transformations, not an invitation to use every available field.

2. What feature engineering means

Feature engineering is the process of selecting, transforming, or combining available data to create representations suitable for a learning task. The useful feature is not always a field directly stored in a database.

For example, a transaction dataset may record a transaction amount, timestamp, merchant, and account. Depending on the task, useful derived features could be:

  • Number of transactions within the preceding hour.
  • Total amount spent during the preceding seven days.
  • Time since the last transaction.
  • Whether the merchant is new to the account.
  • Difference between the transaction amount and the account’s past median amount.

These features summarize patterns that may be harder for some models to discover from raw records. They must be computed using past or present information, never information that becomes available only after the prediction.

2.1 Feature creation and transformation

Common techniques include:

TechniqueExampleWhy it may help
Ratiosdebt / incomeExpress a relationship instead of two isolated measurements
DifferencesCurrent balance minus previous balanceCapture change
CountsPurchases in the preceding weekDescribe recent activity
Date featuresDay of week or account ageExpose calendar or elapsed-time patterns
AggregationsAverage temperature over the past hourSummarize repeated measurements
Interactionsadvertising_spend * season_indicatorRepresent combined effects
Log transformationslog(1 + positive_count)Compress large positive values
Domain-specific signalsSensor vibration energyConnect measurements to subject knowledge

A good derived feature is meaningful for the objective, computable when needed, and stable enough to use in production. Extra columns are not automatically improvements: irrelevant, noisy, redundant, or leakage-prone features can make a model worse.

2.2 Feature selection versus feature extraction

These terms overlap with feature engineering but refer to different operations:

  • Feature selection chooses a subset of existing features. Examples include selecting variables using domain knowledge, statistical tests, or model-based importance measures.
  • Feature extraction constructs a representation from the original data. Examples include principal components, image embeddings, and signal-frequency features.
  • Feature engineering is the broader activity that may include both, plus manual transformations and derived variables.

For detailed treatment of principal components, see Dimensionality Reduction and PCA.

3. Encoding categorical data

A categorical variable identifies a group or class rather than a measured amount. Examples include operating-system type, payment method, and product category. Most conventional machine-learning estimators require numerical input, so categories must be represented numerically.

3.1 One-hot encoding

One-hot encoding creates an indicator column for each category. A value receives 1 in its corresponding column and 0 in the others.

DeviceDevice: phoneDevice: laptopDevice: tablet
Phone100
Tablet001
Laptop010

One-hot encoding does not impose an artificial ranking between categories. It is a sensible starting choice for many nominal variables, where the categories have no natural order.

Its limitation is dimensionality: a column with thousands of distinct values may expand into thousands of indicator columns. In that case, consider infrequent-category grouping, hashing, an appropriate model that natively handles categories, or another carefully evaluated encoding method.

3.2 Ordinal encoding

Ordinal encoding assigns integers to categories, such as low = 0, medium = 1, and high = 2.

This can represent a known order, but it does not mean that the distance from low to medium equals the distance from medium to high. For models sensitive to numerical distances or linear effects, integer codes may impose a misleading assumption.

Do not assign arbitrary integer labels to unordered categories and assume the model will understand that the numbers are only names. Some tree-based models can work with coded categories under appropriate conditions, but behavior depends on the estimator and representation.

3.3 Other categorical encodings

  • Frequency or count encoding: Replace each category with its observed frequency or count. This compresses high-cardinality features but may lose important distinctions.
  • Target encoding: Replace a category with a statistic derived from the target, typically with smoothing. It must be fitted using careful training-only and cross-fitting procedures to avoid leakage and overfitting.
  • Hashing: Map categories into a fixed number of columns. It controls dimension but can create collisions.
  • Learned embeddings: Represent categories as trainable dense vectors, common in recommendation and deep-learning systems.

Choose based on category order, number of distinct values, estimator behavior, and validation performance. There is no universally best encoding.

4. Scaling numerical features

Feature scaling changes the numeric representation of a feature without changing which observation it belongs to. Scaling matters especially for algorithms that depend on distances, gradients, or regularization.

Suppose a dataset contains customer age in years (roughly 18–80) and annual income in currency units (roughly 20,000–200,000). In an unscaled Euclidean distance calculation, differences in income could dominate differences in age merely because of measurement units.

4.1 Standardization (z-score scaling)

Standardization commonly transforms a numeric value using the training-set mean and standard deviation:

z=x−μσz = \frac{x - \mu}{\sigma}

Here, xx is an original value, μ\mu is the mean, and σ\sigma is the standard deviation used by the scaler. For a feature with training mean 5050 and standard deviation 1010, the value 6565 becomes:

z=65−5010=1.5z = \frac{65 - 50}{10} = 1.5

A standard scaler typically centers training data near zero and scales it to unit variance. This does not make the distribution normal; it only changes its location and scale. For a constant feature, software must handle the zero-variance case explicitly.

4.2 Min-max scaling

Min-max scaling maps values relative to an observed minimum and maximum, commonly into the interval from 0 to 1:

x′=x−xmin⁡xmax⁡−xmin⁡x' = \frac{x - x_{\min}}{x_{\max} - x_{\min}}

If training values range from 1010 to 5050, a value of 3030 becomes 0.50.5.

This approach preserves relative positions within the range but is sensitive to extreme minimum and maximum values. Values observed during inference can also fall outside the training range, producing scaled values below 0 or above 1 unless the transformer explicitly clips them.

4.3 Robust scaling

A robust scaler uses statistics less sensitive to extreme values, commonly the median and interquartile range (IQR):

x′=x−median⁡(X)Q3−Q1x' = \frac{x - \operatorname{median}(X)}{Q_3 - Q_1}

Here Q1Q_1 and Q3Q_3 are the first and third quartiles. This can be useful when outliers distort the mean and standard deviation, although robust scaling does not remove outliers or guarantee good performance.

4.4 Normalizing individual samples

Vector normalization is different from standardizing a feature column. It rescales an entire row or vector, often to unit Euclidean length:

x^=x∥x∥2\hat{\mathbf{x}} = \frac{\mathbf{x}}{\|\mathbf{x}\|_2}

It is used when vector direction matters, such as certain text or similarity tasks. Zero-length vectors need special handling. Review Vector and Matrix Operations for the norm and its interpretation.

4.5 Which algorithms need scaling?

Algorithm familyTypical scaling sensitivityReason
k-nearest neighbors and k-meansHighDistances depend on numeric scales
Support vector machinesOften highGeometry and kernel calculations depend on feature magnitudes
Regularized linear/logistic modelsOften highRegularization interacts with feature scale
Neural networksOften beneficialWell-scaled inputs can aid optimization
Decision trees and random forestsUsually lowAxis-aligned split thresholds are largely unaffected by monotonic rescaling

These are guidelines, not absolute rules. Preprocessing decisions should be tested using a representative validation procedure.

5. Apply the transformations in the right order

Data leakage happens when a model-development procedure uses information it would not legitimately have at prediction time or during an unbiased evaluation. Encoding and scaling can leak information even when the target column is never directly included in the input.

For example, calculating a scaler’s mean over the entire dataset before dividing it into training and test sets allows the held-out test distribution to affect the training transformation.

A sound workflow is:

  1. Define the prediction time and available input fields.
  2. Split records into training and held-out sets using a method appropriate to the task.
  3. Fit imputation, encoding, scaling, and feature-selection steps only on training data.
  4. Reuse the fitted transformations to transform validation, test, and production data.
  5. Evaluate on held-out data without refitting preprocessing on it.

For cross-validation, fit the transformations within each training fold, not once on the full training dataset before cross-validation. A scikit-learn Pipeline helps enforce this arrangement.

Note: A feature derived separately for each individual record, using only information legitimately available for that record, may not need a training-fitted statistic. Data-dependent transformations such as means, category vocabularies, and selected-feature rankings do.

6. Worked example: build a leakage-safe preprocessing pipeline

Consider a dataset of customer accounts. It contains a numeric measure (monthly_spend), a numeric count (support_tickets), a category (plan), and a binary target (cancelled). We want to derive spend_per_ticket_plus_one, standardize numeric inputs, and one-hot encode the plan.

import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report

records = pd.DataFrame({
    "monthly_spend": [20, 50, 30, 80, 25, 60, 45, 100, 35, 65, 55, 90],
    "support_tickets": [3, 0, 1, 0, 4, 1, 2, 0, 3, 1, 2, 0],
    "plan": ["basic", "premium", "basic", "premium", "basic", "premium",
             "basic", "premium", "basic", "premium", "basic", "premium"],
    "cancelled": [1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0],
})

# A row-wise transformation using information available at prediction time.
records["spend_per_ticket_plus_one"] = (
    records["monthly_spend"] / (records["support_tickets"] + 1)
)

features = ["monthly_spend", "support_tickets",
            "spend_per_ticket_plus_one", "plan"]
X = records[features]
y = records["cancelled"]

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=42, stratify=y
)

numeric = ["monthly_spend", "support_tickets", "spend_per_ticket_plus_one"]
categorical = ["plan"]

numeric_pipeline = Pipeline([
    ("impute", SimpleImputer(strategy="median")),
    ("scale", StandardScaler()),
])

categorical_pipeline = Pipeline([
    ("impute", SimpleImputer(strategy="most_frequent")),
    ("encode", OneHotEncoder(handle_unknown="ignore")),
])

preprocessing = ColumnTransformer([
    ("numeric", numeric_pipeline, numeric),
    ("categorical", categorical_pipeline, categorical),
])

model = Pipeline([
    ("prepare", preprocessing),
    ("classifier", LogisticRegression(max_iter=1000)),
])

model.fit(X_train, y_train)
predictions = model.predict(X_test)
print(classification_report(y_test, predictions, zero_division=0))

The important details are architectural:

  • ColumnTransformer handles numeric and categorical columns differently.
  • SimpleImputer fills missing numeric values using training-set statistics, and missing categories using the training-set most frequent value.
  • StandardScaler learns the numeric mean and scale from training data only.
  • OneHotEncoder(handle_unknown="ignore") can transform an unseen category without failing; an unknown category produces zeros in that feature’s one-hot columns.
  • Pipeline.fit fits preprocessing and the classifier together on the training set, while Pipeline.predict reuses the learned transformations on the test set.

The sample is deliberately tiny and only illustrates implementation. Its classification score is not meaningful evidence of deployment performance. A real project needs substantially more representative data, an appropriate split, suitable baselines, and repeated evaluation.

For real deployment, preserve the entire fitted pipeline and its feature contract rather than saving only the classifier.

7. Date, text, and high-dimensional features

Not every input belongs in a simple numeric/categorical preprocessing pipeline.

7.1 Dates and cyclic time

A timestamp may support features such as elapsed time, hour of day, or weekday. Some temporal values are cyclic: Sunday is adjacent to Monday, even if weekday integers place them at opposite ends of the range. A cyclic representation can use sine and cosine:

s=sin⁡(2πtP),c=cos⁡(2πtP)s = \sin\left(\frac{2\pi t}{P}\right),\qquad c = \cos\left(\frac{2\pi t}{P}\right)

Here tt is the position within a cycle and PP is its period. For 24-hour time, P=24P=24. This representation is useful when periodic closeness matters, but may not be necessary for every model.

7.2 Text and images

Text can be represented through counts, TF-IDF vectors, or learned embeddings. Images can be represented through pixel arrays or features from a pretrained vision model. These are also forms of feature extraction, but the correct approach depends on the task and model family.

The later PlainCS articles on Natural Language Processing and Computer Vision explore those specialized representations.

8. Common mistakes and trade-offs

MistakeConsequenceBetter practice
Encode an unordered category as arbitrary integersMay imply a false orderingUse one-hot encoding or a model-compatible categorical strategy
Standardize all data before train/test splittingLeaks test-set informationFit transformers on the training partition only
Fit preprocessing before cross-validationLeaks statistics across validation foldsPut preprocessing in the cross-validated pipeline
Use fields produced after the target eventUnrealistic evaluation resultsDefine prediction time and verify feature availability
Apply one-hot encoding to a huge identifier columnExcessive dimensionality and overfitting riskAssess high-cardinality strategies or drop the identifier
Scale tree inputs automatically without considering the modelAdds complexity with little gain in many casesMatch transformations to the estimator
Use target encoding on the same rows without safeguardsCan memorize target informationUse leakage-resistant cross-fitting and smoothing
Create many untested featuresGreater complexity without guaranteed benefitCompare against a baseline using valid evaluation

In production, also plan for schema drift: newly appearing categories, changing units, columns that disappear, and feature calculations that no longer match training. A stable model requires a stable, monitored input contract.

9. How to evaluate whether a feature helps

A transformation is useful only if it improves a relevant objective under trustworthy testing. A disciplined experiment could proceed as follows:

  1. Train a simple baseline using minimally prepared inputs.
  2. Add one family of features, such as recent activity counts.
  3. Compare validation performance using an appropriate metric.
  4. Check whether the change improves performance across meaningful subsets, not only the overall average.
  5. Review inference latency, data availability, maintenance cost, and privacy impact.
  6. Retain the feature only when its benefits justify its complexity and risks.

Feature importance scores and correlations are helpful exploratory tools, but neither alone proves that a feature causes a result or will remain useful when circumstances change.

10. Check your understanding

  1. What is the difference between feature engineering and categorical encoding?
  2. Why might one-hot encoding be preferable to integer coding for payment methods?
  3. If a standard scaler was fitted on training data, should it be refitted when test records arrive?
  4. Does standardization make every feature follow a normal distribution?
  5. Why might account activity measured after cancellation create leakage?
  6. Which scaling approaches would you consider for a distance-based model with extreme outliers?
Show suggested answers
  1. Feature engineering creates or selects useful model inputs. Encoding converts categories or other nonnumeric values into suitable numeric representations.
  2. Payment methods usually have no natural rank, and integer values could suggest a misleading order or distance.
  3. No. Use the already fitted scaler to transform the test records.
  4. No. Standardization changes the mean and standard deviation, not the fundamental shape of the distribution.
  5. The future activity would not be available when a real cancellation prediction is made.
  6. Robust scaling is a candidate; compare it against suitable alternatives using leakage-safe validation. Address whether the outliers are valid before choosing transformations.

References and further reading

Related articles in

Image preview

Fit