# Out-of-Distribution Generalization

### Setup: I.I.D.

We must start by defining what we mean by ‘prediction’. In this particular course, we first assume that each and every input-output pair $(x,y)$, input $x$ or output $y$ is sampled independently of each other. This is a pretty strong assumption, since the world often changes based on what we have seen, because those who saw a sample pair may and often do change their behaviors. For instance, consider building a stock price forecasting model. Once you use a predictor to predict whether the price of a particular stock goes up or down and trade based on the outcome, the next input $x$, that is the stock of your next interest, is not anymore independently selected but based on your own success/failure from the previous trade. This assumption is however also reasonable, because there are many phenomena in which our behaviours do not matter much in a reasonably short horizon. For instance, consider installing and using a bird classifier at a particular forest. With a fixed camera, the input to this classifier will be largely independent of which birds (or not) were seen earlier, although spotting of a particular bird may attract poachers to this forest who would dramatically affect the bird population in a longer time frame. Next, we assume that all these pairs are drawn from the ‘identical’ distribution. This is similar if not identical to the stationarity assumption from RCT. In RCT, we often rely on a double blind experiment design, in order to ensure that the causal effect $p^*(y|a,x)$ does not change over the trial. In this section as well as conventional statistical learning theory, we assume all input-output pairs were drawn from the same distribution. Combining these two assumptions, we arrive at a so-called training set $D$ which satisfies

[] \begin{align} p(D) = \prod_{(x,y) \in D} p^*(x, y), \end{align} []

according to the definition of independence. We do not have access to nor have knowledge of $p^*$. We use this training set $D$ for both model fitting (training) and selection (validation). Once the predictive model $\hat{p}$ is ready, we deploy it to make a prediction on a novel input $x'$ drawn from a distribution $q^*$. That is,

[] \begin{align} \hat{y} \sim \hat{p}(y | x'), \end{align} []

where $(x', y') \sim q^*$. We are often not given $y'$. After all, $y'$ is what we want to use our predictive model to infer. We say that the predictive model is accurate, if the following quantity is low:

[] \begin{align} R(\hat{p}) = \mathbb{E}_{(x',y') \sim q^*} \left[ l(y', \hat{p}(y|x')) \right], \end{align} []

where $l(\cdot, \cdot) \geq 0$ is the loss (misclassification rate). In traditional statistical learning theory, $q^*$ is assumed to be $p^*$, and under this assumption, the goal of designing a learning algorithm is to minimize a so-called excess risk:

[] \begin{align} R_{\mathrm{excess}}(\hat{p}) = R(\hat{p}) - R(p^*) \end{align} []

with respect to $\hat{p}$. Since we do not have access to $p^*$, we often use Monte Carlo approximation to compute $R(\hat{p})$, as follows

[] \begin{align} \label{eq:empirical-risk} R(\hat{p}) \approx \hat{R}_N(\hat{p}) = \frac{1}{N} \sum_{n=1}^N l(y_n, p(y|x_n)), \end{align} []

where $(x_n, y_n) \sim p^*$. With a (strong) assumption of uniform convergence, which is defined as

[] \begin{align} \sup_{\hat{p}} \left| R(\hat{p}) - \hat{R}_N(\hat{p}) \right| \to_p 0, \end{align} []

we can minimize $R$ using $\hat{R}$ with a large enough data set, i.e., $N \to \infty$, and find a good predictive model $\hat{p}$. Of course, since $N$ is always finite in reality, there is almost always non-zero generalization error. Since we never have access to $R(\hat{p})$ even after learning, it is a usual practice to use a separate (held-out) set of examples again drawn from the same distribution $p^* = q^*$ as the test set to approximate the generalization error of a trained model $\hat{p}$. Let $D' = \left\{ (x'_1,y'_1), \ldots, (x'_K, y'_K) \right\}$. Then,

[] \begin{align} R(\hat{p}) \approx \frac{1}{K} \sum_{k=1}^K l(y'_k, \hat{p}(y|x'_k)). \end{align} []

Such a test-set accuracy, or more simply a test accuracy, has been a workhorse behind rapid advances in machine learning over the past several decades. With this whole paradigm in your mind, it is important to notice that the key assumption here is $q^*(x,y)=p^*(x,y)$. In other words, we assume that an instance a predictive model would be tested in the deployment would follow the same distribution as that from which the training examples were drawn, i.e., $q^*(x) = p^*(x)$. Furthermore, the conditional distribution over the outcome does not change either, i.e., $q^*(y|x) = p^*(y|x)$. In this case, there is no reason for us to consider the underlying generating process behind $p^*$ nor $q^*$ separately.

