maxwoe commited on
Commit
8ede82c
·
verified ·
1 Parent(s): 1118982

Confidence value: predict_angle(image, return_confidence=True)

Browse files
Files changed (3) hide show
  1. README.md +34 -1
  2. config.json +6 -1
  3. model_cgd.py +38 -2
README.md CHANGED
@@ -63,6 +63,9 @@ angle = model.predict_angle(image) # degrees in [0, 360), counter-clockwise
63
  print(f"Predicted rotation: {angle:.1f}°")
64
 
65
  upright = image.rotate(-angle, expand=True) # turn the image back
 
 
 
66
  ```
67
 
68
  - `predict_angle` accepts a PIL Image, a numpy array or a file path.
@@ -90,13 +93,42 @@ The error is nearly the same across JPEG quality settings (3.87° at quality 95,
90
  The checkpoint is one of three training runs of this configuration, which reach 3.70°, 3.77° and 3.81° (mean 3.76°).
91
  The strongest earlier model, OAD-360, reaches 6.09° on the same images.
92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  ## Limitations
94
 
95
  - **Photos only.** The model was trained and tested on everyday photos (COCO). Documents, scans, screenshots, drawings, aerial and medical images were not evaluated.
96
  - **Ambiguous images.** Close-ups, textures and symmetric scenes have no clear "up". More than half of the large errors are confusions by 90° or 180° on such images.
97
  - **Central square.** The image is resized so that its shorter side is 224 pixels and the central 224 x 224 square is used. In a very elongated image the model does not see the ends.
98
  - **Images never saved after rotation.** Rotations that are applied in memory or kept in a lossless format are slightly outside the training distribution, which is why the error is a little higher in the second column above.
99
- - **No confidence value.** `predict_angle` returns an angle only, and the probabilities of the model were not evaluated as a measure of confidence.
100
 
101
  ## Checks for Processing Traces
102
 
@@ -131,6 +163,7 @@ They remain available so that earlier results stay reproducible, and can be load
131
  - **Training data:** COCO 2017 train split without the test images (117,372 images), 10% held out for validation
132
  - **Training images:** rotated by a random angle in [0°, 360°), cropped to the largest rectangle without border, saved as JPEG at a random quality between 40 and 90; the interpolation method of the rotation is drawn at random
133
  - **Optimizer:** AdamW, learning rate reduced on plateau, early stopping
 
134
 
135
  ## Paper and Citation
136
 
 
63
  print(f"Predicted rotation: {angle:.1f}°")
64
 
65
  upright = image.rotate(-angle, expand=True) # turn the image back
66
+
67
+ # optionally with a confidence between 0 and 1, see "Confidence" below
68
+ angle, confidence = model.predict_angle(image, return_confidence=True)
69
  ```
70
 
71
  - `predict_angle` accepts a PIL Image, a numpy array or a file path.
 
93
  The checkpoint is one of three training runs of this configuration, which reach 3.70°, 3.77° and 3.81° (mean 3.76°).
94
  The strongest earlier model, OAD-360, reaches 6.09° on the same images.
95
 
96
+ ## Confidence
97
+
98
+ `predict_angle(image, return_confidence=True)` returns the angle together with a confidence between 0 and 1.
99
+ The confidence estimates the probability that the predicted angle is within 10° of the true angle.
100
+ It is computed from the output of the model: the probability mass within 10° of the predicted angle, mapped to the range from 0 to 1 by a logistic curve with two parameters that were fitted on the validation split.
101
+ A second peak in the distribution, for example at the upside-down angle, lowers it.
102
+
103
+ The model is right on most photos, so most values are close to 1: 84% of the test views get 0.99 or more.
104
+ The confidence is therefore best used with a threshold, below which a prediction is not trusted.
105
+ The table shows the effect on the test views that were saved as JPEG after rotation.
106
+
107
+ | Confidence at least | Views answered | Within 10° among those | Mean absolute error among those |
108
+ |---|---|---|---|
109
+ | 0.50 | 99.0% | 97.9% | 3.30° |
110
+ | 0.90 | 97.3% | 98.5% | 2.91° |
111
+ | 0.95 | 95.9% | 98.7% | 2.63° |
112
+ | 0.98 | 92.4% | 99.3% | 2.13° |
113
+ | 0.99 | 84.1% | 99.6% | 1.76° |
114
+
115
+ On views that were never saved after rotation, the same thresholds answer fewer views: 0.98 answers 86.2% of them, with 98.9% within 10°.
116
+ On noise images that have no orientation at all, the median confidence is 0.09 and at most 3% of them reach 0.9.
117
+
118
+ What the confidence cannot do:
119
+
120
+ - **It is not an exact percentage.** It is reliable at the top and too optimistic in the middle: of the predictions with a confidence between 0.95 and 0.98, 84% are within 10°.
121
+ - **Confident mistakes remain.** Of the 87 test views with an error above 45°, which are mostly confusions by 90° or 180°, 49% have a confidence of at least 0.95 and 30% of at least 0.98.
122
+ - **Fitted on photos.** The curve was fitted and tested on COCO photos, and the values were not evaluated on other kinds of images.
123
+ - **Default checkpoint only.** The legacy checkpoints have no confidence value.
124
+
125
  ## Limitations
