1 Introduction
Machine learning suffers from a fundamental problem. While machines are able to learn complex prediction rules by minimizing their training error, data are often marred by selection biases, confounding factors, and other peculiarities [43, 42, 20]
. As such, machines justifiably inherit these data biases. This limitation plays an essential role in the situations where machine learning fails to fulfill the promises of artificial intelligence. More specifically, minimizing training error leads machines into recklessly absorbing all the correlations found in training data. Understanding which patterns are useful has been previously studied as a correlationversuscausation dilemma, since spurious correlations stemming from data biases are unrelated to the causal explanation of interest
[28, 24, 31, 46]. Following this line, we leverage tools from causation to develop the mathematics of spurious and invariant correlations, in order to alleviate the excessive reliance of machine learning systems on data biases, allowing them to generalize to new test distributions.As a thought experiment, consider the problem of classifying images of cows and camels [4]
. To address this task, we label images of both types of animals. Due to a selection bias, most pictures of cows are taken in green pastures, while most pictures of camels happen to be in deserts. After training a convolutional neural network on this dataset, we observe that the model fails to classify easy examples of images of cows when they are taken on sandy beaches. Bewildered, we later realize that our neural network successfully minimized its training error using a simple cheat: classify green landscapes as cows, and beige landscapes as camels.
To solve the problem described above, we need to identify which properties of the training data describe spurious correlations (landscapes and contexts), and which properties represent the phenomenon of interest (animal shapes). Intuitively, a correlation is spurious when we do not expect it to hold in the future in the same manner as it held in the past. In other words, spurious correlations do not appear to be stable properties [48]. Unfortunately, most datasets are not provided in a form amenable to discover stable properties. Because most machine learning algorithms depend on the assumption that training and testing data are sampled independently from the same distribution [45], it is common practice to shuffle at random the training and testing examples. For instance, whereas the original NIST handwritten data was collected from different writers under different conditions [18], the popular MNIST training and testing sets [7] were carefully shuffled to represent similar mixes of writers. Shuffling brings the training and testing distributions closer together, but discards what information is stable across writers. However, shuffling the data is something that we do, not something that Nature does for us. When shuffling, we destroy information about how the data distribution changes when one varies the data sources or collection specifics. Yet, this information is precisely what tells us whether a property of the data is spurious or stable.
Here we take a step back, and assume that the training data is collected into distinct, separate environments. These could represent different measuring circumstances, locations, times, experimental conditions, external interventions, contexts, and so forth. Then, we promote learning correlations that are stable across training environments, as these should (under conditions that we will study) also hold in novel testing environments.
Returning to our motivational example, we would like to label pictures of cows and camels under different environments. For instance, the pictures of cows taken in the first environment may be located in green pastures 80% of the time. In the second environment, this proportion could be slightly different, say 90% of the time (since pictures were taken in a different country). These two datasets reveal that “cow” and “green background” are linked by a strong, but varying (spurious) correlation, which should be discarded in order to generalize to new environments. Learning machines which pool the data from the two environments together may still rely on the background bias when addressing the prediction task. But, we believe that all cows exhibit features that allow us to recognize them as so, regardless of their context.
This suggests that invariant descriptions of objects relate to the causal explanation of the object itself (“Why is it a cow?”) [29]. As shown by [35], there exists an intimate link between invariance and causation useful for generalization. However, [35] assumes a meaningful causal graph relating the observed variables, an awkward assumption when dealing with perceptual inputs such as pixels. Furthermore, [35] only applies to linear models, and scales exponentially with respect to the number of variables in the learning problem. As such, the seamless integration of causation tools [36] into machine learning pipelines remains cumbersome, disallowing what we believe to be a powerful synergy. Here, we work to address these concerns.
Contributions
We propose Invariant Risk Minimization (IRM), a novel learning paradigm that estimates nonlinear, invariant, causal predictors from multiple training environments, to enable outofdistribution (OOD) generalization. To this end, we first analyze in Section 2 how different learning techniques fail to generalize OOD. From this analysis, we derive our IRM principle in Section 3:
To learn invariances across environments, find a data representation such that the optimal classifier on top of that representation matches for all environments.
Section 4 examines the fundamental links between causation, invariance, and OOD generalization. Section 5 contains basic numerical simulations to validate our claims empirically. Section 6 concludes with a Socratic dialogue discussing directions for future research.
2 The many faces of generalization
Following [35], we consider datasets collected under multiple training environments
. These environments describe the same pair of random variables measured under different conditions. The dataset
, from environment, contains examples identically and independently distributed according to some probability distribution
.^{1}^{1}1We omit the superscripts “” when referring to a random variable regardless of the environment. Then, our goal is to use these multiple datasets to learn a predictor , which performs well across a large set of unseen but related environments . Namely, we wish to minimizewhere is the risk under environment . Here, the set of all environments contains all possible experimental conditions concerning our system of variables, both observable and hypothetical. This is in the spirit of modal realism and possible worlds [26], where we could consider, for instance, environments where we switch off the Sun. An example clarifies our intentions.
Example 1.
Consider the structural equation model [49]:
As we formalize in Section 4, the set of all environments contains all modifications of the structural equations for and , and those varying the noise of within a finite range . For instance, may replace the equation of by , or vary within this finite range . To ease exposition consider:
Then, to predict from using a leastsquares predictor for environment , we can:

regress from , to obtain and ,

regress from , to obtain and ,