### Out-of-Distribution Generalization

Impossibility of Out-of-Distribution (ood) generalization. In reality, it is rarely that $q^* = p^*$, because the world changes. When $q^* \neq p^*$, we must be careful about discussing generalization. We must be careful, because we can always choose $q^*$ to be such that minimizing $R(\hat{p})$ in Eq.~\eqref{eq:empirical-risk} would lead to maximizing

[] \begin{align} R^{q^*}(\hat{p}) = \mathbb{E}_{(x,y) \sim q^*}[ l(y, \hat{p}(y|x)) ]. \end{align} []

Assume $y \in \left\{0, 1\right\}$. Consider the following $q^*$, given $p^*(x,y) = p^*(x) p^*(y|x)$,

[] \begin{align} q^*(x, y) = p^*(x) q^*(y|x), \end{align} []

where

[] \begin{align} \label{eq:contrarian-q} q^*(y|x) = 1 - p^*(y|x). \end{align} []

That is, the mapping from $x$ to $y$ is reversed. When $x$ was more probable to be observed together with $y=1$ under $p^*$, it is now more probable to be observed together with $y=0$ now under $q^*$, and vice versa. If we take the log loss, which is defined as

[] \begin{align} l(y, \hat{p}(y|x)) = -\log \hat{p}(y|x), \end{align} []

learning corresponds to minimizing the KL divergence from the true distribution to the learned, predictive distribution. Mathematically,

[] \begin{align} \arg\min_{\hat{p}} \frac{1}{N} \sum_{n=1}^N l(y_n, \hat{p}(y_n|x_n)) \approx \arg\min_{\hat{p}} \mathbb{E}_x \mathrm{KL}( p^*(\cdot | x) \| \hat{p}(\cdot |x) ). \end{align} []

In other words, learning corresponds to recovering $p^*$ as much as we can for as many probable $x$'s under $p^*(x)$. It is clear that minimizing this loss function would make our predictive model worse on a new distribution \eqref{eq:contrarian-q}. Because the following holds for any particular example $(x,y)$:

[] \begin{align} \log p^*(y|x) = \log (1 - q^*(y|x)). \end{align} []

Since $\log$ is a monotonic function, maximizing $p^*$ is equivalent to minimizing $q^*$. As soon as we start minimizing the log loss for learning, out-of-distribution generalization to $q^*$ gets worse, and there is no way to avoid it, other than not learning at all. This is a simple but clear example showing how out-of-distribution generalization is not possible in general. There will always be a target distribution that disagrees with the original distribution, such that learning on the latter is guaranteed to hurt the generalization accuracy on the former. In general, such a target distribution can be written down as

[] \begin{align} \log q^*(y|x) \propto \log (1 - p^*(y|x)). \end{align} []

We can also come up with a similar formula for $q^*(x)$, such that there is almost no support overlap between $p^*(x)$ and $q^*(x)$.

Out-of-distribution generalization. We then must narrow down the scope in order to discuss out-of-distribution generalization. There are many different ways to narrow the scope, and one way is to ensure that the target distribution $q^*$ is not too far from the original distribution $p^*$. Let $D: \mathcal{P} \times \mathcal{P} \to \mathrm{R}_+$ be a (asymmetric) divergence between two distributions, such that the larger $D(p, q)$ implies the greater difference between these two distributions, $p$ and $q$. Then, we can write a so-called distributionally-robust loss as

[] \begin{align} \min_{\hat{p}} \sup_{q: D(p^*,q)\leq \delta} \mathbb{E}_{(x,y) \sim q} \left[ l(y, \hat{p}(y|x)) \right], \end{align} []

where $\sup$ is the supremum which is the smallest item that is greater than equal to all the other items in a partially ordered set~[1]. The distributionally-robust loss above minimizes ($\min_{\hat{p}}$) the expected loss ($\mathbb{E}_{(x,y) \sim q} \left[ l(y, \hat{p}(y|x)) \right]$) over the worst-case distribution ($\sup_{q}$) within the divergence constraint ($q: D(p^*,q)\leq \delta$). Despite its generality, due to the freedom in the choice of the divergence $D$ and the universality (the worst case), such distributionally-robust optimization is challenging to use in practice. The challenge mainly comes from the fact that we must solve a nested optimization problem, where for each update of $\hat{p}$ we must solve another optimization problem that maximizes the loss w.r.t. the distribution $q$. This problem can be cast as a two-player minimax game which is more challenging, both in terms of convergence and its speed, than a more conventional optimization problem. Furthermore, it is often unclear how to choose an appropriate divergence $D$ and the threshold $\delta$, as these choices are not grounded in the problem of interest. Instead, we are more interested in an alternative to the distributionally robust optimization approach. Instead of specifying a divergence, we can describe how the distribution changes in terms of the probabilistic graphical model, or equivalently the structural causal model underlying $p^*$ and $q^*$. Depending on such a distributional change, we may be able to characterize the degree of generalization or even to come up with a better learning algorithm.