126
 
127
  - **Photos only.** The model was trained and tested on everyday photos (COCO). Documents, scans, screenshots, drawings, aerial and medical images were not evaluated.
128
  - **Ambiguous images.** Close-ups, textures and symmetric scenes have no clear "up". More than half of the large errors are confusions by 90° or 180° on such images.
129
  - **Central square.** The image is resized so that its shorter side is 224 pixels and the central 224 x 224 square is used. In a very elongated image the model does not see the ends.
130
  - **Images never saved after rotation.** Rotations that are applied in memory or kept in a lossless format are slightly outside the training distribution, which is why the error is a little higher in the second column above.
131
+ - **Confidence is not a guarantee.** The confidence value flags most wrong predictions, but not all of them (see Confidence).
132
 
133
  ## Checks for Processing Traces
134
 
 
163
  - **Training data:** COCO 2017 train split without the test images (117,372 images), 10% held out for validation
164
  - **Training images:** rotated by a random angle in [0°, 360°), cropped to the largest rectangle without border, saved as JPEG at a random quality between 40 and 90; the interpolation method of the rotation is drawn at random
165
  - **Optimizer:** AdamW, learning rate reduced on plateau, early stopping
166
+ - **Confidence:** probability mass within 10° of the predicted angle, mapped by a logistic curve on its logit (slope 3.010, intercept -1.385) that was fitted on the validation split
167
 
168
  ## Paper and Citation
169
 
config.json CHANGED
@@ -3,7 +3,12 @@
3
  "CGD + ConvNeXt V2 Base (COCO 2017, trace-free protocol)": {
4
  "filename": "cgd_convnextv2_base_coco2017.ckpt",
5
  "architecture": "convnextv2_base.fcmae_ft_in22k_in1k",
6
- "input_size": 224
 
 
 
 
 
7
  },
