Features and Labels
A complete guide to Features and Labels in Machine Learning: independent variables vs target outputs, feature matrices ($X$), target vectors ($y$), encoding types, and feature selection.
Imagine you are an investigator solving a mystery. To reach a conclusion, you collect clues: shoe size, tire tracks, security footage timestamps, and phone records. Each clue provides a measurable piece of information. Your final question is: 'Did this suspect commit the crime or not?' In machine learning: • All the clues, measurements, and pieces of evidence are called **Features** (conventionally denoted by the uppercase letter $\mathbf{X}$). • The final answer or outcome you are trying to predict is called the **Label** or **Target** (conventionally denoted by the lowercase letter $\mathbf{y}$). Understanding the distinction between features and labels is the foundation upon which supervised machine learning datasets are built.
Definition
In machine learning, Features are the individual, measurable input variables ($X$) used by a model to generate predictions. The Label (or Target) is the ground-truth outcome variable ($y$) that the model is trained to predict.
Why It Matters
A machine learning model has no independent eyes, ears, or real-world background: it understands the world exclusively through the features provided in its dataset. If you want to predict property values, but your dataset includes the seller's favorite color while omitting square footage and location, even the most advanced model will struggle. The quality, relevance, and preparation of your features determine the practical limits of your model's accuracy.
How It Works
Here is how features and labels are organized in machine learning: 1. Mathematical Structure: • The Feature Matrix ($\mathbf{X}$): A 2D table of shape $(N, D)$, where $N$ is the number of records (rows) and $D$ is the number of feature columns. Uppercase $\mathbf{X}$ is standard mathematical notation for a 2D matrix. • The Target Vector ($\mathbf{y}$): A 1D array of length $N$, where each entry $y_i$ represents the correct label for row $X_i$. Lowercase $\mathbf{y}$ indicates a 1D vector. 2. Common Feature Types: • Continuous Numerical: Real numbers on an open scale (such as area: 1,850 sq ft, temperature: 72.5°F, or price: $350.00). • Discrete Numerical: Integer count values (such as bedroom count: 3, or website clicks: 12). • Nominal Categorical: Distinct categories with no inherent mathematical ranking (such as city names: ['New York', 'London', 'Tokyo']). These are converted into numerical formats using One-Hot Encoding. • Ordinal Categorical: Categories that carry a natural order (such as education levels: ['High School', 'Bachelor', 'Master', 'PhD']). These are converted using Ordinal Encoding. • Text and Sensory Data: Unstructured text, audio, or images, which are transformed into numerical vector embeddings. 3. Feature Selection vs Feature Extraction: • Feature Selection: Choosing the most informative original features and removing redundant or unhelpful columns. • Feature Extraction: Transforming high-dimensional data into a smaller set of combined features (such as through PCA or convolutional feature maps).
Tabular Machine Learning Data Architecture (X and y)
Key Points
- Features ($X$) are the input measurements; the Label ($y$) is the output target to be predicted.
- In code, features are organized as a 2D matrix $\mathbf{X}$ and labels as a 1D vector $\mathbf{y}$.
- Categorical features must be converted into numerical values through encoding methods like One-Hot Encoding.
- Data leakage occurs when a feature contains information that would not actually be available during real-time prediction.
- Careful feature selection simplifies models and speeds up training without sacrificing accuracy.
Steps
Identify the Target Label (y)
Clearly isolate the single outcome you want to predict, noting whether it is continuous (Regression) or categorical (Classification).
Gather and Audit Features (X)
Collect attributes that would genuinely be available at the moment of prediction. Exclude any variables that contain future information.
Encode Categorical Columns
Apply One-Hot Encoding to unordered categories and Ordinal Encoding to ranked attributes so algorithms can process them numerically.
Inspect Correlations and Redundancy
Check correlation matrices to remove duplicate or near-identical features that could create multicollinearity.
Verify Matrix Dimensions
Confirm that feature matrix $\mathbf{X}$ has dimensions $(N, D)$ with no missing values, and target vector $\mathbf{y}$ has matching length $N$.
Formula
Standardization (Z-Score):
z = \frac{x - \mu}{\sigma}, \quad \mu = \frac{1}{N}\sum_{i=1}^N x_i, \quad \sigma = \sqrt{\frac{1}{N}\sum_{i=1}^N (x_i - \mu)^2}
Min-Max Normalization:
x_{norm} = \frac{x - x_{min}}{x_{max} - x_{min}} \in [0, 1]
Smoothed Target Encoding (Empirical Bayes Shrinkage):
S_k = \lambda(n_k) \cdot \bar{y}_k + (1 - \lambda(n_k)) \cdot \bar{y}_{global}, \quad \lambda(n_k) = \frac{n_k}{n_k + m}
\text{where } n_k \text{ is category count, and } m \text{ is smoothing weight dampening rare categories.}Examples
Customer Churn Prediction
Features ($X$): Account tenure, monthly subscription cost, customer service contacts, and usage volume. Label ($y$): Binary status (1 = Canceled, 0 = Active).
Vehicle Resale Valuation
Features ($X$): Odometer reading, manufacturing year, engine size, fuel type, and transmission. Label ($y$): Sale price in dollars.
Real-World Examples
Retail Shopping Basket Predictions
Retailers analyze changes in customer purchase baskets over time. Features include subtle changes in product categories (like switching to unscented lotions or vitamins) to anticipate customer needs and tailor offers.
Feature Engineering in Data Competitions
In competitive data science, participants often work with the same standard algorithms. Top-performing entries usually succeed because of creative feature engineering, such as creating rolling averages, interaction ratios, and domain-specific indicators that give the model clearer signals.
Technical Examples
import pandas as pd
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.compose import ColumnTransformer
# 1. Raw messy business DataFrame
data = pd.DataFrame({
'CustomerID': [101, 102, 103, 104], # Useless ID feature (should be dropped)
'Age': [25, 45, 34, 52], # Numerical feature
'Income': [50000, 110000, 75000, 95000], # Numerical feature
'City': ['New York', 'London', 'New York', 'Paris'], # Categorical feature
'Churned': [0, 1, 0, 1] # TARGET LABEL (y)
})
# 2. Separate Features (X) from Target Label (y)
X_raw = data.drop(columns=['CustomerID', 'Churned'])
y = data['Churned'].values
# 3. Build Transformation Pipeline: Scale numbers, One-Hot Encode categories
numeric_cols = ['Age', 'Income']
categorical_cols = ['City']
preprocessor = ColumnTransformer(transformers=[
('num', StandardScaler(), numeric_cols),
('cat', OneHotEncoder(sparse_output=False), categorical_cols)
])
# 4. Transform raw features into final numerical Design Matrix X
X_processed = preprocessor.fit_transform(X_raw)
print("Original Features:\n", X_raw)
print("\nFinal Processed Feature Matrix X (Shape:", X_processed.shape, "):\n", X_processed.round(2))
print("\nTarget Vector y:", y)Features (X) vs Labels / Targets (y)
| Aspect | Features (X) | Labels / Targets (y) |
|---|---|---|
| Mathematical Role | Independent input variables ($X_1, X_2, \dots, X_d$) | Dependent target variable to be predicted ($y$) |
| Dimensionality | 2D Matrix: Shape $(N, D)$ with $N$ rows and $D$ columns | 1D Vector: Shape $(N,)$ with 1 outcome per row |
| Role in Unsupervised Learning | Always present (unsupervised algorithms operate on $X$) | Absent (unsupervised problems have no target labels) |
| Availability in Production | Must be collected and available at prediction time | Unknown at prediction time (this is what the model estimates) |
| Common Synonyms | Inputs, Predictors, Attributes, Independent variables | Target, Outcome, Dependent variable, Ground truth |
Target Leakage Audit Checklist
Feature Stores in Production MLOps
Advantages
- Clarifies the data relationship between inputs and predictive targets.
- Supports modular preprocessing pipelines for scaling and encoding.
- Allows feature importance analysis to interpret what variables drive predictions.
Limitations
- Gathering high-quality features can be time-consuming and expensive.
- Missing key features can limit how accurately a model can learn.
- Including too many irrelevant features can lead to overfitting.
Interview Questions
What is Target Leakage, and how can you detect and avoid it?
Target leakage happens when a training feature contains information that will not actually be available when the model makes predictions in production. For example, predicting whether a patient has a condition using a feature that tracks whether they received specialized post-diagnosis medication would create leakage. It is prevented by carefully auditing the timeline of when features are recorded relative to the target event.
When should you choose One-Hot Encoding over Ordinal Encoding?
One-Hot Encoding is appropriate for nominal categories that have no inherent ranking (such as city or product category), because assigning simple sequential numbers might incorrectly imply that one category is mathematically greater than another. Ordinal Encoding is appropriate when categories possess a clear natural order (such as education levels or rating tiers), or when using tree-based models that split on individual thresholds.
Practice Questions
- For a model predicting whether a borrower will default on a loan, list five valid features, the target label, and one example of a feature that would cause data leakage.
- If a categorical feature has 50 distinct values, what happens to the width of the feature matrix after One-Hot Encoding? What trade-off does this introduce?