### Case Studies

The label proportion shift. Let us consider a very basic example of a generative classier which assumes the following generating process: \begin{center}

\end{center} Under this generating process, the joint probability is written as

[] \begin{align} p^*(x,y) = p^*(y) p^*(x|y), \end{align} []

and the posterior distribution over the output $y$ is

[] \begin{align} p(y|x) = \frac{p(y) p(x|y)}{p(x)} = \frac{p(y) p(x|y)}{\sum_{y' \in \mathcal{Y}} p(y') p(x|y')}. \end{align} []

Given a training set $D=\left\{ (x_1, y_1), \ldots, (x_N, y_N) \right\}$, where each $(x_n,y_n)$ was drawn from the generating process above, that is,

[] \begin{align} &y_n \sim p^*(y) \\ &x_n \sim p^*(x|y_n). \end{align} []

We can train a neural network classifier that takes as input $x$ and outputs a probability for each possible value of $y$. This neural network can be written as

[] \begin{align} \label{eq:softmax-nn} \hat{p}(y|x; \theta, b) = \frac{\exp(f_y(x; \theta) + b_y)} {\sum_{y' \in \mathcal{Y}} \exp(f_{y'}(x; \theta)+ b_{y'})}, \end{align} []

where $f_y(x; \theta)$ is the $y$-th element of the $|\mathcal{Y}|$-dimensional output from the neural network $f$, parametrized by $\theta$ and the bias vector $b \in \mathbb{R}^{|\mathcal{Y}|}$. Inspecting this neural net's formulation, based on the so-called softmax output, we notice the following correspondences:

• $p^*(y) \approx \frac{1}{Z_y} \exp(b_y)$
• $p^*(x|y) \approx \frac{1}{Z_{x|y}} \exp(f_y(x; \theta))$,

where $Z_y$'s and $Z_{x|y}$'s are the normalization constants, which are cancelled out in Eq.~\eqref{eq:softmax-nn}.[Notes 1] In other words, the bias $b_y$ captures the marginal distribution over the output, and the rest the conditional distribution over the input given the output. This view suggests a two-stage learning process. In the first stage, we simply set $b_y$ to be $\log p^*(y)$ (and thereby set $Z_y=1$ implicitly.) Then, we use optimization, such as stochastic gradient descent, to estimate the rest of the parameters, $\theta$. After learning is over, we get

[] \begin{align} \label{eq:y-given-x} \hat{p}(y|x) = \hat{p}(y) \frac{\exp(f_y(x; \hat{\theta}))}{\sum_{y'} \exp(f_{y'}(x; \hat{\theta}))}. \end{align} []

It is important to notice that the second term on the right hand side is not the estimate of $p^*(x|y)$, since the denominator must include the extra normalization, i.e. $p(x)$. In other words,

[] \begin{align} \frac{\exp(f_y(x; \hat{\theta}))}{\sum_{y'} \exp(f_{y'}(x; \hat{\theta}))} = \frac{\hat{p}(x|y)}{\hat{p}(x)}. \end{align} []

This predictive model $\hat{p}(y|x)$ would work well even on a new instance under the iid assumption, that is, $p^*(y|x)=q^*(y|x)$. It is however not the case, because $q^*(y) \neq p^*(y)$. For instance, imagine we trained a COVID-19 diagnosis model based on various symptoms, including cough sound, temperature and others, during the winter of 2021. During this period, COVID-19 was rampant, that is, $p^*(y=1)$ was very high. If we use this model however in the winter of 2024, the overall incident rate of COVID-19 is much lower. In other words, $q^*(y=1) \ll p^*(y=1)$. This would lead to the overestimation of $p(y=1|x)$, because the prediction is proportional to $\hat{p}(y=1)$ which is an estimate of the outdated prior $p^*(y=1)$ over the output not of the latest prior $q^*(y=1)$. The prediction becomes worse as $q^*$ deviates further away from $p^*$. One simple way to address this is to assume that a priori it is more probable for the label marginal, i.e., the marginal distribution over the output, to be closer to the uniform distribution. This is a reasonable assumption in many contexts when we are not allowed any information about the situation. For instance, it is perfectly sensible to assume that any given coin is likely to be fair (that is, it has the equal chance of landing head or tail.) In that case, we would simply set the bias $b$ to be an all-zero vector so that

[] \begin{align} \hat{p}(y|x) = \frac{\exp(f_y(x; \hat{\theta}))}{\sum_{y'} \exp(f_{y'}(x; \hat{\theta}))}. \end{align} []

Sometimes we are given some glimpse into $q^*$. In the case of COVID-19, it is difficult to collect $(x,y)$ pairs but it is often easy to collect $y$'s by various means, including the survey and rapid testing in various event venues. Let $\hat{q}(y)$ be the estimate of $q^*(y)$ from such a source. We can then replace $\hat{p}(y)$ with this new estimate in Eq.~\eqref{eq:y-given-x}, resulting in

[] \begin{align} \hat{p}(y|x) = \hat{q}(y) \frac{\exp(f_y(x; \hat{\theta}))}{\sum_{y'} \exp(f_{y'}(x; \hat{\theta}))}. \end{align} []