regress from , to obtain and .
The regression using is our first example of an invariant correlation: this is the only regression whose coefficients do not depend on the environment . Conversely, the second and third regressions exhibit coefficients that vary from environment to environment. These varying (spurious) correlations would not generalize well to novel test environments. Also, not all invariances are interesting: the regression from the empty set of features into is invariant, but of weak predictive power.
The invariant rule is the only predictor with finite across (to see this, let ). Furthermore, this predictor is the causal explanation about how the target variable takes values across environments. In other words, it provides the correct description about how the target variable reacts in response to interventions on each of the inputs. This is compelling, as invariance is a statistically testable quantity that we can measure to discover causation. We elaborate on the relationship between invariance and causation in Section 4. But first, how can we learn the invariant, causal regression? Let us review four techniques commonly discussed in prior work, as well as their limitations.
First, we could merge the data from all the training environments and learn a predictor that minimizes the training error across the pooled data, using all features. This is the ubiquitous Empirical Risk Minimization (ERM) principle [44]. In this example, ERM would grant a large positive coefficient to if the pooled training environments lead to large (as in our example), departing from invariance.
Second, we could minimize , a robust learning objective where the constants serve as environment baselines [2, 6, 14, 40]. Setting these baselines to zero leads to minimizing the maximum error across environments. Selecting these baselines adequately prevents noisy environments from dominating optimization. For example, [32] selects
to maximize the minimal explained variance across environments. While promising, robust learning turns out to be equivalent to minimizing a weighted average of environment training errors:
Proposition 2.
Given KKT differentiability and qualification conditions, such that the minimizer of is a firstorder stationary point of .
This proposition shows that robust learning and ERM (a special case of robust learning with ) would never discover the desired invariance, obtaining infinite . This is because minimizing the risk of any mixture of environments associated to large yields a predictor with a large weight on . Unfortunately, this correlation will vanish for testing environments associated to small .
Third, we could adopt a domain adaptation strategy, and estimate a data representation that follows the same distribution for all environments [15]. This would fail to find the true invariance in Example 1, since the distribution of the true causal feature (and the one of the target ) can change across environments. This illustrates why techniques matching feature distributions sometimes attempt to enforce the wrong type of invariance, as discussed in Appendix C.
Fourth, we could follow invariant causal prediction techniques [35]. These search for the subset of variables that, when used to estimate individual regressions for each environment, produce regression residuals with equal distribution across all environments. Matching residual distributions is unsuited for our example, since the noise variance in may change across environments.
In sum, finding invariant predictors even on simple problems such as Example 1 is surprisingly difficult. To address this issue, we propose Invariant Risk Minimization (IRM), a learning paradigm to extract nonlinear invariant predictors across multiple environments, enabling OOD generalization.
3 Algorithms for invariant risk minimization
In statistical parlance, our goal is to learn correlations invariant across training environments. For prediction problems, this means finding a data representation such that the optimal classifier,^{2}^{2}2We will also use the term “classifier” to denote the last layer for regression problems. on top of that data representation, is the same for all environments. More formally:
Definition 3.
We say that a data representation elicits an invariant predictor across environments if there is a classifier simultaneously optimal for all environments, that is, for all .
Why is Definition 3
equivalent to learning features whose correlations with the target variable are stable? For loss functions such as the mean squared error and the crossentropy, optimal classifiers can be written as conditional expectations. In these cases, a data representation function
elicits an invariant predictor across environments iff for all in the intersection of the supports of we have , for all .We believe that this concept of invariance clarifies common induction methods in science. Indeed, some scientific discoveries can be traced to the realization that distinct but potentially related phenomena, once described with the correct variables, appear to obey the same exact physical laws. The precise conservation of these laws suggests that they remain valid on a far broader range of conditions. If both Newton’s apple and the planets obey the same equations, chances are that gravitation is a thing.
To discover these invariances from empirical data, we introduce Invariant Risk Minimization (IRM), a learning paradigm to estimate data representations eliciting invariant predictors across multiple environments. To this end, recall that we have two goals in mind for the data representation : we want it to be useful to predict well, and elicit an invariant predictor across . Mathematically, we phrase these goals as the constrained optimization problem:
(IRM)  
subject to 
This is a challenging, bileveled optimization problem, since each constraint calls an inner optimization routine. So, we instantiate (IRM) into the practical version: [roundcorner=5pt, backgroundcolor=yellow!8]
(IRMv1) 
where becomes the entire invariant predictor, is a scalar and fixed “dummy” classifier, the gradient norm penalty is used to measure the optimality of the dummy classifier at each environment , and is a regularizer balancing between predictive power (an ERM term), and the invariance of the predictor .
3.1 From (Irm) to (IRMv1)
This section is a voyage circumventing the subtle optimization issues lurking behind the idealistic objective (IRM), to arrive to the efficient proposal (IRMv1).
3.1.1 Phrasing the constraints as a penalty
We translate the hard constraints in (IRM) into the penalized loss
(1) 
where , the function measures how close is to minimizing , and is a hyperparameter balancing predictive power and invariance. In practice, we would like to be differentiable with respect to and . Next, we consider linear classifiers to propose one alternative.
3.1.2 Choosing a penalty for linear classifiers
Consider learning an invariant predictor , where is a linearleast squares regression, and is a nonlinear data representation. In the sequel, and
take real rowvector values, while classifiers
are columnvectors. By the normal equations, and given a fixed data representation , we can write as:(2) 
where we assumed invertibility. This analytic expression would suggest a simple discrepancy between two linear leastsquares classifiers:
(3) 
Figure 1 uses Example 1 to show why is a poor discrepancy. The blue curve shows (3) as we vary the coefficient for a linear data representation , and . The coefficient controls how much the representation depends on the variable , responsible for the spurious correlations in Example 1. We observe that (3) is discontinuous at , the value eliciting the invariant predictor. This happens because when approaches zero without being exactly zero, the leastsquares rule (2) compensates this change by creating vectors whose second coefficient grows to infinity. This causes a second problem, the penalty approaching zero as . The orange curve shows that adding severe regularization to the leastsquares regression does not fix these numerical problems.
To circumvent these issues, we can undo the matrix inversion in (2) to construct:
(4) 
which measures how much does the classifier violate the normal equations. The green curve in Figure 1 shows as we vary , when setting . The penalty is smooth (it is a polynomial on both and ), and achieves an easytoreach minimum at —the data representation eliciting the invariant predictor. Furthermore, if and only if . As a word of caution, we note that the penalty is nonconvex for general .
3.1.3 Fixing the linear classifier
Even when minimizing (1) over using , we encounter one issue. When considering a pair , it is possible to let tend to zero without impacting the ERM term, by letting tend to zero. This problem arises because (1) is severely overparametrized. In particular, for any invertible mapping , we can rewrite our invariant predictor as
This means that we can reparametrize our invariant predictor as to give any nonzero value of our choosing. Thus, we may restrict our search to the data representations for which all the environment optimal classifiers are equal to the same fixed vector . In words, we are relaxing our recipe for invariance into finding a data representation such that the optimal classifier, on top of that data representation, is “” for all environments. This turns (1) into a relaxed version of IRM, where optimization only happens over :
(5) 
As , solutions of (5) tend to solutions of (IRM) for linear .
3.1.4 Scalar fixed classifiers are sufficient to monitor invariance
Perhaps surprisingly, the previous section suggests that would be a valid choice for our fixed classifier. In this case, only the first component of the data representation would matter! We illustrate this apparent paradox by providing a complete characterization for the case of linear invariant predictors. In the following theorem, matrix parametrizes the data representation function, vector the simultaneously optimal classifier, and the predictor .
Theorem 4.
For all , let be convex differentiable cost functions. A vector can be written , where , and where simultaneously minimize for all , if and only if for all . Furthermore, the matrices for which such a decomposition exists are the matrices whose nullspace is orthogonal to and contains all the .
So, any linear invariant predictor can be decomposed as linear data representations of different ranks. In particular, we can restrict our search to matrices and let be the fixed scalar . This translates (5) into:
(6) 
Section 4 shows that the existence of decompositions with highrank data representation matrices are key to outofdistribution generalization, regardless of whether we restrict IRM to search for rank1 .
Geometrically, each orthogonality condition in Theorem 4 defines a dimensional manifold in . Their intersection is itself a manifold of dimension greater than , where is the number of environments. When using the squared loss, each condition is a quadratic equation whose solutions form an ellipsoid in . Figure 2 shows how their intersection is composed of multiple connected components, one of which contains the trivial solution . This shows that (6) remains nonconvex, and therefore sensitive to initialization.
3.1.5 Extending to general losses and multivariate outputs
Continuing from (6), we obtain our final algorithm (IRMv1) by realizing that the invariance penalty (4), introduced for the leastsquares case, can be written as a general function of the risk, namely , where is again a possibly nonlinear data representation. This expression measures the optimality of the fixed scalar classifier for any convex loss, such as the crossentropy. If the target space returned by has multiple outputs, we multiply all of them by the fixed scalar classifier .
3.2 Implementation details
When estimating the objective (IRMv1
) using minibatches for stochastic gradient descent, one can obtain an unbiased estimate of the squared gradient norm as
where and are two random minibatches of size from environment , and
is a loss function. We offer a PyTorch example in Appendix
D.3.3 About nonlinear invariances
How restrictive is it to assume that the invariant optimal classifier is linear? One may argue that given a sufficiently flexible data representation , it is possible to write any invariant predictor as . However, enforcing a linear invariance may grant noninvariant predictors a penalty equal to zero. For instance, the null data representation admits any as optimal amongst all the linear classifiers for all environments. But, the elicited predictor is not invariant in cases where . Such null predictor would be discarded by the ERM term in the IRM objective. In general, minimizing the ERM term will drive so that is optimal amongst all predictors, even if is linear.
We leave for future work several questions related to this issue. Are there noninvariant predictors that would not be discarded by either (ERM or invariance) terms in the IRM objective? What are the benefits of enforcing nonlinear invariances belonging to larger hypothesis classes ? How can we construct invariance penalties for nonlinear invariances?
4 Invariance, causality and generalization
The newly introduced IRM principle promotes low error and invariance across training environments . When do these conditions imply invariance across all environments ? More importantly, when do these conditions lead to low error across , and consequently outofdistribution generalization? And at a more fundamental level, how does statistical invariance and outofdistribution generalization relate to concepts from the theory of causation?
So far, we have omitted how different environments should relate to enable outofdistribution generalization. The answer to this question is rooted in the theory of causation. We begin by assuming that the data from all the environments share the same underlying Structural Equation Model, or SEM [49, 34]:
Definition 5.
A Structural Equation Model (SEM) governing the random vector is a set of structural equations:
where are called the parents of , and the are independent noise random variables. We say that “ causes ” if . We call causal graph of to the graph obtained by drawing i) one node for each , and ii) one edge from to if . We assume acyclic causal graphs.
By running the structural equations of a SEM according to the topological ordering of its causal graph, we can draw samples from the observational distribution . In addition, we can manipulate (intervene) an unique SEM in different ways, indexed by , to obtain different but related SEMs .
Definition 6.
Consider a SEM . An intervention on consists of replacing one or several of its structural equations to obtain an intervened SEM , with structural equations:
The variable is intervened if or .
Similarly, by running the structural equations of the intervened SEM , we can draw samples from the interventional distribution . For instance, we may consider Example 1 and intervene on , by holding it constant to zero, thus replacing the structural equation of by . Admitting a slight abuse of notation, each intervention generates a new environment with interventional distribution . Valid interventions , those that do not destroy too much information about the target variable , form the set of all environments .
Prior work [35] considered valid interventions as those that do not change the structural equation of , since arbitrary interventions on this equation render prediction impossible. In this work, we also allow changes in the noise variance of , since varying noise levels appear in real problems, and these do not affect the optimal prediction rule. We formalize this as follows.
Definition 7.
Consider a SEM governing the random vector , and the learning goal of predicting from . Then, the set of all environments indexes all the interventional distributions obtainable by valid interventions . An intervention is valid as long as (i) the causal graph remains acyclic, (ii) , and (iii) remains within a finite range.
Condition (iii) can be waived if one takes into account environment specific baselines into the definition of , similar to those appearing in the robust learning objective . We leave additional quantifications of outofdistribution generalization for future work.
The previous definitions establish fundamental links between causation and invariance. Moreover, one can show that a predictor is invariant across if and only if it attains optimal , and if and only if it uses only the direct causal parents of to predict, that is, . The rest of this section follows on these ideas to showcase how invariance across training environments can enable outofdistribution generalization across all environments.
4.1 Generalization theory for IRM
The goal of IRM is to build predictors that generalize outofdistribution, that is, achieving low error across . To this end, IRM enforces low error and invariance across . The bridge from low error and invariance across to low error across can be traversed in two steps.
First, one can show that low error across and invariance across leads to low error across . This is because, once the data representation eliciting an invariant predictor across is estimated, the generalization error of
respects standard error bounds. Second, we examine the remaining condition towards low error across
: namely, under which conditions does invariance across training environments imply invariance across all environments ? We explore this question for linear IRM.Our starting point to answer this question is the theory of Invariant Causal Prediction (ICP) [35, Theorem 2]. In there, the authors prove that ICP recovers the target invariance as long as the data (i) is Gaussian, (ii) satisfies a linear SEM, and (iii) is obtained by certain types of interventions. Theorem 9
shows that IRM learns such invariances even when these three assumptions fail to hold. In particular, we allow for nonGaussian data, dealing with observations produced as a linear transformation of the variables with stable and spurious correlations, and do not require specific types of interventions or the existence of a causal graph.
Before showing Theorem 9, we need to make our assumptions precise. To learn useful invariances, one must require some degree of diversity across training environments. On the one hand, extracting two random subsets of examples from a large dataset does not lead to diverse environments, as both subsets would follow the same distribution. On the other hand, splitting a large dataset by conditioning on arbitrary variables can generate diverse environments, but may introduce spurious correlations and destroy the invariance of interest [35, Section 3.3]. Therefore, we will require sets of training environments containing sufficient diversity and satisfying an underlying invariance. We say that a set of training environments satisfying these conditions lie in a linear general position.
Assumption 8.
A set of training environments lie in a linear general position of degree if for some , and for all nonzero :
Intuitively, the assumption of linear general position limits the extent to which the training environments are colinear. Each new environment laying in linear general position will remove one degree of freedom in the space of invariant solutions. Fortunately, Theorem
10 shows that the set of crossproducts not satisfying a linear general position has measure zero. Using the assumption of linear general position, we can show that the invariances that IRM learns across training environments transfer to all environments.In words, the next theorem states the following. If one finds a representation of rank eliciting an invariant predictor across , and lay in a linear general position of degree , then is invariant across .
Theorem 9.
Assume that
Here, , takes values in , and takes values in . Assume that there exists such that , for all environments . Let have rank . Then, if at least training environments lie in a linear general position of degree , we have that
(7) 
holds for all iff elicits the invariant predictor for all .
The assumptions about linearity, centered noise, and independence between the noise and the causal variables from Theorem 9 also appear in ICP [35, Assumption 1]. These assumptions imply the invariance . Also as in ICP, we allow correlations between the noise and the noncausal variables , which would lead ERM into absorbing spurious correlations (as in our example, where and ).
In addition, our result contains several novelties. First, we do not assume that the data is Gaussian, or that the training environments arise from specific types of interventions. Second, the result extends to “scrambled setups” where . These are situations where the causal relations are not defined on the observable features , but on a latent variable that IRM needs to recover and filter. Third, the result shows that data representations with higher rank need less training environments to generalize. This is encouraging, as data representations with higher rank destroy less information about the learning problem at hand.
We close this section with two important observations. First, while robust learning generalizes across interpolations of training environments (recall Proposition
2), learning invariances with IRM buys extrapolation powers. We can observe this in Example 1 where, using two training environments, robust learning yields predictors that work well for , while IRM yields predictors that work well for all. Finally, IRM is a differentiable function with respect to the covariances of the training environments. Therefore, in cases when the data follows an approximately invariant model, IRM should return an approximately invariant solution, being robust to mild model misspecification. This is in contrast to common causal discovery methods based on thresholding statistical hypothesis tests.
4.2 On the nonlinear case and the number of environments
In the same vein as the linear case, we could attempt to provide IRM with guarantees for the nonlinear regime. Namely, we could assume that each constraint removes one degree of freedom from the possible set of solutions . Then, for a sufficiently large number of diverse training environments, we would elicit the invariant predictor. Unfortunately, we were unable to phrase such a “nonlinear general position” assumption and prove that it holds almost everywhere, as we did in Theorem 10 for the linear case. We leave this effort for future work.
While general, Theorem 9 is pessimistic, since it requires the number of training environments to scale linearly with the number of parameters in the representation matrix . Fortunately, as we will observe in our experiments from Section 5, it is often the case that two environments are sufficient to recover invariances. We believe that these are problems where cannot match for two different environments unless extracts the causal invariance. The discussion from Section 3.3 gains relevance here, since enforcing invariance for larger families should allow discarding more noninvariant predictors with less training environments. All in all, studying what problems allow the discovery of invariances from few environments is a promising line of work towards a learning theory of invariance.
4.3 Causation as invariance
We promote invariance as the main feature of causation. Unsurprisingly, we are not pioneers in doing so. To predict the outcome of an intervention, we rely on (i) the properties of our intervention and (ii) the properties assumed invariant after the intervention. Pearl’s docalculus [34] on causal graphs is a framework that tells which conditionals remain invariant after an intervention. Rubin’s ignorability [39] plays the same role. What’s often described as autonomy of causal mechanisms [19, 1] is a specification of invariance under intervention. A large body of philosophical work [41, 37, 33, 11, 48, 12] studies the close link between invariance and causation. Some works in machine learning [17, 23, 38, 30] pursue similar questions.
The invariance view of causation transcends some of the difficulties raised by working with causal graphs. For instance, the ideal gas law or Newton’s universal gravitation are difficult to describe using structural equation models (What causes what?), but they are prominent examples of laws that are invariant across experimental conditions. When collecting data about gases or celestial bodies, the universality of these laws will manifest as invariant correlations, which will sponsor valid predictions across environments, as well as the conception of scientific theories.
Another motivation supporting the invariance view of causation are the problems studied in machine learning. For instance, consider the task of image classification. Here, the observed variables are hundreds of thousands of correlated pixels. What is the causal graph governing them? It is reasonable to assume that causation does not happen between pixels, but between the realworld concepts captured by the camera. In these cases, invariant correlations in images are a proxy into the causation at play in the real world. To find those invariant correlations, we need methods which can disentangle the observed pixels into latent variables closer to the realm of causation, such as IRM. In rare occasions we are truly interested in the entire causal graph governing all the variables in our learning problem. Rather, our focus is often on the causal invariances improving generalization across novel distributions of examples.
5 Experiments
We perform two experiments to assess the generalization abilities of IRM across multiple environments. The sourcecode will be available soon.
5.1 Synthetic data
As a first experiment, we extend our motivating Example 1. First, we increase the dimensionality of each of the two input features in to dimensions. Second, as a form of model misspecification, we allow the existence of a dimensional hidden confounder variable . Third, in some cases the features will not be directly observed, but only a scrambled version . Figure 3 summarizes the SEM generating the data for all environments in these experiments. More specifically, for environment , we consider the following variations:

