1.2 The Power of Representation
A film review calls the acting vivid and the plot flat. A second review uses the same words for the opposite roles. If we keep only word counts, the two reviews look identical. A reader asking about the acting needs information that those counts discarded.
A representation is the information a model passes to its next computation. Its usefulness depends on the question that computation has to answer. [1]
What does the next task need?
- Size. Compression can save memory and computation. Some useful representations expand the input into more coordinates so that a later layer can separate cases.
- Generalization. A face representation that is stable under a change in lighting can help identify the same person. If the task is to estimate lighting, that same invariance discards the answer.
- Transfer. Pretraining can produce features that help several downstream tasks. Held-out examples from the intended use reveal which distinctions the representation retained. [1]
Recognizing the same face in two photos
In one photo, a person faces the camera. In the next, the same person turns slightly. A classifier given only the distance between the eyes in pixels sees a different number. A designer could correct for the angle or add a second measurement.
A learned encoder offers another route. Train it on pairs of photos labeled “same person” or “different people,” then check whether its distances preserve that distinction for people held out of training. Contrast this with the film review. A useful face representation can discard the camera angle. A useful review representation may have to keep the target of each adjective.
Choosing between a model of the data and a predictor
Breiman described two ways to approach a prediction problem. One specifies a probabilistic account of how inputs and outputs relate, then checks its assumptions against the data. The other learns a mapping and tests it on new cases. Both approaches can use statistics and both need validation. [3]
Consider a low score for acting. To predict that score on a new review, we can compare encoders using held-out reviews. To claim that mentioning the plot causes a lower acting score, we would need evidence about what happens when that mention changes and the other relevant conditions stay comparable. A low prediction error answers the first question.
A Brief History: From Hand-Crafted Features to Deep Learning
The history of machine learning can be viewed as an evolution in how we represent data.
- Image descriptors such as SIFT and text features such as TF-IDF encode a designer’s choices about what to preserve. A classifier can still learn weights for those features.
- In the 2012 ImageNet competition, a convolutional network learned filters from labeled images and substantially reduced classification error on that benchmark. The training objective rewarded distinctions among ImageNet classes. [5]
- A self-supervised objective can derive targets from the text itself. BERT’s masked-token task uses surrounding text to predict selected tokens. A causal language model predicts the next token from its prefix. The information available at each prediction differs. [6]
Feature Engineering vs. Representation Learning
| Design question | Engineered example | Learned example |
|---|---|---|
| How is a word represented? | The designer assigns a fixed lexicon score. | Fit a score to labeled uses, or a vector to a prediction objective. |
| What does a review keep? | Word counts discard the order and the aspect each word describes. A designer can add aspect-specific features. | A sequence encoder can use order and context. Whether it retains an aspect depends on its architecture and objective. |
| How can we check? | Swap which aspect each adjective describes and inspect the counts. | Make the same swap on held-out reviews and inspect the outputs for acting and plot separately. |
Hierarchical feature extraction
Stacked layers can compose features into more abstract representations. In a vision network, early layers may respond to edges and textures, intermediate layers to combinations such as object parts, and later layers to features useful for recognizing objects. This is a useful intuition, not a universal assignment of one concept to each layer: representations are distributed and depend on the task and architecture.
The Manifold Hypothesis
A camera records millions of pixel values. If you photograph a stationary object while changing only the camera angle, nearby angles produce related images. The manifold hypothesis proposes that, for some data distributions, observations concentrate near a surface with far fewer local degrees of freedom than the number of measurements. Noise can push individual observations off the surface. [1]
A sheet of paper illustrates the difference. It takes two coordinates to locate a point on the sheet even when the sheet bends through three-dimensional space. The bends can still make it difficult to map a spatial measurement back to coordinates on the sheet.
Learning a Latent Space
Suppose ten sensor channels record different mixtures of the same two signals, plus independent noise. Each row in the example is one reading. A linear encoder maps its ten values to two coordinates. A linear decoder uses those coordinates to reconstruct all ten values. Training minimizes the mean squared error (MSE) across rows and channels.
The CPU example uses 256 synthetic training readings and a fixed budget of 300 full-batch updates. After training, it scores 128 fresh readings from the same generator. For comparison, a constant predictor returns each channel’s training mean for every reading. Both predictors are scored on the same held-out rows.
import torch
from torch import nn
torch.manual_seed(42)
torch.set_num_threads(1)
mixing = torch.randn(2, 10)
def sample(n):
factors = torch.randn(n, 2)
noise = 0.05 * torch.randn(n, 10)
return factors @ mixing + noise
train = sample(256)
test = sample(128)
model = nn.Sequential(nn.Linear(10, 2), nn.Linear(2, 10))
mse = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.02)
for step in range(300):
optimizer.zero_grad()
loss = mse(model(train), train)
loss.backward()
optimizer.step()
model.eval()
with torch.no_grad():
constant = train.mean(dim=0).expand_as(test)
print(f"baseline MSE: {mse(constant, test).item():.4f}")
print(f"autoencoder MSE: {mse(model(test), test).item():.4f}")
With the seed shown, a CPU run gave a held-out MSE of 1.6488 for the constant predictor and 0.0021 for the autoencoder. Two coordinates preserved much of the variation across these readings. A different basis for the same plane can reconstruct them equally well, so the error alone cannot tell us which learned coordinate corresponds to either original signal. Try changing the bottleneck width to one in both layers and compare the held-out errors again.
Example: Feature Engineering vs. Representation Learning in NLP
Use four authored ratings for vivid and four for flat. Each rating is +1 or −1. Fit one number for each rated word by minimizing the sum of squared errors over its ratings. The minimizing value is their mean. Here the fitted scores are +0.5 and −0.5. The third word, spare, has no training ratings.
The controls supply the acting and plot fields directly. Both representations use the same fitted word scores. One stores a single mean for the review. The other keeps an ordered pair, with acting first and plot second. Which representation lets you recover the reviewer’s assessment of the acting after you swap the adjectives?
Did the review praise the acting or the plot?
Swap the two descriptions. Which numbers tell you what the reviewer liked?
Keep one mean
0
Add the two word scores and divide by two. Both words need a fitted score.Keep the two aspects
Acting +0.5
Plot -0.5
Where do the word scores come from?
These are authored training ratings. Each word gets the mean of its positive (+1) and negative (−1) ratings.
- vivid · +1, +1, +1, -1 → +0.5
- flat · +1, -1, -1, -1 → -0.5
- spare · Unrated
For vivid acting, flat plot, the pair is . After the swap it is . Both averages are zero, so any classifier given only that average must give the same answer to both reviews. Supplying the aspect labels makes the pair useful here. A system reading free-form reviews would also need to infer which words describe each aspect.
Quizzes
Quiz 1: In the review example, which pieces were designed and which were learned?
We chose the acting and plot fields, the positive and negative rating scale, and the rule for combining word scores. The numerical score for each rated word was fitted to its examples. A mean is enough to learn this one-dimensional representation.
Quiz 2: A sensor stream varies mainly along a two-dimensional surface. What does that tell you about the encoder you will need?
Two local coordinates may describe nearby readings. The mapping from sensor values to those coordinates can still be complicated on a folded surface. Test a candidate encoder and decoder on held-out readings to see how much detail they preserve.
Quiz 3: Could a larger classifier recover the acting score if its only input is the review’s mean score?
The two swapped reviews both produce zero and have opposite acting scores. Any deterministic classifier sees the same input and must give the same output. Retaining separate aspect scores supplies the missing distinction.
Quiz 4: You pretrain an encoder by predicting masked words in movie reviews. Which labels do you need to evaluate whether it can identify praise for the acting?
The original text supplies the target for each masked word during pretraining. To measure accuracy on the acting question, you also need held-out reviews labeled for the acting, including cases where the plot and acting receive opposite assessments.
Quiz 5: What are the risks of relying entirely on automated Representation Learning in high-stakes domains (e.g., healthcare)?
The primary risks are lack of interpretability and bias amplification. Since the model learns its own representations, it is difficult for humans to understand why it made a specific decision (the black box problem). If the training data contains biases, the model will learn to represent those biases, potentially leading to unfair or dangerous outcomes.
Quiz 6: Derive the analytical gradient of the Mean Squared Error (MSE) loss with respect to the bottleneck latent representation in an Autoencoder.
Let be the input, be the bottleneck representation, and be the reconstruction. The MSE loss is . By the chain rule, the gradient with respect to the latent vector is: . We know . Therefore, , where is the Jacobian matrix of the decoder function evaluated at .
References
- Bengio, Y., Courville, A., & Vincent, P. (2013). Representation learning: A review and new perspectives. IEEE transactions on pattern analysis and machine intelligence, 35(8), 1798-1828. arXiv:1206.5538.
- LeCun, Y., Bengio, Y., & Hinton, G. (2015). Deep learning. Nature, 521(7553), 436-444.
- Breiman, L. (2001). Statistical Modeling: The Two Cultures. Statistical Science, 16(3), 199-231.
- Recommended Video: StatQuest: Word Embedding and Word2Vec A great visual explanation of Word Embeddings and Word2Vec, a prime example of representation learning.
- Krizhevsky, A., Sutskever, I., & Hinton, G. E. (2012). ImageNet Classification with Deep Convolutional Neural Networks.
- Devlin, J., et al. (2018). BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding.