SlowGuess/NeurIPS_2023_OCR huggingface dataset:
Jia-Qi Yang De-Chuan Zhan* Le Gan
State Key Laboratory for Novel Software Technology
Nanjing University, Nanjing, 210023, China
yangjq@lamda.nju.edu.cn, zhandc@nju.edu.cn, ganle@nju.edu.cn
Research has shown that deep networks tend to be overly optimistic about their predictions, leading to an underestimation of prediction errors. Due to the limited nature of data, existing studies have proposed various methods based on model prediction probabilities to bin the data and evaluate calibration error. We propose a more generalized definition of calibration error called Partitioned Calibration Error (PCE), revealing that the key difference among these calibration error metrics lies in how the data space is partitioned. We put forth an intuitive proposition that an accurate model should be calibrated across any partition, suggesting that the input space partitioning can extend beyond just the partitioning of prediction probabilities, and include partitions directly related to the input. Through semantic-related partitioning functions, we demonstrate that the relationship between model accuracy and calibration lies in the granularity of the partitioning function. This highlights the importance of partitioning criteria for training a calibrated and accurate model. To validate the aforementioned analysis, we propose a method that involves jointly learning a semantic aware grouping function based on deep model features and logits to partition the data space into subsets. Subsequently, a separate calibration function is learned for each subset. Experimental results demonstrate that our approach achieves significant performance improvements across multiple datasets and network architectures, thus highlighting the importance of the partitioning function for calibration.
With the advancements in deep learning technology, deep learning models have achieved, and in some cases even surpassed, human-level accuracy in various domains[1, 2]. In safety-critical applications[3, 4] such as self-driving[5] and disease diagnosis[6], it is not only desirable to have high accuracy from models but also to have their predicted probabilities reflect the true likelihood of correctness. For instance, if a model predicts a probability of 0.9 for a particular class, we expect the actual probability of being correct to be close to 0.9. This is known as probability calibration. However, recent research has indicated that while deep models have improved in accuracy, their probability calibration has declined[7-9]. Typically, deep models tend to overestimate the probabilities of correct predictions, leading to overconfidence. This discrepancy between accuracy and calibration has made model calibration a crucial research direction.[7, 10-19]
Defining an evaluation method for assessing the degree of calibration is crucial to calibrating a model. Currently, most evaluation methods are based on binning model prediction probabilities, followed by analyzing the distribution of true labels within each bin[7, 12, 20, 21]. The calibration error is then estimated by measuring the difference between the predicted probabilities and the empirical
*De-Chuan Zhan is the corresponding author.
(a) No calibration
(b) Calibrated with IR
Figure 1: We reconstruct CIFAR10 into a binary classification problem  $\left([0 - 4]\right.$  as positives,  $[5 - 9]$  as negatives) and train a Resnet152 on it. Initially, the predicted probabilities are severely uncalibrated, as shown in (a). Then we train an Isotonic regression (IR) model (with the test labels) to calibrate outputs, which leads to nearly perfect calibration in (b). However, the partitions defined by original labels may reveal underlining miscalibration. For example, let  $G_{1} = \{0,1,2,5,6,7\}$ ,  $G_{2} = \{3,4,8,9\}$ . The outputs of IR turned out to be significantly underconfident on  $G_{1}$  and overconfident on  $G_{2}$ .
(c) Underconfidence in  $\mathbf{G}_1$
(d) Overconfidence in  $\mathbf{G}_2$
distribution. However, such estimation of calibration error fails to reflect the model's accuracy[22]. For instance, consider a binary classification problem where both classes are distributed uniformly, and the model consistently outputs a probability of 0.5 for all inputs. Even using the strictest evaluation method for calibration error, this classifier would appear perfectly calibrated[22]. In reality, as long as the evaluation of calibration error is solely based on prediction probabilities, a classifier with a fixed output marginal distribution  $p(y)$  would always be perfectly calibrated but useless. This type of calibration error definition may also be counterintuitive to some extent. For example, a recommendation model may be overconfident in one user group and underconfident in another, yet still be considered calibrated overall. However, no user would perceive the model's output probabilities as accurate in such cases. To illustrate this issue, we present a constructed experiment in Figure. 1, which demonstrates the existence of such situations.
For calibrating a trained model, existing methods mainly rely on transforming the model's predicted probabilities or logits (inputs to the softmax layer)[7, 10-12, 23-25]. For example, histogram binning[7] involves binning the predicted probabilities and calibrating the probabilities within each bin separately. However, as discussed earlier regarding calibration error analysis, if a calibration method relies solely on the model's output probabilities for calibration, it cannot achieve calibration across different semantic contexts  $(x)$  because the calibration model itself is completely unaware of semantics. Some studies have analyzed calibration across different categories and proposed corresponding calibration methods. For instance, the Dirichlet calibration method[12] models multiclass probabilities as Dirichlet distributions and transforms the uncalibrated probabilities into calibrated ones. These methods incorporate category information, allowing for calibration across different categories. However, this category information may not be directly available, or the known categories may not be the divisions we are interested in. For example, in a recommendation system, we may want the model to be calibrated across various skin color groups, even if we may not have access to the corresponding category information.
Contribution. The analysis above has inspired us to propose that a perfectly calibrated model should be calibrated across any data space partition. We present the Partitioned Calibration Error (PCE) as a comprehensive framework for defining semantic-aware calibration errors. By illustrating that various common calibration error metrics are specific instances of PCE under distinct partition functions, we establish a direct correlation between calibration error and model accuracy: PCE converges to accurate score functions of data uncertainty through a bijective grouping function. To discover more effective partition rules, we introduce a technique that incorporates a linear layer onto the deep model's features, enabling the modeling of the partition function. By employing softmax to generate a soft partition, we achieve end-to-end optimization. By generating diverse partition functions, our approach facilitates calibration across different semantic domains, thereby enhancing overall calibration performance without losing accuracy. Experimental results across multiple datasets and network architectures consistently demonstrate the efficacy of our method in improving calibration.
2 Partitioned calibration error and grouping-based calibration
We first present our formulation of PCE, which serves as the foundation for our calibration approach.
2.1 Measuring calibration with partitions
We start by defining the partition by a grouping function as follows.
Definition 1 (Grouping function and input space partition). A grouping function  $g$  is a mapping from an input  $x$  to a group indicator  $g(x) = G \in \mathcal{G}$ , with the following three properties:
$$
\forall x \in \mathcal {D}, \exists G \in \mathcal {G}, g (x) = G \tag {1}
$$
$$
\forall x _ {1}, x _ {2}, g \left(x _ {1}\right) \neq g \left(x _ {2}\right)\rightarrow x _ {1} \neq x _ {2} \tag {2}
$$
$$
\forall \hat {G} \in \mathcal {G}, \exists \hat {x} \in \mathcal {D}, g (\hat {x}) = \hat {G} \tag {3}
$$
The group indicator  $G$  is also used to denote the induced subset  $\{x|g(x) = G\}$ .
Lemma 1. A partition of the input space  $\mathcal{D}$  is defined by  $P = \{\{x|g(x) = \hat{G}\} |\hat{G}\in \mathcal{G}\}$ .
Proof. By definition, the subsets in  $P$  are (1) non-overlapping (by Eq. (2)), (2) non-empty (by Eq. (3)), (3) the union of all the groups is equal to the universe set(by Eq. (1)). which guarantees  $P$  being a valid partition on set  $\mathcal{D}$  of all valid  $x$ .
We use  $x \in G$  and  $g(x) = G$  interchangeably, and  $(x,y) \in G \leftrightarrow g(x) = G$ . With the partition defined above, we can now define the partitioned calibration error.
Definition 2 (Partitioned calibration error (PCE)).
$$
\operatorname {P C E} (S, g, \mathcal {L}, f, \mathcal {D}) = \sum_ {P \in \mathcal {P}} p (P) \sum_ {G \in P} p (G) \mathcal {L} (S (G), S (f (G))) \tag {4}
$$
Where  $\mathcal{P}$  is the set of all concerned partitions,  $p(P)$  is the probability of choosing partition  $P$ ,  $p(G) = \int_{(x,y)\in G}p(x,y)$  is the probability of observing a data sample belonging to group  $G$ ,  $S(\cdot)$  is a specific statistical magnitude that can be calculated on a group. A straightforward definition of  $S(\cdot)$  is the average function  $S(G) = \int_{x,y}p_G(x,y)y$ , and  $S(f(G)) = \int_{x,y}p_G(x,y)f(x)$ , where  $y$  is the one-hot label with  $y_i = 1$  if  $x\in i$  th class and  $y_i = 0$  otherwise.  $f(x)_i$  is the predicted probability of  $x$  being ith class.  $\mathcal{L}(\cdot ,\cdot)$  measures the difference between  $S(G)$  and  $S(f(G))$ .  $p_G(x,y)$  is the normalized probability density function of  $x\in G$ , that is,
$$
p _ {G} (x, y) = \left\{ \begin{array}{l l} 0, & \text {i f} x \notin G \\ \frac {p (x , y)}{p (G)}, & \text {i f} x \in G \end{array} \right. \tag {5}
$$
We will write  $p_G(x, y)$  as  $p_G$  in the following contents for simplicity. In summary, the aforementioned Eq. (4) defines PCE, which quantifies the expected disparity between the predicted probabilities and the true probabilities within each subgroup, after randomly selecting a partition.
Example 1 (Expected calibration error (ECE)[23]). With  $g(x) = \mathrm{Bin}(f(x))$ , where  $\mathrm{Bin}(\cdot)$  returns the corresponding Bin ID,  $\mathcal{L}(a,b) = |a - b|$ , and keep  $S$  as the average function.
$$
\mathrm {P C E} = \sum_ {G \in P} p (G) \mathcal {L} (S (G), S (f (G))) = \sum_ {G \in P} p (G) \left| \int_ {x, y} p _ {G} f (x) - \int_ {x, y} p _ {G} y \right| \tag {6}
$$
and its empirical estimation is
$$
P C E = \sum_ {G} \frac {| G |}{| D |} \left| \sum_ {(x, y) \in G} \frac {1}{| G |} f (x) - \sum_ {(x, y) \in G} \frac {1}{| G |} y \right| \tag {7}
$$
which is exactly the ECE estimator defined in [23] Eq.3.
Note that in the above ECE, there is only one partition. We provide an example of using multiple partitions in the following example.
Example 2 (Class-wise ECE[12]). There are  $M$  partitions corresponding to  $M$  classes. The partition of class  $u$  is denoted by  $P_{u}$ , the corresponding grouping function is defined by  $g_{u}(x) = \mathrm{Bin}(f(x)_{u})$ .
$$
\text {C l a s s w i s e - E C E} = \sum_ {P _ {u}} \frac {1}{M} \sum_ {G \in P _ {u}} \frac {| G |}{| D |} \left| \sum_ {(x, y) \in G} \frac {1}{| G |} f (x) - \sum_ {(x, y) \in G} \frac {1}{| G |} y \right| \tag {8}
$$
which is exactly the same as Eq. 4 in [12].
Example 3 (Top-label calibration error (TCE)[25]). With  $g(x) = \mathrm{Bin}(\max_i f(x)_i)$ ,  $S(G) = \frac{1}{|G|}\sum \mathbb{I}(y = \arg \max_i f(x)_i)$ , and  $S(f(G)) = \frac{1}{|G|}\sum_{(x,y)\sim G}\max_i f(x)_i$ . Resulting in the Top-label calibration error defined in [25].
From the above examples, it can be observed that the sole distinction among the aforementioned calibration metrics lies in the employed grouping function. Hereinafter, we shall delve into two distinctive scenarios of PCE to shed light on the intricate interplay between calibration and accuracy.
Example 4 (One-to-one grouping function). If the grouping function  $g(\cdot)$  is a bijection, then every different  $x$  belongs to different groups, which corresponds to point-wise accuracy.
$$
\mathrm {P C E} = \sum_ {P \in \mathcal {P}} p (P) \sum_ {G \in P} p (G) \mathcal {L} (S (G), S (f (G))) = \int_ {x, y} p (x, y) \mathcal {L} (y, f (x)) \tag {9}
$$
Minimizing this PCE with bijective grouping function will converge to  $f(x) = p(y|x)$  if a proper score function  $\mathcal{L}$  (e.g., cross-entropy or Brier score[26]) is used with unlimited data. The uncertainty reflected by  $p(y|x)$  is called aleatoric uncertainty[27] and is the best a model can achieve corresponding to Bayes error[28, 29].
Example 5 (Constant grouping function). If the grouping function  $g$  is a constant function with  $\forall x_1, x_2, g(x_1) = g(x_2)$ , then every different  $x$  belongs to a single group.
$$
\mathrm {P C E} = \mathcal {L} \left(\int_ {x, y} p (x, y) f (x), \int_ {x, y} p (x, y) y\right) \tag {10}
$$
which is minimized by the model outputs the marginal distribution  $f(x) = \int_{(x,y)} p(x,y)y = p(y)$ .
We provide proofs and further discussion about Example. (4) and Example. (5) in the supplementary materials. The constant grouping function captures the vanilla uncertainty that we do not have any knowledge about  $x$ , and we only know the marginal distribution of  $y$ .
The above analysis demonstrates that by employing finer partitions, PCE becomes a closer approximation to the measure of accuracy. Conversely, coarser partitions align more closely with the traditional calibration metrics utilized in prior research. Since neither extreme partitioning approach applies to practical calibration, selecting an appropriate partitioning method is crucial for calibration performance.
2.2 Calibration with semantic-aware partitions
Calibration methods can be designed from the perspective of minimizing the corresponding PCE. For instance, histogram binning[7] adjusts the predicted probabilities within each bin to the mean of the true probabilities in that bin. On the other hand, Bayesian Binning into Quantiles (BBQ)[11] calibration involves setting multiple distinct bin counts and then obtaining a weighted average of the predictions from histogram binning for each bin count, effectively encompassing scenarios with multiple partitions in the PCE. However, existing methods rely on binning and calibration based solely on model output probabilities. Our proposed PCE suggests that the partitioning approach can depend not only on the predicted probabilities but also on the information in input  $x$  itself. This would significantly enhance the flexibility of the partitions.
To facilitate implementation, we begin by imposing certain constraints on the range of outputs from the grouping function. We denote the number of partitions by  $U = |\mathcal{P}|$  (each partition corresponds to a specific grouping function as defined in Definition 1), and we assume that all data can be partitioned into  $K$  groups. The output of the grouping function  $g$  takes the form of a one-hot encoding, where if  $x$  belongs to the  $i$ -th group,  $g(x)_i = 1, 0 < i < K$ , while all other  $g(x)_j = 0, j \neq i$ . And
$G_{i} = \{x|g(x)_{i} = 1\}$  is the  $i$ -th group. Under these conditions, the expression for PCE can be formulated as follows:
$$
\mathrm {P C E} = \sum_ {i} ^ {K} \frac {\left| G _ {i} \right|}{\left| D \right|} \mathcal {L} \left(S \left(G _ {i}\right), S \left(f _ {G _ {i}} \left(G _ {i}\right)\right)\right) \tag {11}
$$
From the above equation, it is evident that for each group  $G_{i}$ , we can learn a calibration function  $f_{G_i}$  specific to that group, which aims to minimize the calibration error within the group  $G_{i}$ .
In this paper, we employ the temperature scaling method as the learning approach for the calibration function within each group. Specifically, temperature scaling involves adding a learnable temperature parameter  $\tau$  to the logits  $o(x)$  (i.e., the input to the softmax function) of the model and applying it to a group, resulting in the following form of grouping loss:
$$
\mathcal {L} _ {\text {g r o u p}} = \frac {1}{| G _ {i} |} \sum_ {x, y \in G _ {i}} \log \frac {e ^ {\frac {o (x) _ {y}}{\tau_ {i}}}}{\sum_ {j} e ^ {\frac {o (x) _ {j}}{\tau_ {i}}}} \tag {12}
$$
where the temperature parameter  $\tau_{i}$  is specific to group  $G_{i}$ . Note that  $\mathcal{L}_{\text{group}}$  is not a direct estimation of  $\mathcal{L}(S(G_i), S(f_{G_i}(G_i)))$ . Specifically, if we choose  $S$  to be the average function, so the empirical estimation of  $S(G_{i}) = \frac{1}{|G_{i}|} \sum_{x,y \in G_{i}} y$ , and the empirical estimation of  $S(f_{G_i}(G_i)) = \frac{1}{|G_i|} \sum_{x,y \in G_i} f_{G_i}(x)$ . Then, we choose the difference measure  $\mathcal{L}$  to be the log-likelihood (cross entropy)  $\mathcal{L}(S(G_i), S(f_{G_i}(G_i))) = \sum_j S(G_i)_j \log S(f_{G_i}(G_i))_j$ , where  $j$  is the class index. The  $\mathcal{L}_{\text{group}}$  will be minimized by  $f_{G_i}(x) = y$ , which will also minimize  $\mathcal{L}(S(G_i), S(f_{G_i}(G_i)))$ . Thus, Eq. (12) is a stronger constraint compared with minimizing  $\mathcal{L}(S(G_i), S(f_{G_i}(G_i)))$  directly. Our choice of this objective is motivated by two reasons: First, Eq. (12) is able to provide more signals during training since each label  $y$  can guide corresponding  $f_{G_i}(x)$  directly. On the contrary, if we optimize  $\mathcal{L}(S(G_i), S(f_{G_i}(G_i)))$  directly, the labels and predictions are mixed and much label information is lost. Secondly, optimizing Eq. (12) aligns well with the calibration method (TS and ETS) to be used, which leads to better calibration performance.
In the aforementioned equation Eq. (12), we assume that the groups  $G_{i}$  are known. In order to optimize the partition, we incorporate the grouping function  $g(\cdot)$  into the loss function. By summing the above equation over all groups according to Eq. (11), we can obtain the final optimization objective.
$$
\mathcal {L} _ {G C + T S} = \frac {1}{| D |} \sum_ {x, y \in D} \log \sum_ {i} g (x) _ {i} \frac {e ^ {\frac {o (x) _ {y}}{\tau_ {i}}}}{\sum_ {j} e ^ {\frac {o (x) _ {j}}{\tau_ {i}}}} \tag {13}
$$
When the output of  $g(x)$  is in the form of one-hot encoding, the above equation represents a standard grouping loss function. To optimize  $g$ , we introduce a smoothing technique that transforms its output into a probability value. Specifically, we add a linear layer on top of the neural network's features  $z$  and follow it with a softmax function as the grouping function  $g$ , which takes the following form:
$$
g _ {\phi} (x) = g _ {\phi} ^ {\prime} (z (x)) = \operatorname {s o f t m a x} (z (x) \phi_ {w} + \phi_ {b}) \tag {14}
$$
where  $z\in \mathbb{R}^{|D|\times d_z}$ ,  $\phi_w\in \mathbb{R}^{d_z\times K}$ ,  $\phi_b\in \mathbb{R}^{1\times K}$ . The features  $z(x)$  are fixed, which aligns with the post-calibration setting. The above loss function is the combination of grouping and temperature scaling, which is denoted as Grouping Calibration + Temperature Scaling (GC+TS).
Training  $g_{\phi}(x)$ . The parameters  $\phi$  of grouping function  $g$  is trained jointly with the calibration function  $f_{\theta}$  on the validation dataset  $D_{val}$  (used in early stopping when training deep models). In the GC+TS method, the trainable parameters of  $f$  is  $\theta = \{\tau_i\}$ . In a more intuitive sense, equation Eq. (13) necessitates that the grouping function identifies the optimal partitioning, where adjusting  $\tau_i$  within each subgroup  $G_i$  minimizes the cross-entropy loss. Furthermore, due to the non-uniqueness of the optimal grouping function that satisfies the aforementioned objective function, we can generate multiple distinct partitions by optimizing with different initial values through multiple iterations. To mitigate the potential overfitting caused by the high flexibility of the grouping function  $g$ , we have introduced an additional regularization term, and the overall training loss of training  $g_{\phi}$  is  $\mathcal{L}_{GC + TS} + \lambda ||\phi_w||_2^2$ .
Training  $f_{\theta}(x)$ . After training of  $g_{\phi}$ , we simply apply a calibration method to each group. We can also use temperature scaling in this phase while using hard grouping in Eq. (13). Any other
calibration methods are also applicable, for example, we also adopt Ensemble Temperature Scaling (ETS)[23] method to obtain  $\mathrm{GC + ETS}$  in our experiments. The calibration function  $f_{\theta}$  is trained on the holdout training dataset  $D_{ho}$ , while keeping the grouping function fixed. Then the calibration function  $f$  is used on each group of the testing dataset. The overall training and predicting procedure is summarized in Algorithm 1.
Calibrating with trained partitions. After training, we partition the input space into different partitions. In each partition, an input  $x$  corresponds to a unique group  $G$  and a calibration function  $f_{\theta}(x)$ , which results in a calibrated probability  $p(y|x,G)$ . Since there are many different partitions, the groups can be treated as sampled from a distribution  $p(G|x)$ . We ensemble the calibrated probabilities as the final prediction, which is indeed an Monte-Carlo's estimation of  $p(y|x) = \sum_{G}p(y|x,G)p(G|x)$ . This ensemble approach is described in Line 5-11 of Algorithm 1.
Algorithm 1 Train group calibration with temperature scaling (GC+TS)
Input:  $D_{val} = \{Z_{val},O_{val},Y_{val}\}$ $D_{ho} = \{Z_{ho},O_{ho},Y_{ho}\}$ $D_{test} = \{Z_{test},O_{test}\}$ $U,K,\lambda$    
Output: Calibrated  $\hat{Y}_{test}$    
1: for  $u\gets 0$  to  $U - 1$  do   
2: Randomly initialize  $\phi_u$  and  $\theta_{u}$    
3: Optimize  $\phi_u$  and  $\theta_{u}$  on  $D_{val}$  to minimize Eq. (13) with L-BFGS[30]   
4: Optimize  $\theta_{ui}$  on  $D_{ho}$  to minimize Eq. (11) with base calibration method(e.g., TS)   
5: Calculate partition  $P_{u} = \{G_{ui}\}$  with grouping function  $g_{\phi_u}$  on  $D_{test}$    
6: for  $i\gets 0$  to  $K - 1$  do   
7: Calibrate  $G_{ui}$  with  $f_{\theta_{ui}}(\cdot)$  to obtain  $\hat{Y}_{ui}$    
8: end for   
9: Merge predicts in different groups  $\hat{Y}_u = \{\hat{Y}_{ui}\}$    
10: end for   
11: Ensemble predicts in different partitions  $\hat{Y}_{test} = \frac{1}{U}\sum_u\hat{Y}_u$
On the usage of  $D_{val}$  and  $D_{ho}$ . Guo et al. [7] explicitly states that the validation dataset  $D_{val}$  used for early stopping can be used for calibration, while most researchers use a hold-out dataset  $D_{ho}$  that is not used during training for calibration[12, 23, 25]. Experimentally, we found that calibrating with  $D_{val}$  is significantly worse than  $D_{ho}$  for existing calibration methods. Interestingly, the grouping function trained on the  $D_{val}$  can transfer to  $D_{ho}$  for improving performance, which means the training of  $g_{\phi}$  does not require additional data. We investigate this problem in the supplementary in detail.
An essential characteristic of calibration methods is their ability to preserve accuracy[23], ensuring that the classes with the highest probabilities remain unchanged after the calibration process.
Theorem 1 (Accuracy-preserving of group calibration). Group calibration with any group-wise accuracy-preserving base calibration method is also accuracy-preserving.
Proof Sketch. Since the groups are disjoint, group-wise accuracy-preserving remains overall accuracy-preserving. Ensembles of accuracy-preserving predictions are also accuracy-preserving.  $\square$
The Theorem. 1 guarantees our group calibration method remains accuracy-preserving with accuracy-preserving base methods such as temperature scaling[7] or ensemble temperature scaling [23].