Fullyobserved (F) graphs, where , or
partiallyobserved (P) graphs, where are Gaussian. 
Homoskedastic (O) noise, where and , or
heteroskedastic (E) noise, where and .

These variations lead to eight experimental setups that we will denote by their initials. For instance, the setup “FOS” considers fullyobserved (F), homoskedastic noise (O), and scrambled observations (S). For all variants, have Gaussian entries. Each experiment draws samples from the three training environments . IRM follows the variant (IRMv1), and uses the environment to crossvalidate the invariance regularizer . We compare to ERM and ICP [35].
Figure 4 summarizes the results of our experiments. We show two metrics for each estimated prediction rule . To this end, we consider a descrambled version of the estimated coefficients, . First, the plain barplots shows the average squared error between and . This measures how well does a predictor recover the weights associated to the causal variables. Second, each striped barplot shows the norm of estimated weights associated to the noncausal variable. We would like this norm to be zero, as the desired invariant causal predictor is . In summary, IRM is able to estimate the most accurate causal and noncausal weights across all experimental conditions. In most cases, IRM is orders of magnitude more accurate than ERM (our axes are in logscale). IRM also outperforms ICP, the previous stateoftheart method, by a large margin. Our experiments also show the conservative behaviour of ICP (preferring to reject most covariates as direct causes). This leads ICP into large errors on causal weights, and small errors on noncausal weights.
5.2 Colored MNIST
We validate our method for learning nonlinear invariant predictors on a synthetic binary classification task derived from MNIST. The goal is to predict a binary label assigned to each image based on the digit. Whereas MNIST images are grayscale, we color each image either red or green in a way that correlates strongly (but spuriously) with the class label. By construction, the label is more strongly correlated with the color than with the digit, so any algorithm which purely minimizes training error will tend to exploit the color. Such algorithms will fail at test time because the direction of the correlation is reversed in the test environment. By observing that the strength of the correlation between color and label varies between the two training environments, we can hope to eliminate color as a predictive feature, resulting in better generalization.
We define three environments (two training, one test) by randomly splitting the MNIST dataset in thirds and transforming each example as follows:

