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
bicyclebe 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 field | Potential model representation | Role |
|---|---|---|
| Signup date | Account age in days at prediction time | Numeric feature |
| Plan name | Encoded plan category | Categorical feature |
| Monthly charge | Amount in a consistent currency | Numeric feature |
| Support tickets | Count during the preceding 30 days | Numeric feature |
| Cancellation status in next 30 days | 0 or 1 | Target |
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.
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:
| Technique | Example | Why it may help |
|---|---|---|
| Ratios | debt / income | Express a relationship instead of two isolated measurements |
| Differences | Current balance minus previous balance | Capture change |
| Counts | Purchases in the preceding week | Describe recent activity |
| Date features | Day of week or account age | Expose calendar or elapsed-time patterns |
| Aggregations | Average temperature over the past hour | Summarize repeated measurements |
| Interactions | advertising_spend * season_indicator | Represent combined effects |
| Log transformations | log(1 + positive_count) | Compress large positive values |
| Domain-specific signals | Sensor vibration energy | Connect 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.
| Device | Device: phone | Device: laptop | Device: tablet |
|---|---|---|---|
| Phone | 1 | 0 | 0 |
| Tablet | 0 | 0 | 1 |
| Laptop | 0 | 1 | 0 |
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:
Here, is an original value, is the mean, and is the standard deviation used by the scaler. For a feature with training mean and standard deviation , the value becomes:
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:
If training values range from to , a value of becomes .
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):
Here and 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:
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 family | Typical scaling sensitivity | Reason |
|---|---|---|
| k-nearest neighbors and k-means | High | Distances depend on numeric scales |
| Support vector machines | Often high | Geometry and kernel calculations depend on feature magnitudes |
| Regularized linear/logistic models | Often high | Regularization interacts with feature scale |
| Neural networks | Often beneficial | Well-scaled inputs can aid optimization |
| Decision trees and random forests | Usually low | Axis-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:
- Define the prediction time and available input fields.
- Split records into training and held-out sets using a method appropriate to the task.
- Fit imputation, encoding, scaling, and feature-selection steps only on training data.
- Reuse the fitted transformations to transform validation, test, and production data.
- 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:
ColumnTransformerhandles numeric and categorical columns differently.SimpleImputerfills missing numeric values using training-set statistics, and missing categories using the training-set most frequent value.StandardScalerlearns 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.fitfits preprocessing and the classifier together on the training set, whilePipeline.predictreuses 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:
Here is the position within a cycle and is its period. For 24-hour time, . 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
| Mistake | Consequence | Better practice |
|---|---|---|
| Encode an unordered category as arbitrary integers | May imply a false ordering | Use one-hot encoding or a model-compatible categorical strategy |
| Standardize all data before train/test splitting | Leaks test-set information | Fit transformers on the training partition only |
| Fit preprocessing before cross-validation | Leaks statistics across validation folds | Put preprocessing in the cross-validated pipeline |
| Use fields produced after the target event | Unrealistic evaluation results | Define prediction time and verify feature availability |
| Apply one-hot encoding to a huge identifier column | Excessive dimensionality and overfitting risk | Assess high-cardinality strategies or drop the identifier |
| Scale tree inputs automatically without considering the model | Adds complexity with little gain in many cases | Match transformations to the estimator |
| Use target encoding on the same rows without safeguards | Can memorize target information | Use leakage-resistant cross-fitting and smoothing |
| Create many untested features | Greater complexity without guaranteed benefit | Compare 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:
- Train a simple baseline using minimally prepared inputs.
- Add one family of features, such as recent activity counts.
- Compare validation performance using an appropriate metric.
- Check whether the change improves performance across meaningful subsets, not only the overall average.
- Review inference latency, data availability, maintenance cost, and privacy impact.
- 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
- What is the difference between feature engineering and categorical encoding?
- Why might one-hot encoding be preferable to integer coding for payment methods?
- If a standard scaler was fitted on training data, should it be refitted when test records arrive?
- Does standardization make every feature follow a normal distribution?
- Why might account activity measured after cancellation create leakage?
- Which scaling approaches would you consider for a distance-based model with extreme outliers?
Show suggested answers
- Feature engineering creates or selects useful model inputs. Encoding converts categories or other nonnumeric values into suitable numeric representations.
- Payment methods usually have no natural rank, and integer values could suggest a misleading order or distance.
- No. Use the already fitted scaler to transform the test records.
- No. Standardization changes the mean and standard deviation, not the fundamental shape of the distribution.
- The future activity would not be available when a real cancellation prediction is made.
- Robust scaling is a candidate; compare it against suitable alternatives using leakage-safe validation. Address whether the outliers are valid before choosing transformations.
Related PlainCS concepts
- AI Knowledge Map: The broader sequence of AI foundations.
- Data Cleaning and Preprocessing: Inspect and correct raw records before creating model features.
- Data Types and Data Collection for AI: Understand source data and its constraints.
- Data Splitting, Labeling, and Leakage: Design unbiased training and evaluation partitions.
- Vectors and Matrices: Represent examples as vectors and matrices.
- Descriptive and Inferential Statistics: Understand the statistics used by preprocessing methods.
- Model Training, Overfitting, and Generalization: Connect prepared inputs to learning and model reliability.
References and further reading
Related articles in
- AI Agents and Tool-Using Workflows — Learn agent goals, tool invocation, planning, state, permissions, and how to evaluate multi-step AI workflows.
- AI Development Tools: Git, Jupyter, and APIs — Learn how Git, Jupyter notebooks, Python environments, and APIs fit together in reproducible, secure artificial intelligence workflows.
- How AI Is Changing Theoretical Computer Science — AI is beginning to help researchers explore algorithms, mathematical structures, and formal proofs. Here is what it can do, what still needs human judgment, and why verification matters.