8
  "Legacy: CGD + MambaOut Base (COCO 2017, conventional protocol)": {
9
  "filename": "cgd_mambaout_base_coco2017.ckpt",
 
3
  "CGD + ConvNeXt V2 Base (COCO 2017, trace-free protocol)": {
4
  "filename": "cgd_convnextv2_base_coco2017.ckpt",
5
  "architecture": "convnextv2_base.fcmae_ft_in22k_in1k",
6
+ "input_size": 224,
7
+ "confidence": {
8
+ "window_degrees": 10,
9
+ "slope": 3.0100,
10
+ "intercept": -1.3845
11
+ }
12
  },
13
  "Legacy: CGD + MambaOut Base (COCO 2017, conventional protocol)": {
14
  "filename": "cgd_mambaout_base_coco2017.ckpt",
model_cgd.py CHANGED
@@ -90,6 +90,17 @@ class CircularGaussianDistribution(nn.Module):
90
  max_entropy = math.log(self.num_bins)
91
  return entropy / max_entropy
92
 
 
 
 
 
 
 
 
 
 
 
 
93
 
94
  class CGDAngleEstimation(pl.LightningModule):
95
  """CGD model for 360 degree image orientation estimation (inference only)."""
@@ -131,6 +142,10 @@ class CGDAngleEstimation(pl.LightningModule):
131
  self.model = timm.create_model(model_name, pretrained=False, num_classes=num_bins)
132
  self.cgd = CircularGaussianDistribution(num_bins=num_bins, sigma=sigma)
133
 
 
 
 
 
134
  @classmethod
135
  def try_load(cls, checkpoint_path=None, **kwargs):
136
  """Load model from checkpoint."""
@@ -175,6 +190,7 @@ class CGDAngleEstimation(pl.LightningModule):
175
 
176
  ckpt_path = hf_hub_download(repo_id=repo_id, filename=model_info["filename"])
177
  model = cls.try_load(checkpoint_path=ckpt_path, image_size=model_info["input_size"])
 
178
  model.eval()
179
  return model
180
 
@@ -185,15 +201,33 @@ class CGDAngleEstimation(pl.LightningModule):
185
  return logits
186
  return F.softmax(logits, dim=1)
187
 
188
- def predict_angle(self, image) -> float:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
189
  """Detect the current orientation angle of an image.
190
 
191
  Args:
192
  image: PIL Image, numpy array, or file path string.
193
  For best results, pass PIL Image or numpy array directly.
 
194
 
195
  Returns:
196
- Predicted rotation angle in degrees [0, 360).
 
197
  """
198
  self.eval()
199
 
@@ -223,5 +257,7 @@ class CGDAngleEstimation(pl.LightningModule):
223
  with torch.no_grad():
224
  pred_distributions = self(image_tensor)
225
  angle = self.cgd.distribution_to_angle(pred_distributions, method=self.inference_method).item()
 
 
226
 
227
  return angle
 
90
  max_entropy = math.log(self.num_bins)
91
  return entropy / max_entropy
92
 
93
+ def peak_mass(self, distributions: torch.Tensor, window_degrees: float = 10.0) -> torch.Tensor:
94
+ """Probability mass within +-window_degrees of the most probable angle (circular).
95
+
96
+ The raw score behind the confidence value. A second peak elsewhere, or a flat
97
+ distribution, lowers it.
98
+ """
99
+ half_width = int(round(window_degrees / self.bin_size))
100
+ peak_indices = torch.argmax(distributions, dim=1, keepdim=True)
101
+ offsets = torch.arange(-half_width, half_width + 1, device=distributions.device)
102
+ return distributions.gather(1, (peak_indices + offsets) % self.num_bins).sum(dim=1)
103
+
104
 
105
  class CGDAngleEstimation(pl.LightningModule):
106
  """CGD model for 360 degree image orientation estimation (inference only)."""
 
142
  self.model = timm.create_model(model_name, pretrained=False, num_classes=num_bins)
143
  self.cgd = CircularGaussianDistribution(num_bins=num_bins, sigma=sigma)
144
 
145
+ # {"window_degrees", "slope", "intercept"} of the checkpoint, set by from_pretrained
146
+ # from config.json; None for a checkpoint whose confidence was not calibrated
147
+ self.confidence_calibration = None
148
+
149
  @classmethod
150
  def try_load(cls, checkpoint_path=None, **kwargs):
151
  """Load model from checkpoint."""
 
190
 
191
  ckpt_path = hf_hub_download(repo_id=repo_id, filename=model_info["filename"])
192
  model = cls.try_load(checkpoint_path=ckpt_path, image_size=model_info["input_size"])
193
+ model.confidence_calibration = model_info.get("confidence")
194
  model.eval()
195
  return model
196
 
 
201
  return logits
202
  return F.softmax(logits, dim=1)
203
 
204
+ def confidence_from_distribution(self, distributions: torch.Tensor) -> torch.Tensor:
205
+ """Confidence between 0 and 1 for each distribution of a batch.
206
+
207
+ The probability mass within +-10 degrees of the predicted angle cannot exceed
208
+ about 0.92, because the model is trained on Gaussian targets with sigma = 6 degrees.
209
+ A logistic curve fitted on the validation split maps it to an estimate of the
210
+ probability that the predicted angle is within 10 degrees of the true angle.
211
+ """
212
+ calibration = self.confidence_calibration
213
+ if calibration is None:
214
+ raise ValueError("The confidence of this checkpoint was not calibrated. "
215
+ "It is available for checkpoints with a 'confidence' entry in config.json.")
216
+ mass = self.cgd.peak_mass(distributions, window_degrees=calibration["window_degrees"])
217
+ mass = mass.double().clamp(1e-6, 1 - 1e-6)
218
+ return torch.sigmoid(calibration["slope"] * torch.logit(mass) + calibration["intercept"])
219
+
220
+ def predict_angle(self, image, return_confidence: bool = False):
221
  """Detect the current orientation angle of an image.
222
 
223
  Args:
224
  image: PIL Image, numpy array, or file path string.
225
  For best results, pass PIL Image or numpy array directly.
226
+ return_confidence: Also return the confidence of the prediction.
227
 
228
  Returns:
229
+ Predicted rotation angle in degrees [0, 360), or the tuple (angle, confidence)
230
+ with a confidence between 0 and 1 if return_confidence is set.
231
  """
232
  self.eval()
233
 
 
257
  with torch.no_grad():
258
  pred_distributions = self(image_tensor)
259
  angle = self.cgd.distribution_to_angle(pred_distributions, method=self.inference_method).item()
260
+ if return_confidence:
261
+ return angle, self.confidence_from_distribution(pred_distributions).item()
262
 
263
  return angle