Assign a binary label to the image based on the digit: for digits 04 and for digits 59.

Flip the label with 25% probability.

Color the image either red or green according to its (possibly flipped) label.

Flip the color with a probability that depends on the environment: 20% in the first training environment, 10% in the second training environment, and 90% in the test environment.
Algorithm  Acc. train envs.  Acc. test env. 

ERM  86.57  14.56 
IRM (ours)  70.93  66.10 
Random guessing (hypothetical)  50  50 
Optimal invariant model (hypothetical)  75  75 
ERM, grayscale model (oracle)  73.52  72.90 
We train MLPs on the colored MNIST training environments using different objectives and report results in Table 1. Training with ERM results in a model which attains high accuracy in the training environments but belowchance accuracy in the test environment since the ERM model classifies mainly based on color. Training with IRM results in a model that performs worse on the training environments, but relies less on the color and hence generalizes better to the test environments. For comparison, we also run ERM on a model which is perfectly invariant by construction because it preprocesses all images to remove color. We find that this oracle outperforms our method only slightly.
To better understand the behavior of these models, we take advantage of the fact that
(the logit) is onedimensional and
is binary, and plot as a function of for each environment and each model in Figure 5. We show each algorithm in a separate plot, and each environment in a separate color within the plot. The figure shows that, whether considering only the two training environments or all three environments, the IRM model is closer to achieving invariance than the ERM model. Notably, the IRM model does not achieve perfect invariance, particularly at the tails of the distribution. We suspect this is because of finite sample issues: given the small sample size at the tails, estimating (and hence minimizing) the small differences in between training environments can be quite difficult, regardless of the method.6 Looking forward: a concluding dialogue
Eric and Irma are two graduate students studying the Invariant Risk Minimization (IRM) manuscript. Over a cup of coffee at a café in PalaisRoyal, they discuss the advantages and caveats that invariance brings to Empirical Risk Minimization (ERM).
IrmaI have observed that predictors trained with ERM sometimes absorb biases and spurious correlations from data. This leads to undesirable behaviours when predicting about examples that do not follow the distribution of the training data.
EricI have observed that too, and I wonder what are the reasons behind such phenomena. After all, ERM is an optimal principle to learn predictors from empirical data!
IrmaIt is, indeed. But even when your hypothesis class allows you to find the empirical risk minimizer efficiently, there are some assumptions at play. First, ERM assumes that training and testing data are identically and independently distributed according to the same distribution. Second, generalization bounds require that the ratio between the capacity of our hypothesis class and the number of training examples tends to zero, as . Third, ERM achieves zero test error only in the realizable case —that is, when there exists a function in our hypothesis class able to achieve zero error. I suspect that violating these assumptions leads ERM into absorbing spurious correlations, and that this is where invariance may prove useful.
EricInteresting. Should we study the three possibilities in turn?
IrmaSure thing! But first, let’s grab another cup of coffee.
We also encourage the reader to grab a cup of coffee.
IrmaFirst and foremost, we have the “identically and independently distributed” (iid) assumption. I once heard Professor Ghahramani refer to this assumption as “the big lie in machine learning”. This is to say that all training and testing examples are drawn from the same distribution .
EricI see. This is obviously not the case when learning from multiple environments, as in IRM. Given this factorization, I guess two things are subject to change: either the marginal distribution of my inputs, or the conditional distribution mapping those inputs into my targets.
IrmaThat’s correct. Let’s focus first on the case where is the difference across environments . Some researchers from the field of domain adaptation call this covariate shift. This situation is challenging when the supports of are disjoint across environments. Actually, without apriori knowledge, there is no reason to believe that our predictor will generalize outside the union of the supports of the training environments.
EricA daunting challenge, indeed. How could invariance help here?
IrmaTwo things come to mind. On the one hand, we could try to transform our inputs into some features , as to match the support of all the training environments. Then, we could learn an invariant classifier on top of the transformed inputs. Appendix D studies the shortcomings of this idea. On the other hand, we could assume that the invariant predictor has a simple structure, that we can estimate given limited supports. The authors of IRM follow this route, by assuming linear classifiers on top of representations.
EricI see! Even though the may be disjoint, if there is a simple invariance satisfied for all training environments separately, it may also hold in unobserved regions of the space. I wonder if we could go further by assuming some sort of compositional structure in , the linear assumption of IRM is just the simplest kind. I say this since compositional assumptions often enable learning in one part of the input space, and evaluating on another.
IrmaIt sounds reasonable! What about the case where
changes? Does this happen in normal supervised learning? I remember attending a lecture by Professor Schölkopf
[22] where he mentioned that is often invariant across environments when is a cause of , and that it often varies when is an effect of . For instance, he explains that MNIST classification is anticausal: as in, the observed pixels are an effect of the mental concept that led the writer to draw the digit in the first place. IRM insists on this relation between invariance and causation, what do you think?EricI saw that lecture too. Contrary to Professor Schölkopf [22], I believe that most supervised learning problems, such as image classification, are causal. In these problems we predict human annotations from pixels , hoping that the machine imitates this cognitive process. Furthermore, the annotation process often involves multiple humans in the interest of making deterministic. If the annotation process is close to deterministic and shared across environments, predicting annotations is a causal problem, with an invariant conditional expectation.
IrmaOh! This means that in supervised learning problems about predicting annotations, is often stable across environments, so ERM has great chances of succeeding. This is good news: it explains why ERM is so good at supervised learning, and leaves less to worry about. EricHowever, if any of the other problems appear (disjoint , not enough data, not enough capacity), ERM could get in trouble, right? IrmaIndeed! Furthermore, in some supervised learning problems, the label is not necessarily created from the input. For instance, the input could be an Xray image, and the target could be the result of a tumor biopsy on the same patient. Also, there are problems where we predict parts of the input from other parts of the input, like in selfsupervised learning [13]
. In some other cases, we don’t even have labels! This could include the unsupervised learning of the causal factors of variation behind
, which involves inverting the causal generative process of the data. In all of these cases, we could be dealing with anticausal problems, where the conditional distribution is subject to change across environments. Then, I expect searching for invariance may help by focusing on invariant predictors that generalize outofdistribution.EricThat is an interesting divide between supervised and unsupervised learning! Figure 6 illustrates the main elements of this discussion.
EricSecondly, what about the ratio between the capacity of our classifier and the number of training examples ? Modern neural networks often have a number of parameters on the same order of magnitude, or even greater, than the number of training examples. In these cases, I doubt that this ratio will tend to zero as . So, ERM may be in trouble.
IrmaThat is correct. Neural networks are often overparametrized, and overparametrization carries subtle consequences. For instance, consider that we are using the pseudoinverse to solve an overparametrized linear leastsquares problem, or using SGD to train an overparametrized neural network. Amongst all the zero training error solutions, these procedures will prefer the solution with the smallest capacity [47, 3]. Unfortunately, spurious correlations and biases are often simpler to detect than the true phenomenon of interest [16, 8, 9, 10]. Therefore, low capacity solutions prefer exploiting those simple but spurious correlations. For instance, think about relying on large green textures to declare the presence of a cow on an image.
EricThe cows again!
IrmaAlways. Although I can give you a more concrete example. Consider predicting from , where:
the coefficients satisfy , the training environments are , and we have samples for the dimensional input . In this overparametrized problem, the invariant regression from the cause requires large capacity, while the spurious regression from the effect requires low capacity.
EricOh! Then, the inductive bias of SGD would prefer to exploit the spurious correlation for prediction. In a nutshell, a deficit of training examples forces us into regularization, and regularization comes with the danger of absorbing easy spurious correlations. But, methods based on invariance should realize that, after removing the nuisance variable , the regression from is invariant, and thus interesting for outofdistribution generalization. This means that invariance could sometimes help fighting the issues of small data and overparametrization. Neat!
IrmaAs a final obstacle to ERM, we have the case where the capacity of our hypothesis class is insufficient to solve the learning problem at hand.
EricThis sounds related to the previous point, in the sense that a model with low capacity will stick to spurious correlations, if these are easier to capture.
IrmaThat is correct, although I can see an additional problem arising from insufficient capacity. For instance, the only linear invariant prediction rule to estimate the quadratic , where , is the null predictor . Even though is the only, causal, and invarianceeliciting covariate!
EricGot it. Then, we should expect invariance to have a larger chance of success when allowing high capacity. For lowcapacity problems, I would rely on crossvalidation to lower the importance of the invariance penalty in IRM, and fall back to good old ERM.
IrmaERM is really withstanding the test of time, isn’t it?
EricDefinitely. From what we have discussed before, I think ERM is specially useful in the realizable case, when there is a predictor in my hypothesis class achieving zero error.
IrmaWhy so?
EricIn the realizable case, the optimal invariant predictor has zero error across all environments. Therefore it makes sense, as an empirical principle, to look for zero training error across training environments. This possibly moves towards an optimal prediction rule on the union of the supports of the training environments. This means that achieving invariance across all environments using ERM is possible in the realizable case, although it would require data from lots of environments!
IrmaWait a minute. Are you saying that achieving zero training error makes sense from an invariance perspective?
EricIn the realizable case, I would say so! Turns out all these people training neural networks to zero training error were onto something!
The barista approaches Eric and Irma to let them know that the café is closing.
EricThank you for the interesting chat, Irma.
IrmaThe pleasure is mine!
EricOne of my takeaways is that discarding spurious correlations is something doable even when we have access only to two environments. The remaining, invariant correlations sketch the core pieces of natural phenomena, which in turn form a simpler model.
IrmaSimple models for a complex world. Why bother with the details, right?
EricHah, right. It seems like regularization is more complex than we thought. I wonder what other applications we can find for invariance. Perhaps we could think of reinforcement learning episodes as different environments, so we can learn robust policies that leverage the invariant part of behaviour leading to reward.
IrmaThat is an interesting one. I was also thinking that invariance has something to say about fairness. For instance, we could consider different groups as environments. Then, learning an invariant predictor means finding a representation such that the best way to treat individuals with similar relevant features is shared across groups.
EricInteresting! I was also thinking that it may be possible to formalize IRM in terms of invariance and equivariance concepts from group theory. Do you want to take a stab at these things tomorrow at the lab?
IrmaSurely. See you tomorrow, Eric.
EricSee you tomorrow!
The students pay their bill, leave the café, and stroll down the streets of Paris, quiet and warm during the Summer evening.
Acknowledgements
We are thankful to Francis Bach, Marco Baroni, Ishmael Belghazi, Diane Bouchacourt, François Charton, Yoshua Bengio, Charles Blundell, Joan Bruna, Soumith Chintala, Kyunghyun Cho, Jonathan Gordon, Christina HeinzeDeml, Alyosha Efros, Luke Metz, Cijo Jose, Anna Klimovskaia, Maxime Oquab, Jonas Peters, Alec Radford, Cinjon Resnick, Uri Shalit, Pablo Sprechmann, Sónar festival, Rachel Ward, and Will Whitney for their help in this work.
References
 [1] John Aldrich. Autonomy. Oxford Economic Papers, 1989.
 [2] James Andrew Bagnell. Robust supervised learning. In AAAI, 2005.

