Are Deep Neural Networks Dramatically Overfitted:
[Updated on 2019-05-27: add the section on Lottery Ticket Hypothesis.] If you entered the deep learning field with a background in traditional machine learning, you may have asked a recurring question: given that a typical deep neural network contains an enormous number of parameters, and that its training error can often be driven to perfection, should it not suffer from severe overfitting, If so, how can it generalize to out-of-sample data points,
· 21 min read · Curated and presented by Arthur Sedek
[Updated on 2019-05-27: add the section on Lottery Ticket Hypothesis.]
If you come to deep learning with a background in traditional machine learning, you may repeatedly return to the same concern: a typical deep neural network has an enormous number of parameters, and achieving near-perfect training error is often easy. By that logic, substantial overfitting would seem inevitable. How, then, can it generalize to data points outside the training set?
The attempt to understand why deep neural networks generalize reminds me of a fascinating paper in systems biology, “Can a biologist fix a radio?” (Lazebnik, 2002). If a biologist tried to repair a radio in the same way she studies biological systems, it could be an uphill battle. Because the radio’s full mechanism is not laid bare, probing small, local functionalities may yield clues, but it is unlikely to reveal all interactions within the system, much less the complete operational flow. Whether or not you find the analogy relevant to DL, it is an entertaining read.
In this post, I would like to walk through several papers on generalization and complexity measures for deep learning models. The goal is to help illuminate a path toward understanding why DNNs can generalize.
Classic Theorems on Compression and Model Selection
Suppose we have a classification task and a dataset. We could build many different models, ranging from fitting a simple linear regression model to literally storing and replaying the entire dataset from disk. Which approach is preferable? If we cared only about training accuracy (especially when test data is unknown), the memorization strategy would appear to win, but that conclusion clearly feels wrong.
A number of classic results help guide what properties we should expect from a good model in settings like this.
Occam’s Razor
Occam’s Razor is an informal principle for problem-solving, attributed to William of Ockham in the 14th century:
“Simpler solutions are more likely to be correct than complex ones.”
This idea is remarkably influential when we have several candidate theories to explain the world and must select among them. A theory padded with unnecessary assumptions may fit one situation plausibly, yet be harder to extend to other situations, or fail to converge toward more fundamental principles.
Consider that it took centuries to recognize that the daytime blue sky and the reddish colors at sunset arise from the same mechanism (Rayleigh scattering), even though the two phenomena appear quite different. Many separate explanations were likely proposed, but the unified, simpler account ultimately prevailed.
Minimum Description Length principle
Occam’s Razor can be carried over to machine learning model selection. One formalization is the Minimum Description Length (MDL) principle, which compares competing models (or explanations) given observed data.
“Comprehension is compression.”
The core perspective in MDL is to treat learning as data compression. To compress data effectively, we must identify regularities and patterns that are likely to extend to unseen samples. Information bottleneck theory suggests that a deep neural network is trained, first, to represent the data by minimizing generalization error, and then to compress that representation by removing noise.
At the same time, MDL treats the model description itself as part of the transmitted compressed message, so the model cannot be made arbitrarily large.
A two-part version of the MDL principle states: Let $\mathcal{H}^{(1)}, \mathcal{H}^{(2)}, \dots$ be a list of models that can explain the dataset $\mathcal{D}$. The best hypothesis among them is the one that minimizes the following sum:
- $L(\mathcal{H})$ is the description length of model $\mathcal{H}$, measured in bits.
- $L(\mathcal{D}\vert\mathcal{H})$ is the description length of the data $\mathcal{D}$, measured in bits, when encoded using $\mathcal{H}$.
In other words, the best model is the smallest model that includes both the model itself and an encoding of the data. Under this criterion, the memorization strategy mentioned at the start of this section is clearly undesirable, regardless of how well it performs on the training set.
Some might object that Occam’s Razor is misguided: if the real world can be arbitrarily complex, why insist on simple models? One useful MDL viewpoint is to treat models as “languages” rather than as fundamental generative truths. We want effective compression schemes that capture regularities from a limited set of samples, and they do not have to be the “real” generative model behind the phenomenon. A model can be incorrect and still be useful (for example, consider any Bayesian prior).
Kolmogorov Complexity
Kolmogorov Complexity uses the concept of modern computation to define the algorithmic (descriptive) complexity of an object: it is the length of the shortest binary computer program that describes the object. In line with the MDL perspective, a computer can be viewed as the most general type of data decompressor.
The formal definition of Kolmogorov Complexity is: given a universal computer $\mathcal{U}$ and a program $p$, denote $\mathcal{U}(p)$ as the output produced by the computer when running the program, and denote $L(p)$ as the program’s description length. Then the Kolmogorov Complexity $K_\mathcal{U}$ of a string $s$ with respect to a universal computer $\mathcal{U}$ is:
Recall that a universal computer can simulate the actions of any other computer. Modern computers are universal in this sense because they can be reduced to Turing machines. This definition is essentially independent of which universal computer is used: any other universal computer can be programmed to reproduce the behavior of $\mathcal{U}$, and the extra code needed to implement that simulation contributes only a constant-length overhead.
Kolmogorov Complexity is closely related to Shannon information theory, since both connect to universal coding. A striking result is that the expected Kolmogorov Complexity of a random variable is approximately equal to its Shannon entropy (see Sec 2.3 of the report). A deeper discussion is beyond the scope here, but many good resources are available online. Help yourself :)
Solomonoff’s Inference Theory
Another mathematical formalization of Occam’s Razor is Solomonoff’s theory of universal inductive inference (Solomonoff, 1964). Its guiding idea is to prefer models that correspond to the “shortest program” capable of generating the training data, as measured by Kolmogorov complexity.
Expressive Power of DL Models
Deep neural networks typically contain far more parameters than traditional statistical models. If we apply MDL and equate model complexity with the number of parameters (that is, treat parameter count as the model description length), deep networks can appear highly unfavorable: the model description $L(\mathcal{H})$ can easily become enormous.
However, this abundance of parameters is necessary for neural networks to achieve high expressive power. Because they can capture highly flexible data representations, deep neural networks have delivered strong performance across many applications.
Universal Approximation Theorem
The Universal Approximation Theorem states that a feedforward network with (1) a linear output layer, (2) at least one hidden layer with a finite number of neurons, and (3) an activation function can approximate any continuous function on a compact subset of $\mathbb{R}^n$ to arbitrary accuracy. The result was first proved for sigmoid activations (Cybenko, 1989). Later work showed that universal approximation is not tied to a specific activation choice (Hornik, 1991), but rather to the multilayer feedforward architecture.
While a single-hidden-layer feedforward network is sufficient in principle to represent any function, doing so may require an exponentially large width. Moreover, the universal approximation theorem does not address whether the resulting model can be learned efficiently or whether it will generalize well. In practice, adding more layers often reduces the number of hidden units needed compared with a shallow network.
Thus, although the theorem implies we can always find a neural network whose approximation error falls below any chosen threshold, the cost may be substantial: the network can become extremely large.
Proof: Finite Sample Expressivity of Two-layer NN
The universal approximation discussion above does not explicitly address finite sample sets. Zhang, et al. (2017) provided a concise proof of finite-sample expressivity for two-layer neural networks.
A neural network $C$ can represent any function on a sample of size $n$ in $d$ dimensions if the following holds: for every finite sample set $S \subseteq \mathbb{R}^d$ with $\vert S \vert = n$, and for every function defined on that sample set, $f: S \mapsto \mathbb{R}$, there exists a weight configuration for $C$ such that $C(\boldsymbol{x}) = f(\boldsymbol{x}), \forall \boldsymbol{x} \in S$.
The paper states the following theorem:
There exists a two-layer neural network with ReLU activations and $2n + d$ weights that can represent any function on a sample of size $n$ in $d$ dimensions.
Proof. We begin by constructing a two-layer neural network $C: \mathbb{R}^d \mapsto \mathbb{R}$. The input is a $d$-dimensional vector, $\boldsymbol{x} \in \mathbb{R}^d$. The hidden layer contains $h$ units, with weight matrix $\mathbf{W} \in \mathbb{R}^{d\times h}$, bias vector $-\mathbf{b} \in \mathbb{R}^h$, and a ReLU activation. The second layer produces a scalar output, using weight vector $\boldsymbol{v} \in \mathbb{R}^h$ and zero biases.
The output of network $C$ for an input vector $\boldsymbol{x}$ can be written as:
where $\boldsymbol{W}_{(:,i)}$ is the $i$-th column of the $d \times h$ matrix.
Given a sample set $S = \{\boldsymbol{x}_1, \dots, \boldsymbol{x}_n\}$ and target values $\boldsymbol{y} = \{y_1, \dots, y_n \}$, our goal is to choose weights $\mathbf{W} \in \mathbb{R}^{d\times h}$ and $\boldsymbol{b}, \boldsymbol{v} \in \mathbb{R}^h$ such that $C(\boldsymbol{x}_i) = y_i, \forall i=1,\dots,n$.
Combine all sample points into a single batch, forming an input matrix $\mathbf{X} \in \mathbb{R}^{n \times d}$. If we set $h=n$, then $\mathbf{X}\mathbf{W} - \boldsymbol{b}$ becomes a square matrix of size $n \times n$.
We can further simplify $\mathbf{W}$ so that every column shares the same column vector:
Given $a_i = \boldsymbol{x}_i \boldsymbol{w}$, our goal is to choose appropriate $\boldsymbol{w}$ and $\boldsymbol{b}$ such that $b_1 < a_1 < b_2 < a_2 < \dots < b_n < a_n$ holds. This is always possible because we are solving $n+d$ unknown variables under $n$ constraints, and $\boldsymbol{x}_i$ are independent (for example, choose a random $\boldsymbol{w}$, sort $\boldsymbol{x}_i \boldsymbol{w}$, and then assign the $b_j$’s to be intermediate values). Under this construction, $\mathbf{M}_\text{ReLU}$ becomes a lower triangular matrix:
This matrix is a nonsingular square matrix because $\det(\mathbf{M}_\text{ReLU}) \neq 0$, so we can always find suitable $\boldsymbol{v}$ to solve $\boldsymbol{v}\mathbf{M}_\text{ReLU}=\boldsymbol{y}$. Equivalently, the column space of $\mathbf{M}_\text{ReLU}$ is the entirety of $\mathbb{R}^n$, and we can form any $\boldsymbol{y}$ as a linear combination of its column vectors.
Deep NN can Learn Random Noise
Because two-layer neural networks are universal approximators, it is not especially surprising that they can fit unstructured random noise perfectly, as demonstrated in Zhang, et al. (2017). When the labels in an image classification dataset are randomly permuted, the high expressive capacity of deep neural networks still enables them to drive the training loss close to zero. Notably, these findings remain qualitatively unchanged even when regularization terms are added.
Are Deep Learning Models Dramatically Overfitted?
Deep learning models are often heavily over-parameterized and can frequently achieve perfect performance on the training set. From the traditional perspective (for example, the bias-variance trade-off), this would appear disastrous, suggesting that the model might fail to generalize to unseen test data. Yet, in practice, these seemingly “overfitted” deep models (training error = 0) often still deliver solid out-of-sample performance. This raises a natural question: why does this happen?
Modern Risk Curve for Deep Learning
Traditional machine learning commonly relies on a U-shaped risk curve to characterize the bias-variance trade-off and to quantify how well a model is expected to generalize. If asked how to identify whether a model is overfitted, this is typically the first diagnostic that comes to mind.
As the model grows (that is, as more parameters are added), training error tends to fall toward zero. However, once model complexity crosses the boundary between “underfitting” and “overfitting,” the test error (generalization error) begins to rise. In spirit, this is consistent with Occam’s Razor.
However, this picture does not cleanly describe deep learning. Belkin et al. (2018) reconciled the classical bias-variance framing with modern behavior by proposing a new double-U-shaped risk curve for deep neural networks. In their view, once a network has sufficiently many parameters, the risk curve transitions into an additional regime.
The paper argued that this behavior is likely driven by two factors:
- The parameter count is a poor proxy for inductive bias, which is defined as the set of assumptions a learning algorithm uses to make predictions on previously unseen samples. For additional discussion of deep learning model complexity, see the later sections.
- With a larger model, we may be able to explore broader function classes and identify interpolating functions with smaller norms, and therefore “simpler” solutions.
The double-U-shaped curve was reported empirically in the paper. That said, I found it fairly challenging to reproduce. While there are encouraging signs, producing a smooth curve comparable to the theorem requires careful control of many details in the experimental setup.
Regularization is not the Key to Generalization
Regularization is a standard tool for controlling overfitting and improving generalization. Interestingly, some work (Zhang, et al. 2017) suggests that explicit regularization (for example, data augmentation, weight decay, and dropout) is neither necessary nor sufficient to reduce generalization error.
Using an Inception model trained on CIFAR10 as an example (see Fig. 5), regularization methods help out-of-sample generalization, but not dramatically. No single regularization component appears essential in isolation from the others. Therefore, it seems unlikely that regularizers are the fundamental reason deep models generalize.
Intrinsic Dimension
In deep learning, parameter count often fails to correlate with overfitting, indicating that counting parameters does not capture the true complexity of deep neural networks.
Beyond parameter counting, many alternative complexity measures have been proposed, including the number of degrees of freedom of models (Gao & Jojic, 2016) and prequential code (Blier & Ollivier, 2018).
Here, I focus on a more recent approach called intrinsic dimension (Li et al, 2018). Intrinsic dimension is conceptually straightforward, relatively easy to measure, and it reveals notable properties across models of different sizes.
Consider a neural network with a very large number of parameters, which defines a high-dimensional parameter space. Learning then proceeds over this high-dimensional objective landscape. The geometry of the parameter-space manifold is important. For instance, a smoother manifold can make optimization easier by providing more predictive gradients and permitting larger learning rates, which was proposed as a reason batch normalization can stabilize training (Santurkar, et al, 2019).
Although the parameter space is enormous, we do not necessarily need to worry that optimization will be trapped in poor local optima. It has been shown that local optimal points in the objective landscape almost always occur at saddle points rather than true valleys. Put differently, there is typically a subset of dimensions that provides directions to escape and continue exploring.
A key intuition behind intrinsic dimension is that, in such a high-dimensional parameter space, effective learning may not require using every dimension. If optimization can move through only a slice of the objective landscape and still reach a strong solution, then the effective complexity of the resulting model may be far smaller than parameter counting would suggest. Intrinsic dimension is designed to quantify this notion.
Suppose a model has $D$ dimensions, with parameters denoted by $\theta^{(D)}$. For training, we randomly sample a smaller $d$-dimensional subspace, $\theta^{(d)}$, where $d < D$. During each optimization update, instead of taking a gradient step in all $D$ dimensions, we update only within the smaller subspace $\theta^{(d)}$ and then remap that update back to the full parameter space.
The gradient update takes the following form:
where $\theta_0^{(D)}$ are the initialization values and $\mathbf{P}$ is a $D \times d$ projection matrix sampled at random prior to training. Both $\theta_0^{(D)}$ and $\mathbf{P}$ are fixed (not trainable) throughout training. $\theta^{(d)}$ is initialized to all zeros.
By searching over $d = 1, 2, \dots, D$, the associated $d$ at which a solution first appears is defined as the intrinsic dimension.
Empirically, many tasks exhibit intrinsic dimensions far smaller than their raw parameter counts. For instance, in CIFAR10 image classification, a fully connected network with 650k+ parameters has an intrinsic dimension of only 9k, and a convolutional network with 62k parameters has an even lower intrinsic dimension of 2.9k.
These intrinsic-dimension measurements suggest that deep learning models can be substantially simpler than they appear based solely on parameter counts.
Heterogeneous Layer Robustness
Zhang et al. (2019) studied how parameters in different layers contribute to model behavior. Their central question is: “are all layers created equal?” Their conclusion is that they are not, some layers are much more sensitive to perturbations than others.
The paper introduced two parameter interventions for the $\ell$-th layer, $\ell = 1, \dots, L$, at time $t$, $\theta^{(\ell)}_t$, and examined their effects on robustness:
-
Re-initialization: Reset the layer parameters to their initialization values, $\theta^{(\ell)}_t \leftarrow \theta^{(\ell)}_0$. The resulting network performance after re-initializing layer $\ell$ is called the re-initialization robustness of layer $\ell$.
-
Re-randomization: Resample the layer parameters at random, $\theta^{(\ell)}_t \leftarrow \tilde{\theta}^{(\ell)} \sim \mathcal{P}^{(\ell)}$. The resulting network performance is called the re-randomization robustness of layer $\ell$.
Using these two operations, layers can be grouped into two types:
- Robust Layers: Re-initializing or re-randomizing the layer causes no, or only negligible, degradation in performance.
- Critical Layers: Any layer that does not satisfy the robust criterion.
Comparable patterns appear in both fully connected and convolutional networks. Re-randomizing any layer completely destroys performance, with predictions immediately collapsing to random guessing. More unexpectedly, under re-initialization, only the first layer or the first few layers (closest to the input) are critical, while re-initializing higher layers produces only negligible decrease in performance.
ResNet can leverage shortcut connections between non-adjacent layers, redistributing sensitivity across the network rather than concentrating it near the bottom. With residual blocks, the network can evenly be robust to re-randomization. Only the first layer in each residual block remains sensitive to both re-initialization and re-randomization. If each residual block is treated as a local sub-network, the robustness pattern resembles what is observed for the fully connected and convolutional networks above.
Because many upper layers in deep networks are not critical to performance under re-initialization, the paper offered the following loose conclusion:
“Over-capacitated deep networks trained with stochastic gradient have low-complexity due to self-restricting the number of critical layers.”
Re-initialization can be interpreted as a mechanism for reducing the effective number of parameters. In that sense, this observation is consistent with what intrinsic dimension suggests.
The Lottery Ticket Hypothesis
The lottery ticket hypothesis (Frankle & Carbin, 2019) provides another compelling result supporting the idea that only a subset of parameters materially determines performance, and therefore the network is not necessarily overfitted in the intuitive sense. The hypothesis proposes that a randomly initialized, dense, feed-forward network contains many subnetworks, and that only some of these subnetworks are “winning tickets” capable of reaching optimal performance when trained in isolation.
This idea is motivated by network pruning methods, which remove unnecessary weights (for example, very small weights that contribute negligibly) without reducing accuracy. Although pruning can drastically reduce the final model size, training the resulting pruned architecture successfully from scratch is difficult. This creates an apparent tension: training seems to benefit from many parameters, but maintaining high accuracy after training does not require nearly as many. Why?
To study this, the lottery ticket hypothesis conducted the following procedure:
- Randomly initialize a dense feed-forward network with initialization values $\theta_0$;
- Train the network for multiple iterations until it reaches good performance, yielding parameter configuration $\theta$;
- Prune $\theta$, producing a mask $m$.
- The “winning ticket” initialization configuration is $m \odot \theta_0$.
If we then train only the small “winning ticket” subset of parameters, using the same initial values found in step 1, the model can reach the same accuracy achieved in step 2. The implication is that a large parameter space may not be required to represent the final solution, but it can be useful during training because it supplies a large pool of initialization configurations for many much smaller subnetworks.
The lottery ticket hypothesis offers a new perspective for interpreting and dissecting deep neural network behavior, and it has inspired many follow-up studies.
Experiments
After reviewing the findings above, reproducing them is an appealing exercise. Some results are easier to replicate than others, and the details are provided below. The code is available on github at lilianweng/generalization-experiment.
New Risk Curve for DL Models
This is the most difficult result to replicate. The authors shared several helpful suggestions, which I greatly appreciate. The following experimental settings are particularly important:
- No regularization is used (for example, no weight decay and no dropout).
- In Fig 3, the training set consists of 4k samples. It is sampled once and then held fixed across all models. Evaluation uses the full MNIST test set.
- Each network is trained for a long time to drive training risk close to zero. The learning rate is adjusted differently for models of different sizes.
- To reduce sensitivity to initialization in the under-parameterized regime, they employ a “weight reuse” scheme: parameters learned by a smaller network are used to initialize larger networks.
I did not train or tune each model long enough to reach perfect training performance, but the evaluation error does exhibit a distinctive twist around the interpolation threshold that differs from the training error. For MNIST, for example, the threshold equals the number of training samples multiplied by the number of classes (10), that is 40000.
The x-axis is the number of model parameters, computed as: (28 * 28 + 1) * num. units + num. units * 10, plotted on a logarithmic scale.
Layers are not Created Equal
This result is relatively straightforward to reproduce. See my implementation here.
In the first experiment, I used a three-layer fully connected network with 256 units per layer. Layer 0 is the input layer, and layer 3 is the output layer. The network is trained on MNIST for 100 epochs.
In the second experiment, I used a four-layer fully connected network with 128 units per layer. All other settings match experiment 1.
Intrinsic Dimension Measurement
To correctly map the $d$-dimensional subspace into the full parameter space, the projection matrix $\mathbf{P}$ should have orthogonal columns. Because the product $\mathbf{P}\theta^{(d)}$ is a sum of the columns of $\mathbf{P}$, each scaled by the corresponding scalar entry in the $d$-dimensional vector $\sum_{i=1}^d \theta^{(d)}_i \mathbf{P}^\top_{(:,i)}$, it is preferable to fully utilize the subspace by ensuring orthogonal columns in $\mathbf{P}$.
My implementation uses a naive approach: it samples a large matrix with independent entries from a standard normal distribution. In a high-dimensional space, the columns are expected to be independent and therefore approximately orthogonal. This approach works when the dimension is not too large. When experimenting with large $d$, sparse projection matrix constructions are available, which is what the intrinsic dimension paper recommended.
Below are experiment runs for two networks: (left) a two-layer fully connected network with 64 units in each layer, and (right) a one-layer fully connected network with 128 hidden units, trained on 10% of MNIST. For each $d$, the model is trained for 100 epochs. See the code here.
Cited as:
@article{weng2019overfit,
title = "Are Deep Neural Networks Dramatically Overfitted?",
author = "Weng, Lilian",
journal = "lilianweng.github.io",
year = "2019",
url = "https://lilianweng.github.io/posts/2019-03-14-overfit/"
}
References
[1] Wikipedia page on Occam’s Razor.
[2] Occam’s Razor on Principia Cybernetica Web.
[3] Peter Grunwald. “A Tutorial Introduction to the Minimum Description Length Principle”. 2004.
[4] Ian Goodfellow, et al. Deep Learning. 2016. Sec 6.4.1.
[5] Zhang, Chiyuan, et al. “Understanding deep learning requires rethinking generalization.” ICLR 2017.
[6] Shibani Santurkar, et al. “How does batch normalization help optimization?.” NIPS 2018.
[7] Mikhail Belkin, et al. “Reconciling modern machine learning and the bias-variance trade-off.” arXiv:1812.11118, 2018.
[8] Chiyuan Zhang, et al. “Are All Layers Created Equal?” arXiv:1902.01996, 2019.
[9] Chunyuan Li, et al. “Measuring the intrinsic dimension of objective landscapes.” ICLR 2018.
[10] Jonathan Frankle and Michael Carbin. “The lottery ticket hypothesis: Finding sparse, trainable neural networks.” ICLR 2019.