This is equivalently to replacing the bias $b_y$ with $\log \hat{q}(y)$. In practice, it is often the case that the number of $y$ samples we can collect is limited, leading to a high-variance estimate of $q^*$. We do not want to rely solely on such an estimate. Instead, we can interpolate between $\hat{p}(y)$ and $\hat{q}(y)$, leading to replacing the bias of each output with

[] \begin{align} b_y \leftarrow \log \left(\alpha \hat{p}(y) + (1-\alpha) \hat{q}(y) \right), \end{align} []

with $\alpha \in [0, 1]$. $\alpha$ describes the degree of our trust in the original estimate of the label marginal. if $\alpha = 1$, we end up with the original iid setup, and with $\alpha=0$, we fully trust our new estimate of the label marginal.

Data augmentation. Consider an object classification task, where the goal is to build a classifier that categorizes the object in the center of an image into one of $K$ predefined classes. Just like before, we assume generative classification in which the object label produces the image. We however further assume that there exists an extra variable $z=(i,j)$ that determines the precise position of the object. \begin{center}

\end{center} During the training time, $z$ follows a Normal distribution centered at the center of the image, i.e., $z \sim \mathcal{N}(\mu_z=[0, 0]^\top, I_2)$. Assuming that the background is randomly produced and does not correlate with the identity of the object in the center, a classifier we train on data produced from this data generating process should become blind to periphery pixels, since $\mathrm{cov}(x_{mn}, y) \approx 0$, where $|m| \gg 0$ and $|n| \gg 0$. This can be written down as

[] \begin{align} p(x_{mn} | y) \approx p(x_{nm}), \end{align} []

meaning that $x_{mn}$ is independent of $y$. If we make the na\"ive Bayes assumption, that is, all pixels are independent conditioned on the label, we get the following expression of the posterior over the label:

[] \begin{align} p(y|x) \propto p(y) \prod_{m, n} p(x_{mn} | y) \propto p(y) \prod_{(m, n) \in C} p(x_{mn} | y), \end{align} []

where $C$ is a set of pixels near the center. In other words, if the object is outside the center of the image, the posterior distribution over the label would not capture the actual identity of the object. This dependence on the position arises from the existence of the hidden variable $z$ and its prior distribution $p^*(z)$. If this prior distribution over $z$ shifts in the test time, such that $q^*(z) = \mathcal{N}(\mu_z=[100, 100]^\top, I_2)$, all objects in the images would be positioned on the top-right corners. The classifier based on the training set with $p^*(z)$ will then completely fail to detect and classify these objects. Because we assume to know the precise type of shift that is possible, we can now mitigate this issue by data augmentation~[2]. During training, we randomly shift a training image such that the position of the object in the image varies more greatly than it usually does in the original training set. This can be thought of as introducing another random variable $u$ such that

[] \begin{align} p(l | z, u) = p(l), \end{align} []

where $l$ indicates the position of the object in an image. In other words, $u$ makes the position of an object independent of $z$, such that a classifier trained on the training data with such data augmentation is able to detect objects in any position, making it invariant to the distributional shift of $z$.

## General references

Cho, Kyunghyun (2024). "A Brief Introduction to Causal Inference in Machine Learning". arXiv:2405.08793 [cs.LG].

## Notes

1. $\exp(a + b) = \exp(a) \exp(b)$.

## References

1. "Distributionally robust stochastic programming" (2017). SIAM Journal on Optimization 27. SIAM.
2. "Effective training of a neural network character classifier for word recognition" (1996). Advances in neural information processing systems 9.