[3]
Peter L. Bartlett, Philip M. Long, Gábor Lugosi, and Alexander
Tsigler.
Benign Overfitting in Linear Regression.
arXiv, 2019.  [4] Sara Beery, Grant Van Horn, and Pietro Perona. Recognition in terra incognita. In ECCV, 2018.
 [5] Shai BenDavid, John Blitzer, Koby Crammer, and Fernando Pereira. Analysis of representations for domain adaptation. In NIPS. 2007.
 [6] Aharon BenTal, Laurent El Ghaoui, and Arkadi Nemirovski. Robust optimization. Princeton University Press, 2009.
 [7] Léon Bottou, Corinna Cortes, John S. Denker, Harris Drucker, Isabelle Guyon, Lawrence D. Jackel, Yann Le Cun, Urs A. Muller, Eduard Säckinger, Patrice Simard, and Vladimir Vapnik. Comparison of classifier methods: a case study in handwritten digit recognition. In ICPR, 1994.

[8]
Wieland Brendel and Matthias Bethge.
Approximating CNNs with bagoflocalfeatures models works surprisingly well on imagenet.
In ICLR, 2019.  [9] Joan Bruna and Stephane Mallat. Invariant scattering convolution networks. TPAMI, 2013.

[10]
Joan Bruna, Stephane Mallat, Emmanuel Bacry, and JeanFrançois Muzy.
Intermittent process analysis with scattering moments.
The Annals of Statistics, 2015.  [11] Nancy Cartwright. Two theorems on invariance and causality. Philosophy of Science, 2003.
 [12] Patricia W. Cheng and Hongjing Lu. Causal invariance as an essential constraint for creating a causal representation of the world. The Oxford handbook of causal reasoning, 2017.
 [13] Jacob Devlin, MingWei Chang, Kenton Lee, and Kristina Toutanova. Bert: Pretraining of deep bidirectional transformers for language understanding. NAACL, 2019.
 [14] John Duchi, Peter Glynn, and Hongseok Namkoong. Statistics of robust optimization: A generalized empirical likelihood approach. arXiv, 2016.
 [15] Yaroslav Ganin, Evgeniya Ustinova, Hana Ajakan, Pascal Germain, Hugo Larochelle, François Laviolette, Mario March, and Victor Lempitsky. Domainadversarial training of neural networks. JMLR, 2016.
 [16] Robert Geirhos, Patricia Rubisch, Claudio Michaelis, Matthias Bethge, Felix A. Wichmann, and Wieland Brendel. Imagenettrained cnns are biased towards texture; increasing shape bias improves accuracy and robustness. ICLR, 2019.
 [17] AmirEmad Ghassami, Saber Salehkaleybar, Negar Kiyavash, and Kun Zhang. Learning causal structures using regression invariance. In NIPS, 2017.
 [18] Patrick J. Grother. NIST Special Database 19: Handprinted forms and characters database. https://www.nist.gov/srd/nistspecialdatabase19, 1995. File doc/doc.ps in the 1995 NIST CD ROM NIST Special Database 19.
 [19] Trygve Haavelmo. The probability approach in econometrics. Econometrica: Journal of the Econometric Society, 1944.
 [20] Allan Jabri, Armand Joulin, and Laurens Van Der Maaten. Revisiting visual question answering baselines. In ECCV, 2016.
 [21] Fredrik D. Johansson, David A. Sontag, and Rajesh Ranganath. Support and invertibility in domaininvariant representations. AISTATS, 2019.
 [22] Niki Kilbertus, Giambattista Parascandolo, and Bernhard Schölkopf. Generalization in anticausal learning. arXiv, 2018.
 [23] Kun Kuang, Peng Cui, Susan Athey, Ruoxuan Xiong, and Bo Li. Stable prediction across unknown environments. In SIGKDD, 2018.
 [24] Brenden M. Lake, Tomer D. Ullman, Joshua B Tenenbaum, and Samuel J. Gershman. Building machines that learn and think like people. Behavioral and brain sciences, 2017.
 [25] James M. Lee. Introduction to Smooth Manifolds. Springer, 2003.
 [26] David Lewis. Counterfactuals. John Wiley & Sons, 2013.
 [27] Ya Li, Xinmei Tian, Mingming Gong, Yajing Liu, Tongliang Liu, Kun Zhang, and Dacheng Tao. Deep domain generalization via conditional invariant adversarial networks. In ECCV, 2018.
 [28] David LopezPaz. From dependence to causation. PhD thesis, University of Cambridge, 2016.
 [29] David LopezPaz, Robert Nishihara, Soumith Chintala, Bernhard Scholkopf, and Léon Bottou. Discovering causal signals in images. In CVPR, 2017.
 [30] Sara Magliacane, Thijs van Ommen, Tom Claassen, Stephan Bongers, Philip Versteeg, and Joris M Mooij. Domain adaptation by using causal inference to predict invariant conditional distributions. In NIPS, 2018.
 [31] Gary Marcus. Deep learning: A critical appraisal. arXiv, 2018.
 [32] Nicolai Meinshausen and Peter Bühlmann. Maximin effects in inhomogeneous largescale data. The Annals of Statistics, 2015.
 [33] Sandra D. Mitchell. Dimensions of scientific law. Philosophy of Science, 2000.
 [34] Judea Pearl. Causality: Models, Reasoning, and Inference. Cambridge University Press, 2nd edition, 2009.

[35]
Jonas Peters, Peter Bühlmann, and Nicolai Meinshausen.
Causal inference using invariant prediction: identification and confidence intervals.
JRSS B, 2016.  [36] Jonas Peters, Dominik Janzing, and Bernhard Schölkopf. Elements of causal inference: foundations and learning algorithms. MIT press, 2017.
 [37] Michael Redhead. Incompleteness, non locality and realism. a prolegomenon to the philosophy of quantum mechanics. 1987.

[38]
Mateo RojasCarulla, Bernhard Schölkopf, Richard Turner, and Jonas Peters.
Invariant models for causal transfer learning.
JMLR, 2018.  [39] Donald B. Rubin. Estimating causal effects of treatments in randomized and nonrandomized studies. Journal of educational Psychology, 1974.
 [40] Aman Sinha, Hongseok Namkoong, and John Duchi. Certifying some distributional robustness with principled adversarial training. ICLR, 2018.
 [41] Brian Skyrms. Causal necessity: a pragmatic investigation of the necessity of laws. Yale University Press, 1980.
 [42] Bob L. Sturm. A simple method to determine if a music information retrieval system is a “horse”. IEEE Transactions on Multimedia, 2014.
 [43] Antonio Torralba and Alexei Efros. Unbiased look at dataset bias. In CVPR, 2011.
 [44] Vladimir Vapnik. Principles of risk minimization for learning theory. In NIPS. 1992.
 [45] Vladimir N. Vapnik. Statistical Learning Theory. John Wiley & Sons, 1998.
 [46] Max Welling. Do we still need models or just more data and compute?, 2019.
 [47] Ashia C. Wilson, Rebecca Roelofs, Mitchell Stern, Nati Srebro, and Benjamin Recht. The marginal value of adaptive gradient methods in machine learning. In NIPS. 2017.
 [48] James Woodward. Making things happen: A theory of causal explanation. Oxford university press, 2005.
 [49] Sewall Wright. Correlation and causation. Journal of agricultural research, 1921.
Appendix A Additional theorems
Theorem 10.
Let , with the space of symmetric positive semidefinite matrices, and . Then, for any arbitrary tuple , the set
has measure zero in .
Appendix B Proofs
b.1 Proof of Proposition 2
Let
Then, the pair solves the constrained optimization problem
s.t. 
with Lagrangian . If the problem above satisfies the KKT differentiability and qualification conditions, then there exist with , such that
b.2 Proof of Theorem 4
Let , , and . The simultaneous optimization
(8) 
is equivalent to
(9) 
where is the set of vectors reachable by picking any . It turns out that , that is, the subspace orthogonal to the nullspace of . Indeed, for all and all , we have . Therefore . Since both subspaces have dimension , they must be equal.
We now prove the theorem: let where and minimizes all . Since , we have . Since minimizes , we can also write
(10) 
Therefore . Finally .
Conversely, let satisfy for all . Thanks to these orthogonality conditions, we can construct a subspace that contains all the and is orthogonal to . Let be any matrix whose nullspace satisfies these conditions. Since , that is, , there is a vector such that . Finally, since , the derivative (10) is zero.