zhurong2333 commited on
Commit
a3ade38
·
verified ·
1 Parent(s): b326280

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. AAAI2025-FC/.gitignore +14 -0
  2. AAAI2025-FC/README.md +30 -0
  3. AAAI2025-FC/calibration/__init__.py +1 -0
  4. AAAI2025-FC/calibration/feature_clipping.py +66 -0
  5. AAAI2025-FC/calibration/group_calibration/__init__.py +0 -0
  6. AAAI2025-FC/calibration/group_calibration/conf/main.yaml +3 -0
  7. AAAI2025-FC/calibration/group_calibration/conf/method/ets.yaml +2 -0
  8. AAAI2025-FC/calibration/group_calibration/conf/method/group_calibration_combine_ets.yaml +16 -0
  9. AAAI2025-FC/calibration/group_calibration/conf/method/group_calibration_combine_ts.yaml +16 -0
  10. AAAI2025-FC/calibration/group_calibration/conf/method/histogram_binning.yaml +2 -0
  11. AAAI2025-FC/calibration/group_calibration/conf/method/isotonic_regression.yaml +2 -0
  12. AAAI2025-FC/calibration/group_calibration/conf/method/none.yaml +1 -0
  13. AAAI2025-FC/calibration/group_calibration/conf/method/temp_scaling.yaml +2 -0
  14. AAAI2025-FC/calibration/group_calibration/data.py +34 -0
  15. AAAI2025-FC/calibration/group_calibration/evaluate.py +28 -0
  16. AAAI2025-FC/calibration/group_calibration/main.py +52 -0
  17. AAAI2025-FC/calibration/group_calibration/methods/__init__.py +68 -0
  18. AAAI2025-FC/calibration/group_calibration/methods/group_calibration.py +212 -0
  19. AAAI2025-FC/calibration/group_calibration/methods/mix_calibration.py +190 -0
  20. AAAI2025-FC/calibration/group_calibration/methods/nn_calibration.py +435 -0
  21. AAAI2025-FC/calibration/group_calibration/methods/temp_scaling.py +36 -0
  22. AAAI2025-FC/calibration/group_calibration/utils.py +95 -0
  23. AAAI2025-FC/calibration/pts_cts_ets/__init__.py +74 -0
  24. AAAI2025-FC/calibration/pts_cts_ets/dataloader.py +19 -0
  25. AAAI2025-FC/calibration/pts_cts_ets/lossfunction.py +112 -0
  26. AAAI2025-FC/calibration/pts_cts_ets/optimizer.py +25 -0
  27. AAAI2025-FC/calibration/pts_cts_ets/option.py +32 -0
  28. AAAI2025-FC/calibration/pts_cts_ets/scaler.py +61 -0
  29. AAAI2025-FC/calibration/pts_cts_ets/utils.py +150 -0
  30. AAAI2025-FC/calibration/temperature_scaling.py +112 -0
  31. AAAI2025-FC/dataset/__init__.py +0 -0
  32. AAAI2025-FC/dataset/cifar10.py +165 -0
  33. AAAI2025-FC/dataset/cifar100.py +165 -0
  34. AAAI2025-FC/dataset/svhn.py +142 -0
  35. AAAI2025-FC/environment.yml +514 -0
  36. AAAI2025-FC/evaluate.py +622 -0
  37. AAAI2025-FC/evaluate_scripts_post_hoc.sh +18 -0
  38. AAAI2025-FC/evaluate_scripts_train_time.sh +63 -0
  39. AAAI2025-FC/losses/brier_score.py +27 -0
  40. AAAI2025-FC/losses/focal_loss.py +32 -0
  41. AAAI2025-FC/losses/focal_loss_adaptive_gamma.py +68 -0
  42. AAAI2025-FC/losses/loss.py +43 -0
  43. AAAI2025-FC/losses/mmce.py +140 -0
  44. AAAI2025-FC/metrics/.gitignore +1 -0
  45. AAAI2025-FC/metrics/__init__.py +0 -0
  46. AAAI2025-FC/metrics/metrics.py +291 -0
  47. AAAI2025-FC/metrics/ood_test_utils.py +76 -0
  48. AAAI2025-FC/metrics/plots.py +94 -0
  49. AAAI2025-FC/models/__init__.py +0 -0
  50. AAAI2025-FC/models/densenet.py +117 -0
AAAI2025-FC/.gitignore ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ data
2
+ __pycache__
3
+ .vscode
4
+ *.model
5
+ wandb/
6
+ output/
7
+ pretrained_weights/
8
+ *.pkl
9
+ *.pyc
10
+ playground/
11
+ *.pth
12
+ pre_calculated_logits/
13
+ output/
14
+ paper-figure
AAAI2025-FC/README.md ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Feature Clipping
2
+ ### Pretrained models
3
+
4
+ All logits and features and extracted from the following models:
5
+
6
+ - CIFAR10 (from [focal loss calibration](https://github.com/torrvision/focal_calibration?tab=readme-ov-file))
7
+ - [Resnet-50](https://www.robots.ox.ac.uk/~viveka/focal_calibration/CIFAR10/resnet50_cross_entropy_350.model)
8
+ - [Resnet-110](https://www.robots.ox.ac.uk/~viveka/focal_calibration/CIFAR10/resnet110_cross_entropy_350.model)
9
+ - [DenseNet-121](https://www.robots.ox.ac.uk/~viveka/focal_calibration/CIFAR10/densenet121_cross_entropy_350.model)
10
+ - CIFAR100 (from [focal loss calibration](https://github.com/torrvision/focal_calibration?tab=readme-ov-file))
11
+ - [Resnet-50](https://www.robots.ox.ac.uk/~viveka/focal_calibration/CIFAR100/resnet50_cross_entropy_350.model)
12
+ - [Resnet-110](https://www.robots.ox.ac.uk/~viveka/focal_calibration/CIFAR100/resnet110_cross_entropy_350.model)
13
+ - [DenseNet-121](https://www.robots.ox.ac.uk/~viveka/focal_calibration/CIFAR100/densenet121_cross_entropy_350.model)
14
+ - IMAGENET (from [pytorch's torchvision.models](https://pytorch.org/vision/main/models.html))
15
+ - Resnet-50: torchvision.models.resnet50(weights=torchvision.models.ResNet50_Weights.IMAGENET1K_V1)
16
+ - DenseNet-121: torchvision.models.densenet121(weights=torchvision.models.DenseNet121_Weights.IMAGENET1K_V1)
17
+ - Wide-Resnet-50: torchvision.models.wide_resnet50_2(weights=torchvision.models.Wide_ResNet50_2_Weights.IMAGENET1K_V1)
18
+ - MobileNet-V2: torchvision.models.mobilenet_v2(weights=torchvision.models.MobileNet_V2_Weights.IMAGENET1K_V1)
19
+ - ViT-L-16: torchvision.models.vit_l_16(weights=torchvision.models.ViT_L_16_Weights.IMAGENET1K_V1)
20
+
21
+ ### Dependencies
22
+ `conda create -n feature-clipping python=3.10`
23
+
24
+ `python -m pip install -r requirements.txt`
25
+
26
+ ### Evalutation
27
+
28
+ run `bash evaluate_scripts_post_hoc.sh` to evaluate post hoc methods
29
+
30
+ run `bash evaluate_scripts_train-time.sh` to evaluate train time methods
AAAI2025-FC/calibration/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from . import *
AAAI2025-FC/calibration/feature_clipping.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ Code to perform feature clipping. Adapted from https://github.com/gpleiss/temperature_scaling
3
+ '''
4
+ import torch
5
+ import numpy as np
6
+ from torch import nn, optim
7
+ from torch.nn import functional as F
8
+
9
+ from metrics.metrics import ECELoss
10
+
11
+ # implemented as a post hoc calibrator
12
+ class FeatureClippingCalibrator(nn.Module):
13
+ def __init__(self, model, cross_validate='ece'):
14
+ super(FeatureClippingCalibrator, self).__init__()
15
+ self.cross_validate = cross_validate
16
+ self.feature_clip = float("inf")
17
+ self.ece_criterion = ECELoss().cuda()
18
+ self.nll_criterion = nn.CrossEntropyLoss().cuda()
19
+ self.model = model
20
+ self.classifier = self.model.classifier
21
+
22
+ def get_feature_clip(self):
23
+ return self.feature_clip
24
+
25
+ def set_feature_clip(self, features_val, logits_val, labels_val):
26
+ nll_val_opt = float("inf")
27
+ ece_val_opt = float("inf")
28
+ C_opt_nll = float("inf")
29
+ C_opt_ece = float("inf")
30
+ self.feature_clip = float("inf")
31
+
32
+ before_clipping_acc = (F.softmax(logits_val, dim=1).argmax(dim=1) == labels_val).float().mean().item()
33
+
34
+ C = 0.01
35
+ for _ in range(2000):
36
+ logits_after_clipping = self.classifier(self.feature_clipping(features_val, C))
37
+ after_clipping_nll = self.nll_criterion(logits_after_clipping, labels_val).item()
38
+ after_clipping_ece = self.ece_criterion(logits_after_clipping, labels_val).item()
39
+ after_clipping_acc = (F.softmax(logits_after_clipping, dim=1).argmax(dim=1) == labels_val).float().mean().item()
40
+ if (after_clipping_nll < nll_val_opt) and (after_clipping_acc > before_clipping_acc*0.99):
41
+ C_opt_nll = C
42
+ nll_val_opt = after_clipping_nll
43
+
44
+ if (after_clipping_ece < ece_val_opt) and (after_clipping_acc > before_clipping_acc*0.99):
45
+ C_opt_ece = C
46
+ ece_val_opt = after_clipping_ece
47
+
48
+ C += 0.01
49
+
50
+ if self.cross_validate == 'ece':
51
+ self.feature_clip = C_opt_ece
52
+ elif self.cross_validate == 'nll':
53
+ self.feature_clip = C_opt_nll
54
+
55
+ return self.feature_clip
56
+
57
+ def feature_clipping(self, features, c=None):
58
+ """
59
+ Perform feature clipping on logits
60
+ """
61
+
62
+ return torch.clamp(features, min=-c, max=c)
63
+
64
+
65
+ def forward(self, features, c=None):
66
+ return self.classifier(self.feature_clipping(features, c))
AAAI2025-FC/calibration/group_calibration/__init__.py ADDED
File without changes
AAAI2025-FC/calibration/group_calibration/conf/main.yaml ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ data: ???
2
+ method: ???
3
+ seeds: [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99]
AAAI2025-FC/calibration/group_calibration/conf/method/ets.yaml ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ name: ets
2
+ train_set: test_train
AAAI2025-FC/calibration/group_calibration/conf/method/group_calibration_combine_ets.yaml ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: group_calibration_combine_ets
2
+ num_groups: 2
3
+ num_partitions: 20
4
+ train_set: test_train
5
+
6
+ w_net:
7
+ model: linear
8
+ weight_decay: 1e-1
9
+
10
+ optimizer:
11
+ name: lbfgs
12
+ lr: 1e-3
13
+ steps: 100
14
+
15
+ base_calibrator:
16
+ name: ets
AAAI2025-FC/calibration/group_calibration/conf/method/group_calibration_combine_ts.yaml ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: group_calibration_combine_ts
2
+ num_groups: 2
3
+ num_partitions: 20
4
+ train_set: test_train
5
+
6
+ w_net:
7
+ model: linear
8
+ weight_decay: 1e-1
9
+
10
+ optimizer:
11
+ name: lbfgs
12
+ lr: 1e-3
13
+ steps: 100
14
+
15
+ base_calibrator:
16
+ name: temp_scaling
AAAI2025-FC/calibration/group_calibration/conf/method/histogram_binning.yaml ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ name: histogram_binning
2
+ train_set: test_train
AAAI2025-FC/calibration/group_calibration/conf/method/isotonic_regression.yaml ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ name: isotonic_regression
2
+ train_set: test_train
AAAI2025-FC/calibration/group_calibration/conf/method/none.yaml ADDED
@@ -0,0 +1 @@
 
 
1
+ name: none
AAAI2025-FC/calibration/group_calibration/conf/method/temp_scaling.yaml ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ name: temp_scaling
2
+ train_set: test_train
AAAI2025-FC/calibration/group_calibration/data.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import pickle
3
+ import logging
4
+
5
+ from utils import RandomSplitter
6
+
7
+ def load_data(data_config,
8
+ test_splits=(0.1, 0.9),
9
+ seed=None):
10
+ with open(data_config.val_path, "rb") as f:
11
+ val_data = pickle.load(f)
12
+
13
+ with open(data_config.test_path, "rb") as f:
14
+ test_data = pickle.load(f)
15
+
16
+ val_acc = (torch.argmax(val_data["logits"], dim=1)
17
+ == val_data["labels"]).float().mean().item()
18
+ test_acc = (torch.argmax(test_data["logits"], dim=1)
19
+ == test_data["labels"]).float().mean().item()
20
+ logging.info("Dataset: val_acc: {:.4f}, test_acc: {:.4f}".format(val_acc, test_acc))
21
+
22
+ test_splitter = RandomSplitter(splits=test_splits,
23
+ num=test_data["logits"].shape[0],
24
+ seed=seed)
25
+ test_train_data, test_test_data = {}, {}
26
+ test_train_data["logits"], test_test_data["logits"] = test_splitter.split(
27
+ test_data["logits"])
28
+ test_train_data["labels"], test_test_data["labels"] = test_splitter.split(
29
+ test_data["labels"]
30
+ )
31
+ test_train_data["features"], test_test_data["features"] = test_splitter.split(
32
+ test_data["features"]
33
+ )
34
+ return val_data, test_train_data, test_test_data
AAAI2025-FC/calibration/group_calibration/evaluate.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ import torch.nn.functional as F
4
+ import torchmetrics.functional as tmF
5
+
6
+ def evaluate(y, num_classes, n_bins=15, pred_prob=None, pred_logits=None):
7
+ if pred_logits is not None:
8
+ pred_logits = pred_logits.contiguous()
9
+ if pred_prob is None:
10
+ pred_prob = torch.softmax(pred_logits, dim=1)
11
+ ece_multiclass = tmF.calibration_error(pred_prob,
12
+ y,
13
+ task="multiclass",
14
+ n_bins=n_bins,
15
+ num_classes=num_classes)
16
+ if pred_logits is not None:
17
+ nll = F.cross_entropy(pred_logits, y).item()
18
+ else:
19
+ nll = -torch.mean(torch.sum(torch.log(pred_prob + 1e-10)
20
+ * F.one_hot(y, num_classes=num_classes), dim=1)).item()
21
+ pred_labels = torch.argmax(pred_prob, dim=1)
22
+ acc = (pred_labels == y).float().mean().item()
23
+ results = {
24
+ "ece_m": ece_multiclass.item(),
25
+ "nll": nll,
26
+ "acc": acc,
27
+ }
28
+ return results
AAAI2025-FC/calibration/group_calibration/main.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hydra
2
+ from omegaconf import DictConfig, OmegaConf
3
+ import logging
4
+ import time
5
+
6
+ from data import load_data
7
+ from utils import set_seed, gather_metrics
8
+ from methods import calibrate
9
+ from evaluate import evaluate
10
+
11
+ def _main(cfg):
12
+ logging.info("config: {}\n===========\n".format(OmegaConf.to_yaml(cfg)))
13
+ seeds = cfg.seeds
14
+
15
+ start_time = time.time()
16
+ metrics = []
17
+ for seed in seeds:
18
+ logging.info("Running seed: {}".format(seed))
19
+
20
+
21
+ val_data, test_train_data, test_test_data = load_data(data_config=cfg.data,
22
+ seed=seed)
23
+ set_seed(seed)
24
+
25
+ calibrated_test_test = calibrate(method_config=cfg.method,
26
+ val_data=val_data,
27
+ test_train_data=test_train_data,
28
+ test_test_data=test_test_data,
29
+ seed=seed,
30
+ cfg=cfg)
31
+
32
+ _metrics = evaluate(y=test_test_data["labels"],
33
+ num_classes=test_test_data["logits"].shape[1],
34
+ n_bins=15,
35
+ pred_logits=calibrated_test_test.get(
36
+ "logits", None),
37
+ pred_prob=calibrated_test_test.get("prob", None)
38
+ )
39
+ logging.info("Metrics: {}".format(_metrics))
40
+ _results = (seed, _metrics)
41
+
42
+ metrics.append(_results)
43
+ metric_stats, metrics = gather_metrics(metrics)
44
+ logging.info("Metrics stats: {}".format(metric_stats))
45
+
46
+
47
+ @hydra.main(version_base=None, config_path="conf", config_name="main")
48
+ def main(cfg: DictConfig) -> None:
49
+ _main(cfg)
50
+
51
+ if __name__ == "__main__":
52
+ main()
AAAI2025-FC/calibration/group_calibration/methods/__init__.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+
3
+ import torch
4
+ import calibration.group_calibration.methods.temp_scaling as temp_scaling
5
+ import calibration.group_calibration.methods.group_calibration as group_calibration
6
+ import calibration.group_calibration.methods.nn_calibration as nn_calibration
7
+ import calibration.group_calibration.methods.mix_calibration as mix_calibration
8
+
9
+
10
+ def get_calibrate_fn(method_config):
11
+ if method_config.name in ["temp_scaling"]:
12
+ return temp_scaling.calibrate
13
+ elif method_config.name in ["histogram_binning",
14
+ "isotonic_regression"]:
15
+ return nn_calibration.calibrate
16
+ elif method_config.name in ["ets"]:
17
+ return mix_calibration.calibrate
18
+ else:
19
+ raise ValueError("config_name {} not found".format(method_config.name))
20
+
21
+
22
+ def calibrate(method_config,
23
+ val_data,
24
+ test_train_data,
25
+ test_test_data,
26
+ seed,
27
+ cfg):
28
+ if method_config.name == "none":
29
+ return {
30
+ "logits": test_test_data["logits"]
31
+ }
32
+
33
+ train_set = method_config.get("train_set", "test_train")
34
+ if train_set == "val":
35
+ train_logits = val_data["logits"]
36
+ train_labels = val_data["labels"]
37
+ elif train_set == "test_train":
38
+ train_logits = test_train_data["logits"]
39
+ train_labels = test_train_data["labels"]
40
+ else:
41
+ assert train_set == "val+test_train"
42
+ train_logits = torch.cat(
43
+ [val_data["logits"], test_train_data["logits"]], dim=0)
44
+ train_labels = torch.cat(
45
+ [val_data["labels"], test_train_data["labels"]], dim=0)
46
+
47
+ test_test_logits = test_test_data["logits"]
48
+
49
+ if "group_calibration_combine" in method_config.name:
50
+ return group_calibration.calibrate_combine(val_features=val_data["features"],
51
+ val_logits=val_data["logits"],
52
+ val_labels=val_data["labels"],
53
+ test_train_features=test_train_data["features"],
54
+ test_train_logits=test_train_data["logits"],
55
+ test_train_labels=test_train_data["labels"],
56
+ test_test_features=test_test_data["features"],
57
+ test_test_logits=test_test_data["logits"],
58
+ base_calibrate_fn=get_calibrate_fn(
59
+ method_config=method_config.base_calibrator),
60
+ method_config=method_config,
61
+ seed=seed,
62
+ cfg=cfg)
63
+ else:
64
+ calibrate_fn = get_calibrate_fn(method_config=method_config)
65
+ return calibrate_fn(method_name=method_config.name,
66
+ train_logits=train_logits,
67
+ train_labels=train_labels,
68
+ test_logits=test_test_logits)
AAAI2025-FC/calibration/group_calibration/methods/group_calibration.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+
4
+ from tqdm import tqdm
5
+
6
+ class WNet(torch.nn.Module):
7
+
8
+ def __init__(self, feature_dim, num_groups):
9
+ super().__init__()
10
+ self.feature_dim = feature_dim
11
+ self.num_groups = num_groups
12
+
13
+ self.model = torch.nn.Sequential(
14
+ torch.nn.Linear(feature_dim, num_groups, bias=False),
15
+ ).cuda()
16
+
17
+ def forward(self, x):
18
+ x = self.model(x)
19
+ return x
20
+
21
+
22
+ def calibrate_with_tau_and_w_logits(logits,
23
+ features,
24
+ tau,
25
+ hard,
26
+ w_net=None,
27
+ w_logits=None):
28
+ assert (w_logits is not None) != (w_net is not None)
29
+
30
+
31
+ N, num_classes = logits.shape
32
+ if hard:
33
+ num_groups = w_net.num_groups
34
+ group_log_softmax = torch.log_softmax(
35
+ w_net(features), dim=1)
36
+ group_argmax = torch.argmax(group_log_softmax, dim=1)
37
+ group_hard_prob = F.one_hot(
38
+ group_argmax, num_classes=num_groups).view((N, num_groups, 1))
39
+ group_hard_prob = group_hard_prob.expand((N, num_groups, num_classes))
40
+
41
+ temp_logits = logits.view((N, 1, num_classes)) / \
42
+ tau.view((1, num_groups, 1))
43
+ temp_log_softmax = torch.log_softmax(temp_logits, dim=2)
44
+ calibrated_logits = torch.sum(
45
+ temp_log_softmax * group_hard_prob, dim=1)
46
+ return calibrated_logits
47
+ else:
48
+
49
+ if w_logits is not None:
50
+ num_groups = w_logits.shape[1]
51
+ group_log_softmax = torch.log_softmax(
52
+ w_logits, dim=1).view((N, num_groups, 1))
53
+ else:
54
+ num_groups = w_net.num_groups
55
+ group_log_softmax = torch.log_softmax(
56
+ w_net(features), dim=1).view((N, num_groups, 1))
57
+
58
+ group_log_softmax = group_log_softmax.expand(
59
+ (N, num_groups, num_classes))
60
+ temp_logits = logits.view((N, 1, num_classes)) / \
61
+ tau.view((1, num_groups, 1))
62
+ temp_log_softmax = torch.log_softmax(temp_logits, dim=2)
63
+ calibrated_logits = torch.logsumexp(group_log_softmax +
64
+ temp_log_softmax, dim=1)
65
+ return calibrated_logits
66
+
67
+
68
+ def optimize_group_fn(
69
+ features,
70
+ logits,
71
+ labels,
72
+ w_net,
73
+ hard_group,
74
+ method_config):
75
+
76
+ if isinstance(w_net, str):
77
+ train_w = True
78
+ assert isinstance(method_config.num_groups, int)
79
+ w_net = WNet(feature_dim=features.shape[1],
80
+ num_groups=method_config.num_groups)
81
+ else:
82
+ train_w = False
83
+ assert isinstance(w_net, torch.nn.Module)
84
+
85
+ tau = torch.nn.Parameter(torch.tensor(
86
+ [1.5] * method_config.num_groups,
87
+ requires_grad=True, device=features.device))
88
+
89
+ if train_w:
90
+ params = [tau] + list(w_net.parameters())
91
+ else:
92
+ params = [tau]
93
+
94
+ if method_config.optimizer.name == "lbfgs" or not train_w:
95
+ optimizer = torch.optim.LBFGS(params,
96
+ line_search_fn="strong_wolfe",
97
+ max_iter=method_config.optimizer.steps)
98
+ else:
99
+ raise ValueError(method_config.optimizer)
100
+
101
+ W_gpu = w_net.to(features.device)
102
+
103
+ def closure():
104
+ optimizer.zero_grad()
105
+
106
+ # Calculate weight decay loss
107
+ reg_weight_decay = 0
108
+ for name, param in W_gpu.named_parameters():
109
+ if "weight" in name:
110
+ reg_weight_decay += torch.mean((param)**2)
111
+ reg_weight_decay_loss = reg_weight_decay * method_config.w_net.weight_decay
112
+
113
+ # Calculate NLL loss
114
+ calibrated_logits = calibrate_with_tau_and_w_logits(
115
+ logits=logits,
116
+ features=features,
117
+ tau=tau,
118
+ w_net=W_gpu,
119
+ hard=hard_group
120
+ )
121
+
122
+ main_loss = F.cross_entropy(calibrated_logits, labels)
123
+
124
+ # Gather all loss
125
+ _loss = main_loss + reg_weight_decay_loss
126
+
127
+ _loss.backward()
128
+ return _loss
129
+
130
+ optimizer.step(closure=closure)
131
+
132
+ return tau.detach().cpu(), w_net.cpu()
133
+
134
+
135
+ def train_partitions(features,
136
+ logits,
137
+ labels,
138
+ w_net,
139
+ method_config):
140
+ w_net_list = []
141
+ # print("Generating partitions...")
142
+ for partition_i in range(method_config.num_partitions):
143
+ trained_tau, trained_w_net = optimize_group_fn(features.to("cuda:0"),
144
+ logits.to("cuda:0"),
145
+ labels.to("cuda:0"),
146
+ hard_group=False,
147
+ w_net=w_net,
148
+ method_config=method_config)
149
+ w_net_list.append(trained_w_net)
150
+ return w_net_list
151
+
152
+
153
+ def calibrate_combine(val_features,
154
+ val_logits,
155
+ val_labels,
156
+ test_train_features,
157
+ test_train_logits,
158
+ test_train_labels,
159
+ test_test_features,
160
+ test_test_logits,
161
+ method_config,
162
+ base_calibrate_fn,
163
+ seed,
164
+ cfg,
165
+ *args, **kwargs):
166
+
167
+ w_net_list = train_partitions(val_features,
168
+ val_logits,
169
+ val_labels,
170
+ w_net=method_config.w_net.model,
171
+ method_config=method_config)
172
+
173
+ calibrated_probs = []
174
+ # print("Calibrating with partitions...")
175
+ for trained_w_net in w_net_list:
176
+
177
+ train_group_logits = trained_w_net(test_train_features)
178
+ test_group_logits = trained_w_net(test_test_features)
179
+ # Hard group
180
+ train_groups_id = torch.argmax(
181
+ train_group_logits, dim=1)
182
+ test_groups_id = torch.argmax(
183
+ test_group_logits, dim=1)
184
+
185
+ _calibrated_probs = torch.zeros_like(test_test_logits)
186
+ for _g in range(method_config.num_groups):
187
+ train_group_mask = train_groups_id == _g
188
+ test_group_mask = test_groups_id == _g
189
+ group_train_logits = test_train_logits[train_group_mask]
190
+ group_train_labels = test_train_labels[train_group_mask]
191
+
192
+ group_test_logits = test_test_logits[test_group_mask]
193
+
194
+ _group_calibrated_results = base_calibrate_fn(
195
+ method_name=method_config.base_calibrator.name,
196
+ train_logits=group_train_logits,
197
+ train_labels=group_train_labels,
198
+ test_logits=group_test_logits
199
+ )
200
+ if "prob" in _group_calibrated_results:
201
+ _group_calibrated_prob = _group_calibrated_results["prob"]
202
+ else:
203
+ _group_calibrated_prob = torch.softmax(_group_calibrated_results["logits"],
204
+ dim=1)
205
+ _calibrated_probs[test_group_mask] = _group_calibrated_prob
206
+
207
+ calibrated_probs.append(_calibrated_probs.detach())
208
+ calibrated_probs = torch.stack(calibrated_probs, dim=0).mean(0)
209
+
210
+ return {
211
+ "prob": calibrated_probs
212
+ }
AAAI2025-FC/calibration/group_calibration/methods/mix_calibration.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ from scipy import optimize
4
+ from sklearn.isotonic import IsotonicRegression
5
+ from scipy.special import softmax
6
+
7
+ """
8
+ auxiliary functions for optimizing the temperature (scaling approaches) and weights of ensembles
9
+ *args include logits and labels from the calibration dataset:
10
+ """
11
+ # Adapted from https://github.com/zhang64-llnl/Mix-n-Match-Calibration/blob/master/util_calibration.py
12
+
13
+
14
+ def mse_t(t, *args):
15
+ # find optimal temperature with MSE loss function
16
+
17
+ logit, label = args
18
+ logit = logit/t
19
+
20
+ n = np.sum(np.exp(logit), 1)
21
+ p = np.exp(logit)/n[:, None]
22
+ mse = np.mean((p-label)**2)
23
+ return mse
24
+
25
+
26
+ def ll_t(t, *args):
27
+ # find optimal temperature with Cross-Entropy loss function
28
+
29
+ logit, label = args
30
+ logit = logit/t
31
+ n = np.sum(np.exp(logit), 1)
32
+ p = np.clip(np.exp(logit)/n[:, None], 1e-20, 1-1e-20)
33
+ N = p.shape[0]
34
+ ce = -np.sum(label*np.log(p))/N
35
+ return ce
36
+
37
+
38
+ def mse_w(w, *args):
39
+ # find optimal weight coefficients with MSE loss function
40
+
41
+ p0, p1, p2, label = args
42
+ p = w[0]*p0+w[1]*p1+w[2]*p2
43
+ p = p/np.sum(p, 1)[:, None]
44
+ mse = np.mean((p-label)**2)
45
+ return mse
46
+
47
+
48
+ def ll_w(w, *args):
49
+ # find optimal weight coefficients with Cros-Entropy loss function
50
+
51
+ p0, p1, p2, label = args
52
+ p = (w[0]*p0+w[1]*p1+w[2]*p2)
53
+ N = p.shape[0]
54
+ ce = -np.sum(label*np.log(p))/N
55
+ return ce
56
+
57
+
58
+ # Ftting Temperature Scaling
59
+ def temperature_scaling(logit, label, loss):
60
+ bnds = ((0.05, 5.0),)
61
+ if loss == 'ce':
62
+ t = optimize.minimize(ll_t, 1.0, args=(
63
+ logit, label), method='L-BFGS-B', bounds=bnds, tol=1e-12,
64
+ options={"disp": False})
65
+ if loss == 'mse':
66
+ t = optimize.minimize(mse_t, 1.0, args=(
67
+ logit, label), method='L-BFGS-B', bounds=bnds, tol=1e-12,
68
+ options={"disp": False}
69
+ )
70
+ t = t.x
71
+ return t
72
+
73
+
74
+ # Ftting Enseble Temperature Scaling
75
+ def ensemble_scaling(logit, label, loss, t, n_class):
76
+
77
+ p1 = np.exp(logit)/np.sum(np.exp(logit), 1)[:, None]
78
+ logit = logit/t
79
+ p0 = np.exp(logit)/np.sum(np.exp(logit), 1)[:, None]
80
+ p2 = np.ones_like(p0)/n_class
81
+
82
+ bnds_w = ((0.0, 1.0), (0.0, 1.0), (0.0, 1.0),)
83
+ def my_constraint_fun(x): return np.sum(x)-1
84
+ constraints = {"type": "eq", "fun": my_constraint_fun, }
85
+ if loss == 'ce':
86
+ w = optimize.minimize(ll_w, (1.0, 0.0, 0.0), args=(p0, p1, p2, label), method='SLSQP',
87
+ constraints=constraints, bounds=bnds_w, tol=1e-12, options={'disp': False})
88
+ if loss == 'mse':
89
+ w = optimize.minimize(mse_w, (1.0, 0.0, 0.0), args=(p0, p1, p2, label), method='SLSQP',
90
+ constraints=constraints, bounds=bnds_w, tol=1e-12, options={'disp': False})
91
+ w = w.x
92
+ return w
93
+
94
+
95
+ """
96
+ Calibration:
97
+ Input: uncalibrated logits, temperature (and weight)
98
+ Output: calibrated prediction probabilities
99
+ """
100
+
101
+ # Calibration: Temperature Scaling with MSE
102
+
103
+
104
+ def ts_calibrate(logit, label, logit_eval, loss):
105
+ t = temperature_scaling(logit, label, loss)
106
+ # print("temperature = " +str(t))
107
+ logit_eval = logit_eval/t
108
+ p = np.exp(logit_eval)/np.sum(np.exp(logit_eval), 1)[:, None]
109
+ return p
110
+
111
+
112
+ # Calibration: Ensemble Temperature Scaling
113
+ def ets_calibrate(logit, label, logit_eval, n_class, loss="mse"):
114
+ t = temperature_scaling(logit, label, loss=loss) # loss can change to 'ce'
115
+ w = ensemble_scaling(logit, label, 'mse', t, n_class)
116
+
117
+ p1 = np.exp(logit_eval)/np.sum(np.exp(logit_eval), 1)[:, None]
118
+ logit_eval = logit_eval/t
119
+ p0 = np.exp(logit_eval)/np.sum(np.exp(logit_eval), 1)[:, None]
120
+ p2 = np.ones_like(p0)/n_class
121
+ p = w[0]*p0 + w[1]*p1 + w[2]*p2
122
+ return p
123
+
124
+
125
+ # Calibration: Isotonic Regression (Multi-class)
126
+ def mir_calibrate(logit, label, logit_eval, eps):
127
+
128
+ original_pred = np.argmax(logit_eval, axis=1)
129
+
130
+ p = softmax(logit, axis=1)
131
+ p_eval = softmax(logit_eval, axis=1)
132
+ ir = IsotonicRegression(out_of_bounds="clip")
133
+
134
+ y_ = ir.fit_transform(p.flatten(), (label.flatten()))
135
+ yt_ = ir.predict(p_eval.flatten())
136
+
137
+
138
+ p = yt_.reshape(logit_eval.shape) + eps*p_eval
139
+ p = p / np.sum(p, axis=1, keepdims=True)
140
+
141
+ after_pred = np.argmax(p, axis=1)
142
+ noe_mask = after_pred != original_pred
143
+
144
+ diff = np.sum(np.abs(original_pred - after_pred))
145
+ print("diff ", diff)
146
+ return p
147
+
148
+ def irova_calibrate(logit, label, logit_eval):
149
+ p = np.exp(logit)/np.sum(np.exp(logit), 1)[:, None]
150
+ p_eval = np.exp(logit_eval)/np.sum(np.exp(logit_eval), 1)[:, None]
151
+
152
+ for ii in range(p_eval.shape[1]):
153
+ ir = IsotonicRegression(out_of_bounds='clip')
154
+ y_ = ir.fit_transform(p[:, ii], label[:, ii])
155
+ p_eval[:, ii] = ir.predict(p_eval[:, ii])+1e-9*p_eval[:, ii]
156
+ return p_eval
157
+
158
+
159
+ def calibrate(
160
+ method_name,
161
+ train_logits,
162
+ train_labels,
163
+ test_logits,
164
+ *args, **kwargs):
165
+ n_class = train_logits.shape[1]
166
+ train_labels = torch.nn.functional.one_hot(train_labels,
167
+ num_classes=n_class)
168
+ train_logits = train_logits.detach().numpy()
169
+ train_labels = train_labels.numpy()
170
+ test_logits = test_logits.detach().numpy()
171
+
172
+ if "ets" in method_name:
173
+ calibrated_prob = ets_calibrate(logit=train_logits,
174
+ label=train_labels,
175
+ logit_eval=test_logits,
176
+ n_class=n_class)
177
+ elif "irm" in method_name:
178
+ calibrated_prob = mir_calibrate(logit=train_logits,
179
+ label=train_labels,
180
+ logit_eval=test_logits,
181
+ eps=kwargs["eps"])
182
+ elif method_name == "irova":
183
+ calibrated_prob = irova_calibrate(logit=train_logits,
184
+ label=train_labels,
185
+ logit_eval=test_logits)
186
+ else:
187
+ raise ValueError(method_name)
188
+ return {
189
+ "prob": torch.from_numpy(calibrated_prob).float()
190
+ }
AAAI2025-FC/calibration/group_calibration/methods/nn_calibration.py ADDED
@@ -0,0 +1,435 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ from scipy.optimize import minimize
4
+ from sklearn.metrics import log_loss
5
+ import time
6
+ from sklearn.metrics import log_loss, brier_score_loss
7
+ from os.path import join
8
+ from betacal import BetaCalibration
9
+ import sklearn.metrics as metrics
10
+ from sklearn.isotonic import IsotonicRegression
11
+
12
+ # Adapted from open-source code
13
+ # https://github.com/markus93/NN_calibration/blob/master/scripts/calibration/cal_methods.py
14
+ # https://github.com/dirichletcal/experiments_dnn/blob/master/scripts/calibration/cal_methods.py
15
+
16
+ def softmax(x):
17
+ """
18
+ Compute softmax values for each sets of scores in x.
19
+
20
+ Parameters:
21
+ x (numpy.ndarray): array containing m samples with n-dimensions (m,n)
22
+ Returns:
23
+ x_softmax (numpy.ndarray) softmaxed values for initial (m,n) array
24
+ """
25
+ e_x = np.exp(x - np.max(x))
26
+ return e_x / e_x.sum(axis=1, keepdims=1)
27
+
28
+
29
+ class HistogramBinning():
30
+ """
31
+ Histogram Binning as a calibration method. The bins are divided into equal lengths.
32
+
33
+ The class contains two methods:
34
+ - fit(probs, true), that should be used with validation data to train the calibration model.
35
+ - predict(probs), this method is used to calibrate the confidences.
36
+ """
37
+
38
+ def __init__(self, M=15):
39
+ """
40
+ M (int): the number of equal-length bins used
41
+ """
42
+ self.bin_size = 1./M # Calculate bin size
43
+ self.conf = [] # Initiate confidence list
44
+ self.upper_bounds = np.arange(self.bin_size, 1+self.bin_size, self.bin_size) # Set bin bounds for intervals
45
+
46
+
47
+ def _get_conf(self, conf_thresh_lower, conf_thresh_upper, probs, true):
48
+ """
49
+ Inner method to calculate optimal confidence for certain probability range
50
+
51
+ Params:
52
+ - conf_thresh_lower (float): start of the interval (not included)
53
+ - conf_thresh_upper (float): end of the interval (included)
54
+ - probs : list of probabilities.
55
+ - true : list with true labels, where 1 is positive class and 0 is negative).
56
+ """
57
+
58
+ # Filter labels within probability range
59
+ filtered = [x[0] for x in zip(true, probs) if x[1] > conf_thresh_lower and x[1] <= conf_thresh_upper]
60
+ nr_elems = len(filtered) # Number of elements in the list.
61
+
62
+ if nr_elems < 1:
63
+ return 0
64
+ else:
65
+ # In essence the confidence equals to the average accuracy of a bin
66
+ conf = sum(filtered)/nr_elems # Sums positive classes
67
+ return conf
68
+
69
+
70
+ def fit(self, probs, true):
71
+ """
72
+ Fit the calibration model, finding optimal confidences for all the bins.
73
+
74
+ Params:
75
+ probs: probabilities of data
76
+ true: true labels of data
77
+ """
78
+
79
+ conf = []
80
+
81
+ # Got through intervals and add confidence to list
82
+ for conf_thresh in self.upper_bounds:
83
+ temp_conf = self._get_conf((conf_thresh - self.bin_size), conf_thresh, probs = probs, true = true)
84
+ conf.append(temp_conf)
85
+
86
+ self.conf = conf
87
+
88
+
89
+ # Fit based on predicted confidence
90
+ def predict(self, probs):
91
+ """
92
+ Calibrate the confidences
93
+
94
+ Param:
95
+ probs: probabilities of the data (shape [samples, classes])
96
+
97
+ Returns:
98
+ Calibrated probabilities (shape [samples, classes])
99
+ """
100
+
101
+ # Go through all the probs and check what confidence is suitable for it.
102
+ for i, prob in enumerate(probs):
103
+ idx = np.searchsorted(self.upper_bounds, prob)
104
+ probs[i] = self.conf[idx]
105
+
106
+ return probs
107
+
108
+
109
+ class TemperatureScaling():
110
+
111
+ def __init__(self, temp = 1, maxiter = 50, solver = "BFGS"):
112
+ """
113
+ Initialize class
114
+
115
+ Params:
116
+ temp (float): starting temperature, default 1
117
+ maxiter (int): maximum iterations done by optimizer, however 8 iterations have been maximum.
118
+ """
119
+ self.temp = temp
120
+ self.maxiter = maxiter
121
+ self.solver = solver
122
+
123
+ def _loss_fun(self, x, probs, true):
124
+ # Calculates the loss using log-loss (cross-entropy loss)
125
+ scaled_probs = self.predict(probs, x)
126
+ loss = log_loss(y_true=true, y_pred=scaled_probs)
127
+ return loss
128
+
129
+ # Find the temperature
130
+ def fit(self, logits, true):
131
+ """
132
+ Trains the model and finds optimal temperature
133
+
134
+ Params:
135
+ logits: the output from neural network for each class (shape [samples, classes])
136
+ true: one-hot-encoding of true labels.
137
+
138
+ Returns:
139
+ the results of optimizer after minimizing is finished.
140
+ """
141
+
142
+ true = true.flatten() # Flatten y_val
143
+ opt = minimize(self._loss_fun, x0 = 1, args=(logits, true), options={'maxiter':self.maxiter}, method = self.solver)
144
+ self.temp = opt.x[0]
145
+
146
+ return opt
147
+
148
+ def predict(self, logits, temp = None):
149
+ """
150
+ Scales logits based on the temperature and returns calibrated probabilities
151
+
152
+ Params:
153
+ logits: logits values of data (output from neural network) for each class (shape [samples, classes])
154
+ temp: if not set use temperatures find by model or previously set.
155
+
156
+ Returns:
157
+ calibrated probabilities (nd.array with shape [samples, classes])
158
+ """
159
+
160
+ if not temp:
161
+ return softmax(logits/self.temp)
162
+ else:
163
+ return softmax(logits/temp)
164
+
165
+ def compute_acc_bin(conf_thresh_lower, conf_thresh_upper, conf, pred, true):
166
+ """
167
+ # Computes accuracy and average confidence for bin
168
+
169
+ Args:
170
+ conf_thresh_lower (float): Lower Threshold of confidence interval
171
+ conf_thresh_upper (float): Upper Threshold of confidence interval
172
+ conf (numpy.ndarray): list of confidences
173
+ pred (numpy.ndarray): list of predictions
174
+ true (numpy.ndarray): list of true labels
175
+
176
+ Returns:
177
+ (accuracy, avg_conf, len_bin): accuracy of bin, confidence of bin and number of elements in bin.
178
+ """
179
+ filtered_tuples = [x for x in zip(pred, true, conf) if x[2] > conf_thresh_lower and x[2] <= conf_thresh_upper]
180
+ if len(filtered_tuples) < 1:
181
+ return 0,0,0
182
+ else:
183
+ correct = len([x for x in filtered_tuples if x[0] == x[1]]) # How many correct labels
184
+ len_bin = len(filtered_tuples) # How many elements falls into given bin
185
+ avg_conf = sum([x[2] for x in filtered_tuples]) / len_bin # Avg confidence of BIN
186
+ accuracy = float(correct)/len_bin # accuracy of BIN
187
+ return accuracy, avg_conf, len_bin
188
+
189
+
190
+ def ECE(conf, pred, true, bin_size = 0.1):
191
+
192
+ """
193
+ Expected Calibration Error
194
+
195
+ Args:
196
+ conf (numpy.ndarray): list of confidences
197
+ pred (numpy.ndarray): list of predictions
198
+ true (numpy.ndarray): list of true labels
199
+ bin_size: (float): size of one bin (0,1) # TODO should convert to number of bins?
200
+
201
+ Returns:
202
+ ece: expected calibration error
203
+ """
204
+
205
+ upper_bounds = np.arange(bin_size, 1+bin_size, bin_size) # Get bounds of bins
206
+
207
+ n = len(conf)
208
+ ece = 0 # Starting error
209
+
210
+ for conf_thresh in upper_bounds: # Go through bounds and find accuracies and confidences
211
+ acc, avg_conf, len_bin = compute_acc_bin(conf_thresh-bin_size, conf_thresh, conf, pred, true)
212
+ ece += np.abs(acc-avg_conf)*len_bin/n # Add weigthed difference to ECE
213
+
214
+ return ece
215
+
216
+
217
+ def MCE(conf, pred, true, bin_size = 0.1):
218
+
219
+ """
220
+ Maximal Calibration Error
221
+
222
+ Args:
223
+ conf (numpy.ndarray): list of confidences
224
+ pred (numpy.ndarray): list of predictions
225
+ true (numpy.ndarray): list of true labels
226
+ bin_size: (float): size of one bin (0,1) # TODO should convert to number of bins?
227
+
228
+ Returns:
229
+ mce: maximum calibration error
230
+ """
231
+
232
+ upper_bounds = np.arange(bin_size, 1+bin_size, bin_size)
233
+
234
+ cal_errors = []
235
+
236
+ for conf_thresh in upper_bounds:
237
+ acc, avg_conf, _ = compute_acc_bin(conf_thresh-bin_size, conf_thresh, conf, pred, true)
238
+ cal_errors.append(np.abs(acc-avg_conf))
239
+
240
+ return max(cal_errors)
241
+
242
+
243
+ def get_bin_info(conf, pred, true, bin_size = 0.1):
244
+
245
+ """
246
+ Get accuracy, confidence and elements in bin information for all the bins.
247
+
248
+ Args:
249
+ conf (numpy.ndarray): list of confidences
250
+ pred (numpy.ndarray): list of predictions
251
+ true (numpy.ndarray): list of true labels
252
+ bin_size: (float): size of one bin (0,1) # TODO should convert to number of bins?
253
+
254
+ Returns:
255
+ (acc, conf, len_bins): tuple containing all the necessary info for reliability diagrams.
256
+ """
257
+
258
+ upper_bounds = np.arange(bin_size, 1+bin_size, bin_size)
259
+
260
+ accuracies = []
261
+ confidences = []
262
+ bin_lengths = []
263
+
264
+ for conf_thresh in upper_bounds:
265
+ acc, avg_conf, len_bin = compute_acc_bin(conf_thresh-bin_size, conf_thresh, conf, pred, true)
266
+ accuracies.append(acc)
267
+ confidences.append(avg_conf)
268
+ bin_lengths.append(len_bin)
269
+
270
+
271
+ return accuracies, confidences, bin_lengths
272
+
273
+ def evaluate(probs, y_true, verbose = False, normalize = False, bins = 15):
274
+ """
275
+ Evaluate model using various scoring measures: Error Rate, ECE, MCE, NLL, Brier Score
276
+
277
+ Params:
278
+ probs: a list containing probabilities for all the classes with a shape of (samples, classes)
279
+ y_true: a list containing the actual class labels
280
+ verbose: (bool) are the scores printed out. (default = False)
281
+ normalize: (bool) in case of 1-vs-K calibration, the probabilities need to be normalized.
282
+ bins: (int) - into how many bins are probabilities divided (default = 15)
283
+
284
+ Returns:
285
+ (error, ece, mce, loss, brier), returns various scoring measures
286
+ """
287
+
288
+ preds = np.argmax(probs, axis=1) # Take maximum confidence as prediction
289
+
290
+ if normalize:
291
+ confs = np.max(probs, axis=1)/np.sum(probs, axis=1)
292
+ # Check if everything below or equal to 1?
293
+ else:
294
+ confs = np.max(probs, axis=1) # Take only maximum confidence
295
+
296
+ accuracy = metrics.accuracy_score(y_true, preds) * 100
297
+ error = 100 - accuracy
298
+
299
+ # Calculate ECE
300
+ ece = ECE(confs, preds, y_true, bin_size = 1/bins)
301
+ # Calculate MCE
302
+ mce = MCE(confs, preds, y_true, bin_size = 1/bins)
303
+
304
+ loss = log_loss(y_true=y_true, y_pred=probs)
305
+
306
+ y_prob_true = np.array([probs[i, idx] for i, idx in enumerate(y_true)]) # Probability of positive class
307
+ brier = brier_score_loss(y_true=y_true, y_prob=y_prob_true) # Brier Score (MSE)
308
+
309
+ if verbose:
310
+ print("Accuracy:", accuracy)
311
+ print("Error:", error)
312
+ print("ECE:", ece)
313
+ print("MCE:", mce)
314
+ print("Loss:", loss)
315
+ print("brier:", brier)
316
+
317
+ return (error, ece, mce, loss, brier)
318
+
319
+
320
+ def cal_results(fn,
321
+ train_logits,
322
+ train_labels,
323
+ test_logits,
324
+ m_kwargs={},
325
+ approach="1-vs-k"):
326
+
327
+ """
328
+ Calibrate models scores, using output from logits files and given function (fn).
329
+ There are implemented to different approaches "all" and "1-vs-K" for calibration,
330
+ the approach of calibration should match with function used for calibration.
331
+
332
+ TODO: split calibration of single and all into separate functions for more use cases.
333
+
334
+ Params:
335
+ fn (class): class of the calibration method used. It must contain methods "fit" and "predict",
336
+ where first fits the models and second outputs calibrated probabilities.
337
+ path (string): path to the folder with logits files
338
+ files (list of strings): pickled logits files ((logits_val, y_val), (logits_test, y_test))
339
+ m_kwargs (dictionary): keyword arguments for the calibration class initialization
340
+ approach (string): "all" for multiclass calibration and "1-vs-K" for 1-vs-K approach.
341
+
342
+ Returns:
343
+ df (pandas.DataFrame): dataframe with calibrated and uncalibrated results for all the input files.
344
+
345
+ """
346
+ y_val = train_labels
347
+ logits_val = train_logits
348
+ logits_test = test_logits
349
+
350
+ if approach == "all":
351
+
352
+ y_val = y_val.flatten()
353
+
354
+ model = fn(**m_kwargs)
355
+
356
+ model.fit(logits_val, y_val)
357
+
358
+ probs_val = model.predict(logits_val)
359
+ probs_test = model.predict(logits_test)
360
+ return probs_test
361
+
362
+ else: # 1-vs-k models
363
+ probs_val = softmax(logits_val) # Softmax logits
364
+ probs_test = softmax(logits_test)
365
+ K = probs_test.shape[1]
366
+
367
+ # Go through all the classes
368
+ for k in range(K):
369
+ # Prep class labels (1 fixed true class, 0 other classes)
370
+ y_cal = np.array(y_val == k, dtype="int")
371
+
372
+ # print("sum y_cal ", np.sum(y_cal))
373
+ if np.sum(y_cal) < 1:
374
+ probs_test[:, k] = 0
375
+ continue
376
+
377
+ # Train model
378
+ model = fn(**m_kwargs)
379
+ model.fit(probs_val[:, k], y_cal) # Get only one column with probs for given class "k"
380
+
381
+ probs_val[:, k] = model.predict(probs_val[:, k]) # Predict new values based on the fitting
382
+ probs_test[:, k] = model.predict(probs_test[:, k])
383
+
384
+ # Replace NaN with 0, as it should be close to zero # TODO is it needed?
385
+ idx_nan = np.where(np.isnan(probs_test))
386
+ probs_test[idx_nan] = 0
387
+
388
+ idx_nan = np.where(np.isnan(probs_val))
389
+ probs_val[idx_nan] = 0
390
+
391
+ probs_test += 1e-10 # avoid 1.0 and 0.0
392
+ probs_test = probs_test / np.sum(probs_test, axis=1, keepdims=True)
393
+ return probs_test
394
+
395
+
396
+ def calibrate(
397
+ method_name,
398
+ train_logits,
399
+ train_labels,
400
+ test_logits,
401
+ *args, **kwargs):
402
+ train_logits = train_logits.numpy()
403
+ train_labels = train_labels.numpy()
404
+ test_logits = test_logits.numpy()
405
+ if method_name == "temp_scaling_ref":
406
+ calibrated_prob = cal_results(fn=TemperatureScaling,
407
+ train_logits=train_logits,
408
+ train_labels=train_labels,
409
+ test_logits=test_logits,
410
+ approach="all")
411
+ elif method_name == "histogram_binning":
412
+ calibrated_prob = cal_results(fn=HistogramBinning,
413
+ train_logits=train_logits,
414
+ train_labels=train_labels,
415
+ test_logits=test_logits,
416
+ approach="1-vs-k")
417
+ elif method_name == "beta_calibration":
418
+ calibrated_prob = cal_results(fn=BetaCalibration,
419
+ train_logits=train_logits,
420
+ train_labels=train_labels,
421
+ test_logits=test_logits,
422
+ m_kwargs={'parameters':"abm"},
423
+ approach="1-vs-k")
424
+ elif method_name == "isotonic_regression":
425
+ calibrated_prob = cal_results(fn=IsotonicRegression,
426
+ train_logits=train_logits,
427
+ train_labels=train_labels,
428
+ test_logits=test_logits,
429
+ m_kwargs={'y_min':0, 'y_max':1},
430
+ approach="1-vs-k")
431
+ else:
432
+ raise ValueError(method_name)
433
+ return {
434
+ "prob": torch.from_numpy(calibrated_prob)
435
+ }
AAAI2025-FC/calibration/group_calibration/methods/temp_scaling.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import torch
3
+ import torch.nn.functional as F
4
+ import numpy as np
5
+
6
+
7
+ def calibrate(train_logits,
8
+ train_labels,
9
+ test_logits,
10
+ *args, **kwargs):
11
+ train_logits = train_logits.cuda()
12
+ train_labels = train_labels.cuda()
13
+
14
+ tau = torch.nn.Parameter(torch.tensor(1.0))
15
+ optimizer = torch.optim.LBFGS([tau],
16
+ line_search_fn="strong_wolfe",
17
+ max_iter=50)
18
+
19
+ def closure():
20
+ optimizer.zero_grad()
21
+ loss = F.cross_entropy(train_logits / tau, train_labels)
22
+ loss.backward()
23
+ return loss
24
+ optimizer.step(closure=closure)
25
+ final_loss = closure()
26
+
27
+ if torch.isnan(tau):
28
+ tau = 1
29
+ else:
30
+ tau = tau.item()
31
+
32
+ return {
33
+ "tau": tau,
34
+ "logits": test_logits / tau,
35
+ "loss": final_loss.item()
36
+ }
AAAI2025-FC/calibration/group_calibration/utils.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import torch
3
+ import numpy as np
4
+
5
+
6
+ def gather_metrics(metrics):
7
+ _metrics = sorted(metrics, key=lambda x: x[0])
8
+ metrics = [x[1] for x in _metrics]
9
+ assert isinstance(metrics, list)
10
+ res = {k: [] for k in metrics[0].keys()}
11
+
12
+ for m in metrics:
13
+ to_del = []
14
+ for k in res:
15
+ if k not in m:
16
+ to_del.append(k)
17
+ for k in to_del:
18
+ del res[k]
19
+
20
+ for m in metrics:
21
+ for k in res.keys():
22
+ res[k].append(m[k])
23
+
24
+ res_stats = {}
25
+ for k, v in res.items():
26
+ res_stats[k] = {"mean": np.mean(v), "std": np.std(v)}
27
+ logging.info("Raw metrics: {}".format(res))
28
+ return res_stats, metrics
29
+
30
+
31
+ def set_seed(seed, get_state=False, set_torch=True, set_numpy=True):
32
+ if get_state:
33
+ if set_torch:
34
+ torch_state = torch.get_rng_state()
35
+ else:
36
+ torch_state = None
37
+ if set_numpy:
38
+ numpy_state = np.random.get_state()
39
+ else:
40
+ numpy_state = None
41
+ else:
42
+ torch_state, numpy_state = None, None
43
+ if set_torch:
44
+ torch.manual_seed(seed)
45
+ if set_numpy:
46
+ np.random.seed(seed)
47
+ if get_state:
48
+ return (torch_state, numpy_state)
49
+
50
+
51
+ def restore_state(states, set_torch=True, set_numpy=True):
52
+ if set_torch:
53
+ torch.set_rng_state(states[0])
54
+ if set_numpy:
55
+ np.random.set_state(states[1])
56
+
57
+
58
+ class seed_scope:
59
+
60
+ def __init__(self, seed, set_torch=True, set_numpy=True):
61
+ self.seed = seed
62
+ self.set_torch = set_torch
63
+ self.set_numpy = set_numpy
64
+
65
+ def __enter__(self):
66
+ self.prev_state = set_seed(self.seed, get_state=True,
67
+ set_numpy=self.set_numpy,
68
+ set_torch=self.set_torch)
69
+
70
+ def __exit__(self, type, value, traceback):
71
+ restore_state(self.prev_state,
72
+ set_torch=self.set_torch,
73
+ set_numpy=self.set_numpy)
74
+
75
+
76
+ class RandomSplitter:
77
+ def __init__(self, splits, num, seed=None):
78
+ assert np.isclose(np.sum(splits), 1)
79
+ self.num = num
80
+ idx = list(range(num))
81
+ with seed_scope(seed=seed, set_torch=False):
82
+ np.random.shuffle(idx)
83
+ cnt = 0
84
+ self.idx_splits = []
85
+ for s in splits[:-1]:
86
+ length = int(s * num)
87
+ self.idx_splits.append(idx[cnt: cnt+length])
88
+ cnt += length
89
+ self.idx_splits.append(idx[cnt:])
90
+
91
+ def split(self, x, split_id=None):
92
+ if split_id is not None:
93
+ return x[self.idx_splits[split_id]]
94
+ else:
95
+ return [x[_idx] for _idx in self.idx_splits]
AAAI2025-FC/calibration/pts_cts_ets/__init__.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+ from . import lossfunction, scaler, optimizer
4
+ from .option import opt
5
+ from .utils import dataset_mapping, dataloader, expected_caibration_error, calibrator_mapping, loss_mapping
6
+
7
+ # Dataset params
8
+ dataset_num_classes = {
9
+ 'cifar10': 10,
10
+ 'cifar100': 100,
11
+ 'tiny_imagenet': 200,
12
+ 'imagenet': 1000
13
+ }
14
+
15
+ class calibrator(nn.Module):
16
+ def __init__(self, args):
17
+ super(calibrator, self).__init__()
18
+ torch.manual_seed(1)
19
+ self.data = args.dataset
20
+ self.n_class = dataset_num_classes[args.dataset]
21
+ # Call the function to measure accuracy and expected calibration error.
22
+ self.evaluator = expected_caibration_error()
23
+
24
+ # Call the scaler for selected temperature based approach.
25
+ self.scaler = getattr(scaler, calibrator_mapping(args.cal))(args)
26
+
27
+ # Call the loss for learn.
28
+ self.loss = getattr(lossfunction, loss_mapping('CE'))(args)
29
+
30
+ # Call the optimizer for corresponding combination of scaler and loss.
31
+ self.optim = args.optim
32
+ self.optimizer = [getattr(optimizer, self.optim)(self.scaler, args)] if args.cal != 'ETS' else [
33
+ getattr(optimizer, self.optim)(self.scaler.t, args), getattr(optimizer, self.optim)(self.scaler.w, args)
34
+ ]
35
+
36
+ def evaluate(self, x, y):
37
+ # Evaluate the uncalibrated logits.
38
+ uncalibrated_ece, uncalibrated_acc = self.evaluator(x, y)
39
+
40
+ # Calibrate the logits.
41
+ q = self.forward(x)
42
+
43
+ # Evaluate the calibrated logits.
44
+ calibrated_ece, calibrated_acc = self.evaluator(q, y)
45
+
46
+
47
+ def forward(self, x):
48
+ return self.scaler(x)
49
+
50
+ def train(self, x, y):
51
+ # Training for Parameterized Temperature Scaling
52
+ if 'adam' in self.optim:
53
+ for optimizers in self.optimizer:
54
+ for optimizer, epochs in optimizers:
55
+ for _ in range(epochs):
56
+ optimizer.zero_grad()
57
+ q = self.forward(x)
58
+ loss = self.loss(q, y)
59
+ loss.backward()
60
+ optimizer.step()
61
+
62
+ # Traninig for Temperature Scaling and Class-based Temperature Scaling
63
+ else:
64
+ for optimizers in self.optimizer:
65
+ for optimizer in optimizers:
66
+ def trainer():
67
+ optimizer.zero_grad()
68
+ q = self.forward(x)
69
+ loss = self.loss(q, y)
70
+ loss.backward()
71
+
72
+ return loss
73
+
74
+ optimizer.step(trainer)
AAAI2025-FC/calibration/pts_cts_ets/dataloader.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pickle
2
+ import torch
3
+
4
+ def dataloader(file, args):
5
+ with open(file, 'rb') as f:
6
+ (y_probs_val, y_val), (y_probs_test, y_test) = pickle.load(f)
7
+
8
+ if args.logger != 'None':
9
+ args.logger.info("{}".format(file.split('/')[-1].split('.p')[0]))
10
+ args.logger.info("y_probs_val : {} | y_val : {} | y_probs_test : {} | y_true_test : {}".format(y_probs_val.shape,y_val.shape,y_probs_test.shape,y_test.shape))
11
+
12
+ n_class = y_probs_val.shape[1]
13
+
14
+ valid_logits = torch.tensor(y_probs_val).cuda()
15
+ valid_labels = torch.tensor(y_val).long().view(-1).cuda()
16
+ test_logits = torch.tensor(y_probs_test).cuda()
17
+ test_labels = torch.tensor(y_test).long().view(-1).cuda()
18
+
19
+ return ((valid_logits, valid_labels), (test_logits, test_labels), n_class)
AAAI2025-FC/calibration/pts_cts_ets/lossfunction.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ from scipy import optimize
4
+ from torch import nn
5
+ from torch.autograd import Variable
6
+ from torch.nn import functional as F
7
+
8
+ # Baseline Loss
9
+ class cross_entropy_loss(nn.Module):
10
+ def __init__(self, args):
11
+ super(cross_entropy_loss, self).__init__()
12
+ self.loss = nn.CrossEntropyLoss()
13
+
14
+ def forward(self, input, target):
15
+ return self.loss(input, target)
16
+
17
+ class label_smoothing_loss(nn.Module):
18
+ def __init__(self, args):
19
+ super(label_smoothing_loss, self).__init__()
20
+ args.optim += '_schedule'
21
+ self.loss = nn.CrossEntropyLoss(label_smoothing=0.05).cuda()
22
+
23
+ def forward(self, input, target):
24
+ return self.loss(input, target)
25
+
26
+ class focal_loss(nn.Module):
27
+ def __init__(self, args, gamma=3, alpha=None, size_average=True):
28
+ super(focal_loss, self).__init__()
29
+ args.optim += '_schedule'
30
+ self.gamma = gamma
31
+ self.alpha = alpha
32
+ if isinstance(alpha,(float,int)): self.alpha = torch.Tensor([alpha,1-alpha])
33
+ if isinstance(alpha,list): self.alpha = torch.Tensor(alpha)
34
+ self.size_average = size_average
35
+
36
+ def forward(self, input, target):
37
+ if input.dim()>2:
38
+ input = input.view(input.size(0),input.size(1),-1) # N,C,H,W => N,C,H*W
39
+ input = input.transpose(1,2) # N,C,H*W => N,H*W,C
40
+ input = input.contiguous().view(-1,input.size(2)) # N,H*W,C => N*H*W,C
41
+ target = target.view(-1,1)
42
+
43
+ logpt = F.log_softmax(input, dim=1)
44
+ logpt = logpt.gather(1,target)
45
+ logpt = logpt.view(-1)
46
+ pt = Variable(logpt.data.exp())
47
+
48
+ if self.alpha is not None:
49
+ if self.alpha.type()!=input.data.type():
50
+ self.alpha = self.alpha.type_as(input.data)
51
+ at = self.alpha.gather(0,target.data.view(-1))
52
+ logpt = logpt * Variable(at)
53
+
54
+ loss = -1 * (1-pt)**self.gamma * logpt
55
+
56
+ if self.size_average:
57
+ return loss.mean()
58
+ else:
59
+ return loss.sum()
60
+
61
+ class scaling_classwise_training_loss(nn.Module):
62
+ def __init__(self, args):
63
+ super(scaling_classwise_training_loss, self).__init__()
64
+ self.loss = nn.CrossEntropyLoss()
65
+ self.n_class = args.n_class
66
+ self.norm = args.norm
67
+ self.step = 0
68
+ self.alpha = 1
69
+ self.beta = 1.5
70
+
71
+ def forward(self, input, target):
72
+ losses = torch.zeros(self.n_class)
73
+ for i in range(self.n_class):
74
+ indice = target.eq(i)
75
+ tx = input[indice]
76
+ ty = target[indice]
77
+ losses[i] = self.loss(tx, ty)
78
+
79
+ loss = losses.clone().detach()
80
+
81
+ if self.norm == 'ND':
82
+ norm = (loss-loss.mean())/loss.std()
83
+ elif self.norm == 'MM':
84
+ norm = (loss-loss.min())/(loss.max()-loss.min())
85
+ elif self.norm == 'CM':
86
+ norm = (loss-loss.mean())/(loss.max()-loss.min())
87
+
88
+ if self.step == 0:
89
+ self.first = loss.tolist()
90
+
91
+ # Optimize alpha and beta
92
+ elif self.step == 1:
93
+ self.optim = False
94
+ self.optimize_scailing_estimator(norm.tolist(), loss.tolist())
95
+
96
+ self.step += 1
97
+
98
+ # scale loss
99
+ losses *= self.scailing_estimator(norm)
100
+ return losses.sum()
101
+
102
+ def scailing_estimator(self, x):
103
+ return self.beta/(1+np.exp(-x/self.alpha)) - self.beta/2 + 1
104
+
105
+ def optimize_scailing_estimator(self, norm, loss):
106
+ def func(x, *args):
107
+ return np.sqrt(((np.array(args[2]) - (x[1]/(1+np.exp(-np.array(args[0])/x[0])) -x[1]/2) * (np.array(args[1])-np.array(args[2])) - np.array(args[1]).mean()) ** 2).sum())
108
+
109
+ opt = optimize.minimize(func, (self.alpha, self.beta), args=(norm, loss, self.first, self.n_class), method='SLSQP',
110
+ bounds=((0.1, np.log(self.n_class)/2),(1.5, 2.0)), options={'disp':False})
111
+
112
+ self.alpha, self.beta = opt.x
AAAI2025-FC/calibration/pts_cts_ets/optimizer.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch import optim
2
+
3
+ # Optimizer for Temperature Scalinig, Ensemble Temperature Scaling, and Class-based Temperature Scaling
4
+ def lbfgs(cal, args):
5
+ args.lr=0.02
6
+ args.n_iter=1000
7
+ return [optim.LBFGS(cal.parameters(), lr=args.lr, max_iter=args.n_iter)]
8
+
9
+ # Optimizer for Temperature Scalinig, Ensemble Temperature Scaling, and Class-based Temperature Scaling, by using Focal Loss or Label Smoothing
10
+ def lbfgs_schedule(cal, _):
11
+ return [optim.LBFGS(cal.parameters(), lr=0.005, max_iter=200),
12
+ optim.LBFGS(cal.parameters(), lr=0.003, max_iter=400),
13
+ optim.LBFGS(cal.parameters(), lr=0.001, max_iter=400)]
14
+
15
+ # Optimizer for Parameterized Temperature Scalinig
16
+ def adam(cal, args):
17
+ args.lr=0.02
18
+ args.n_iter=1000
19
+ return [[optim.Adam(cal.parameters(), lr=args.lr),args.n_iter]]
20
+
21
+ # Optimizer for Parameterized Temperature Scalinig, by using Focal Loss or Label Smoothing
22
+ def adam_schedule(cal, _):
23
+ return [[optim.Adam(cal.parameters(), lr=0.005), 200],
24
+ [optim.Adam(cal.parameters(), lr=0.003), 400],
25
+ [optim.Adam(cal.parameters(), lr=0.001), 400]]
AAAI2025-FC/calibration/pts_cts_ets/option.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+
3
+ def opt():
4
+ parser = argparse.ArgumentParser(description='SCTL')
5
+ # Datasets
6
+ parser.add_argument('--dataset', type=str, required=True,
7
+ help='Select the datasets')
8
+
9
+ # Calibrator and Training Loss
10
+ parser.add_argument('--cal', type=str, default='TS',
11
+ help='TS : Temperature Scaling, ETS : Ensemble Temperature Scaling, CTS : Class-based Temeprature Scailing, PTS : Parameterized Temerature Scailng')
12
+ parser.add_argument('--loss', type=str, default='CE',
13
+ help='CE : Cross Entropy, LS : Label Smoothing loss, FL : Focal Loss, CL : scaling Class-wise Loss')
14
+
15
+ # Hyper-parameter
16
+ parser.add_argument('--n_iter', type=int, default=1000,
17
+ help='Limit the max iter for optimizer')
18
+ parser.add_argument('--lr', type=float, default=0.02,
19
+ help='Learning rate')
20
+ parser.add_argument('--wd', type=float, default=0.02,
21
+ help='weight_decay')
22
+ parser.add_argument('--norm', type=str, default='ND',
23
+ help='ND : Normal Distribution(standardization), CM : Centerized Min-max normalization ,MM : Min-Max Normalization')
24
+
25
+ # Log
26
+ parser.add_argument('--name', type=str, default='text.log',
27
+ help='Name of log')
28
+ parser.add_argument('--trainlog', action='store_true',
29
+ help='Logging loss and measures during training')
30
+
31
+
32
+ return parser.parse_args()
AAAI2025-FC/calibration/pts_cts_ets/scaler.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+
4
+ class temperature_scaler(nn.Module):
5
+ def __init__(self, args):
6
+ super(temperature_scaler, self).__init__()
7
+ args.optim = 'lbfgs'
8
+ # Call a Tmeperature Scaling parameter.
9
+ self.t = nn.Parameter(torch.ones(1))
10
+
11
+ def forward(self, x):
12
+ return x / self.t
13
+
14
+ class ensemble_scaler(nn.Module):
15
+ def __init__(self, args):
16
+ super(ensemble_scaler, self).__init__()
17
+ # Call a Tmeperature Scaling parameter.
18
+ self.w = nn.Parameter(torch.tensor((1.0, 0.0, 0.0)))
19
+
20
+ def forward(self, x1, x2, x3):
21
+ return x1*self.w[0] + x2*self.w[1] + x3*self.w[2]
22
+
23
+ class ensemble_temperature_scaler(nn.Module):
24
+ def __init__(self, args):
25
+ super(ensemble_temperature_scaler, self).__init__()
26
+ self.n_class = args.n_class
27
+
28
+ self.t = temperature_scaler(args)
29
+ self.w = ensemble_scaler(args)
30
+
31
+ def forward(self, x):
32
+ return self.w(self.t(x), x, 1/self.n_class)
33
+
34
+
35
+ class parameterized_temperature_scaler(nn.Module):
36
+ def __init__(self, args):
37
+ super(parameterized_temperature_scaler, self).__init__()
38
+ args.optim = 'adam'
39
+
40
+ for i in range(4):
41
+ if i == 0:
42
+ model = [nn.Sequential(nn.Linear(10,2),nn.ReLU())]
43
+ else:
44
+ model += [nn.Sequential(nn.Linear(2,2),nn.ReLU())]
45
+ model += [nn.Linear(2,1)]
46
+ self.models = nn.Sequential(*model)
47
+
48
+ def forward(self, x):
49
+ t,_ = x.clone().detach().sort(descending=True)
50
+ t = t[:,:10]
51
+ t = self.models(t)
52
+ return x/t
53
+
54
+ class class_based_temperature_scaler(nn.Module):
55
+ def __init__(self, args):
56
+ super(class_based_temperature_scaler, self).__init__()
57
+ args.optim = 'lbfgs'
58
+ self.T = nn.Parameter(torch.ones(args.n_class))
59
+
60
+ def forward(self, x):
61
+ return x / self.T
AAAI2025-FC/calibration/pts_cts_ets/utils.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import pickle
3
+ from torch import nn
4
+ from torch.nn import functional as F
5
+
6
+ DATASETS = {
7
+ 'cifar10_densenet40' : ['datasets/probs_densenet40_c10_logits.p',],
8
+ 'cifar10_wideresnet32' : ['datasets/probs_resnet_wide32_c10_logits.p',],
9
+ 'cifar10_resnet110' : ['datasets/probs_resnet110_c10_logits.p',],
10
+ 'cifar10_resnet110sd' : ['datasets/probs_resnet110_SD_c10_logits.p',],
11
+ 'cifar100_densenet40' : ['datasets/probs_densenet40_c100_logits.p',],
12
+ 'cifar100_wideresnet32' : ['datasets/probs_resnet_wide32_c100_logits.p',],
13
+ 'cifar100_resnet110' : ['datasets/probs_resnet110_c100_logits.p',],
14
+ 'cifar100_resnet110sd' : ['datasets/probs_resnet110_SD_c100_logits.p',],
15
+ 'imagenet_resnet152' : ['datasets/probs_resnet152_imgnet_logits.p',],
16
+ 'imagenet_densenet161' : ['datasets/probs_densenet161_imgnet_logits.p',],
17
+
18
+ 'LT_cifar10_densenet40' : ['datasets/probs_densenet40_c10_LT_logits.p',],
19
+ 'LT_cifar10_wideresnet28' : ['datasets/probs_resnet_wide28_c10_LT_logits.p',],
20
+ 'LT_cifar10_resnet110' : ['datasets/probs_resnet110_c10_LT_logits.p',],
21
+ 'LT_cifar10_resnet110sd' : ['datasets/probs_resnet110_SD_c10_LT_logits.p',],
22
+ 'LT_cifar100_densenet40' : ['datasets/probs_densenet40_c100_LT_logits.p',],
23
+ 'LT_cifar100_wideresnet28': ['datasets/probs_resnet_wide28_c100_LT_logits.p',],
24
+ 'LT_cifar100_resnet110' : ['datasets/probs_resnet110_c100_LT_logits.p',],
25
+ 'LT_cifar100_resnet110sd' : ['datasets/probs_resnet110_SD_c100_LT_logits.p',],
26
+
27
+ 'cifar10' : ['datasets/probs_densenet40_c10_logits.p',
28
+ 'datasets/probs_resnet_wide32_c10_logits.p',
29
+ 'datasets/probs_resnet110_c10_logits.p',
30
+ 'datasets/probs_resnet110_SD_c10_logits.p',],
31
+ 'cifar100' : ['datasets/probs_densenet40_c100_logits.p',
32
+ 'datasets/probs_resnet_wide32_c100_logits.p',
33
+ 'datasets/probs_resnet110_c100_logits.p',
34
+ 'datasets/probs_resnet110_SD_c100_logits.p',],
35
+ 'imagenet' : ['datasets/probs_resnet152_imgnet_logits.p',
36
+ 'datasets/probs_densenet161_imgnet_logits.p',],
37
+
38
+ 'LT_cifar10' : ['datasets/probs_densenet40_c10_LT_logits.p',
39
+ 'datasets/probs_resnet_wide28_c10_LT_logits.p',
40
+ 'datasets/probs_resnet110_c10_LT_logits.p',
41
+ 'datasets/probs_resnet110_SD_c10_LT_logits.p',],
42
+ 'LT_cifar100' : ['datasets/probs_densenet40_c100_LT_logits.p',
43
+ 'datasets/probs_resnet_wide28_c100_LT_logits.p',
44
+ 'datasets/probs_resnet110_c100_LT_logits.p',
45
+ 'datasets/probs_resnet110_SD_c100_LT_logits.p',],
46
+
47
+ 'all' : ['datasets/probs_densenet40_c10_logits.p',
48
+ 'datasets/probs_resnet_wide32_c10_logits.p',
49
+ 'datasets/probs_resnet110_c10_logits.p',
50
+ 'datasets/probs_resnet110_SD_c10_logits.p',
51
+ 'datasets/probs_densenet40_c100_logits.p',
52
+ 'datasets/probs_resnet_wide32_c100_logits.p',
53
+ 'datasets/probs_resnet110_c100_logits.p',
54
+ 'datasets/probs_resnet110_SD_c100_logits.p',
55
+ 'datasets/probs_resnet152_imgnet_logits.p',
56
+ 'datasets/probs_densenet161_imgnet_logits.p',],
57
+
58
+ 'LT' : ['datasets/probs_densenet40_c10_LT_logits.p',
59
+ 'datasets/probs_resnet_wide28_c10_LT_logits.p',
60
+ 'datasets/probs_resnet110_c10_LT_logits.p',
61
+ 'datasets/probs_resnet110_SD_c10_LT_logits.p',
62
+ 'datasets/probs_densenet40_c100_LT_logits.p',
63
+ 'datasets/probs_resnet_wide28_c100_LT_logits.p',
64
+ 'datasets/probs_resnet110_c100_LT_logits.p',
65
+ 'datasets/probs_resnet110_SD_c100_LT_logits.p',],
66
+
67
+ 'ALL' : ['datasets/probs_densenet40_c10_logits.p',
68
+ 'datasets/probs_resnet_wide32_c10_logits.p',
69
+ 'datasets/probs_resnet110_c10_logits.p',
70
+ 'datasets/probs_resnet110_SD_c10_logits.p',
71
+ 'datasets/probs_densenet40_c100_logits.p',
72
+ 'datasets/probs_resnet_wide32_c100_logits.p',
73
+ 'datasets/probs_resnet110_c100_logits.p',
74
+ 'datasets/probs_resnet110_SD_c100_logits.p',
75
+ 'datasets/probs_resnet152_imgnet_logits.p',
76
+ 'datasets/probs_densenet161_imgnet_logits.p',
77
+ 'datasets/probs_densenet40_c10_LT_logits.p',
78
+ 'datasets/probs_resnet_wide28_c10_LT_logits.p',
79
+ 'datasets/probs_resnet110_c10_LT_logits.p',
80
+ 'datasets/probs_resnet110_SD_c10_LT_logits.p',
81
+ 'datasets/probs_densenet40_c100_LT_logits.p',
82
+ 'datasets/probs_resnet_wide28_c100_LT_logits.p',
83
+ 'datasets/probs_resnet110_c100_LT_logits.p',
84
+ 'datasets/probs_resnet110_SD_c100_LT_logits.p',],
85
+ }
86
+
87
+ CALIBRATOR = {
88
+ 'TS' : 'temperature_scaler',
89
+ 'ETS': 'ensemble_temperature_scaler',
90
+ 'CTS': 'class_based_temperature_scaler',
91
+ 'PTS': 'parameterized_temperature_scaler',
92
+ }
93
+
94
+ LOSS = {
95
+ 'CE' : 'cross_entropy_loss',
96
+ 'LS' : 'label_smoothing_loss',
97
+ 'FL' : 'focal_loss',
98
+ 'CL' : 'scaling_classwise_training_loss'
99
+ }
100
+
101
+ class expected_caibration_error(nn.Module):
102
+ def __init__(self, n_bins=15):
103
+ super(expected_caibration_error, self).__init__()
104
+ bin_boundaries = torch.linspace(0, 1, n_bins + 1)
105
+ self.bin_lowers = bin_boundaries[:-1]
106
+ self.bin_uppers = bin_boundaries[1:]
107
+
108
+ def forward(self, logits, labels):
109
+ softmaxes = F.softmax(logits, dim=1)
110
+ confidences, predictions = torch.max(softmaxes, 1)
111
+ accuracies = predictions.eq(labels)
112
+
113
+ ece = torch.zeros(1, device=logits.device)
114
+ acc = torch.zeros(1, device=logits.device)
115
+ for bin_lower, bin_upper in zip(self.bin_lowers, self.bin_uppers):
116
+ # Calculated |confidence - accuracy| in each bin
117
+ in_bin = confidences.gt(bin_lower.item()) * confidences.le(bin_upper.item())
118
+ prop_in_bin = in_bin.float().mean()
119
+ if prop_in_bin.item() > 0:
120
+ accuracy_in_bin = accuracies[in_bin].float().mean()
121
+ avg_confidence_in_bin = confidences[in_bin].mean()
122
+
123
+ ece += torch.abs(avg_confidence_in_bin - accuracy_in_bin) * prop_in_bin
124
+ acc += accuracies[in_bin].float().mean() * prop_in_bin
125
+ return ece * 100, acc * 100
126
+
127
+ def dataloader(args):
128
+ with open(args.data, 'rb') as f:
129
+ (y_probs_val, y_val), (y_probs_test, y_test) = pickle.load(f)
130
+
131
+ # print("{}".format(file.split('/')[-1].split('.p')[0]))
132
+ # print("y_probs_val : {} | y_val : {} | y_probs_test : {} | y_true_test : {}".format(y_probs_val.shape,y_val.shape,y_probs_test.shape,y_test.shape))
133
+
134
+ args.n_class = y_probs_val.shape[1] # using for class_based_temperature_scalining
135
+
136
+ valid_logits = torch.tensor(y_probs_val).cuda()
137
+ valid_labels = torch.tensor(y_val).long().view(-1).cuda()
138
+ test_logits = torch.tensor(y_probs_test).cuda()
139
+ test_labels = torch.tensor(y_test).long().view(-1).cuda()
140
+
141
+ return (valid_logits, valid_labels), (test_logits, test_labels)
142
+
143
+ def dataset_mapping(data):
144
+ return DATASETS[data]
145
+
146
+ def calibrator_mapping(cal):
147
+ return CALIBRATOR[cal]
148
+
149
+ def loss_mapping(loss):
150
+ return LOSS[loss]
AAAI2025-FC/calibration/temperature_scaling.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ Code to perform temperature scaling. Adapted from https://github.com/gpleiss/temperature_scaling
3
+ '''
4
+ import torch
5
+ import numpy as np
6
+ from torch import nn, optim
7
+ from torch.nn import functional as F
8
+
9
+ from metrics.metrics import ECELoss
10
+
11
+
12
+ class ModelWithTemperature(nn.Module):
13
+ """
14
+ A thin decorator, which wraps a model with temperature scaling
15
+ model (nn.Module):
16
+ A classification neural network
17
+ NB: Output of the neural network should be the classification logits,
18
+ NOT the softmax (or log softmax)!
19
+ """
20
+ def __init__(self, model, log=True):
21
+ super(ModelWithTemperature, self).__init__()
22
+ self.model = model
23
+ self.temperature = 1.0
24
+ self.log = log
25
+
26
+
27
+ def forward(self, input, return_feature=None):
28
+ if return_feature == None:
29
+ logits = self.model(input)
30
+ return self.temperature_scale(logits)
31
+ else:
32
+ logits, features = self.model(input, return_feature=True)
33
+ return self.temperature_scale(logits), features
34
+
35
+
36
+ def temperature_scale(self, logits):
37
+ """
38
+ Perform temperature scaling on logits
39
+ """
40
+ # Expand temperature to match the size of logits
41
+ return logits / self.temperature
42
+
43
+
44
+ def set_temperature(self,
45
+ valid_loader,
46
+ cross_validate='ece'):
47
+ """
48
+ Tune the tempearature of the model (using the validation set) with cross-validation on ECE or NLL
49
+ """
50
+ self.cuda()
51
+ self.model.eval()
52
+ nll_criterion = nn.CrossEntropyLoss().cuda()
53
+ ece_criterion = ECELoss().cuda()
54
+
55
+ # First: collect all the logits and labels for the validation set
56
+ logits_list = []
57
+ labels_list = []
58
+ with torch.no_grad():
59
+ for input, label in valid_loader:
60
+ input = input.cuda()
61
+ logits = self.model(input)
62
+ logits_list.append(logits)
63
+ labels_list.append(label)
64
+ logits = torch.cat(logits_list).cuda()
65
+ labels = torch.cat(labels_list).cuda()
66
+
67
+ # Calculate NLL and ECE before temperature scaling
68
+ before_temperature_nll = nll_criterion(logits, labels).item()
69
+ before_temperature_ece = ece_criterion(logits, labels).item()
70
+ if self.log:
71
+ print('Before temperature - NLL: %.3f, ECE: %.3f' % (before_temperature_nll, before_temperature_ece))
72
+
73
+ nll_val = 10 ** 7
74
+ ece_val = 10 ** 7
75
+ T_opt_nll = 1.0
76
+ T_opt_ece = 1.0
77
+ T = 0.1
78
+ for i in range(100):
79
+ self.temperature = T
80
+ self.cuda()
81
+ after_temperature_nll = nll_criterion(self.temperature_scale(logits), labels).item()
82
+ after_temperature_ece = ece_criterion(self.temperature_scale(logits), labels).item()
83
+ if nll_val > after_temperature_nll:
84
+ T_opt_nll = T
85
+ nll_val = after_temperature_nll
86
+
87
+ if ece_val > after_temperature_ece:
88
+ T_opt_ece = T
89
+ ece_val = after_temperature_ece
90
+ T += 0.1
91
+
92
+ if cross_validate == 'ece':
93
+ self.temperature = T_opt_ece
94
+ else:
95
+ self.temperature = T_opt_nll
96
+ self.cuda()
97
+
98
+ # Calculate NLL and ECE after temperature scaling
99
+ after_temperature_nll = nll_criterion(self.temperature_scale(logits), labels).item()
100
+ after_temperature_ece = ece_criterion(self.temperature_scale(logits), labels).item()
101
+ if self.log:
102
+ print('Optimal temperature: %.3f' % self.temperature)
103
+ print('After temperature - NLL: %.3f, ECE: %.3f' % (after_temperature_nll, after_temperature_ece))
104
+
105
+ return self
106
+
107
+
108
+ def get_temperature(self):
109
+ return self.temperature
110
+
111
+ def classifier(self, features):
112
+ return self.model.classifier(features)
AAAI2025-FC/dataset/__init__.py ADDED
File without changes
AAAI2025-FC/dataset/cifar10.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Create train, valid, test iterators for CIFAR-10.
3
+ Train set size: 45000
4
+ Val set size: 5000
5
+ Test set size: 10000
6
+ """
7
+
8
+ import torch
9
+ import numpy as np
10
+
11
+ from torchvision import datasets
12
+ from torchvision import transforms
13
+ from torch.utils.data.sampler import SubsetRandomSampler
14
+
15
+
16
+ def get_train_valid_loader(batch_size,
17
+ augment,
18
+ random_seed,
19
+ data_dir='/share/datasets/',
20
+ valid_size=0.1,
21
+ shuffle=True,
22
+ num_workers=4,
23
+ pin_memory=False,
24
+ get_val_temp=0):
25
+ """
26
+ Utility function for loading and returning train and valid
27
+ multi-process iterators over the CIFAR-10 dataset.
28
+ Params:
29
+ ------
30
+ - batch_size: how many samples per batch to load.
31
+ - augment: whether to apply the data augmentation scheme
32
+ mentioned in the paper. Only applied on the train split.
33
+ - random_seed: fix seed for reproducibility.
34
+ - valid_size: percentage split of the training set used for
35
+ the validation set. Should be a float in the range [0, 1].
36
+ - shuffle: whether to shuffle the train/validation indices.
37
+ - num_workers: number of subprocesses to use when loading the dataset.
38
+ - pin_memory: whether to copy tensors into CUDA pinned memory. Set it to
39
+ True if using GPU.
40
+ - get_val_temp: set to 1 if temperature is to be set on a separate
41
+ val set other than normal val set.
42
+ Returns
43
+ -------
44
+ - train_loader: training set iterator.
45
+ - valid_loader: validation set iterator.
46
+ """
47
+ error_msg = "[!] valid_size should be in the range [0, 1]."
48
+ assert ((valid_size >= 0) and (valid_size <= 1)), error_msg
49
+
50
+ normalize = transforms.Normalize(
51
+ mean=[0.4914, 0.4822, 0.4465],
52
+ std=[0.2023, 0.1994, 0.2010],
53
+ )
54
+
55
+ # define transforms
56
+ valid_transform = transforms.Compose([
57
+ transforms.ToTensor(),
58
+ normalize,
59
+ ])
60
+ if augment:
61
+ train_transform = transforms.Compose([
62
+ transforms.RandomCrop(32, padding=4),
63
+ transforms.RandomHorizontalFlip(),
64
+ transforms.ToTensor(),
65
+ normalize,
66
+ ])
67
+ else:
68
+ train_transform = transforms.Compose([
69
+ transforms.ToTensor(),
70
+ normalize,
71
+ ])
72
+
73
+ # load the dataset
74
+ train_dataset = datasets.CIFAR10(
75
+ root=data_dir, train=True,
76
+ download=True, transform=train_transform,
77
+ )
78
+
79
+ valid_dataset = datasets.CIFAR10(
80
+ root=data_dir, train=True,
81
+ download=True, transform=valid_transform,
82
+ )
83
+
84
+ num_train = len(train_dataset)
85
+ indices = list(range(num_train))
86
+ split = int(np.floor(valid_size * num_train))
87
+
88
+ if shuffle:
89
+ np.random.seed(random_seed)
90
+ np.random.shuffle(indices)
91
+
92
+ train_idx, valid_idx = indices[split:], indices[:split]
93
+ if get_val_temp > 0:
94
+ valid_temp_dataset = datasets.CIFAR10(
95
+ root=data_dir, train=True,
96
+ download=True, transform=valid_transform,
97
+ )
98
+ split = int(np.floor(get_val_temp * split))
99
+ valid_idx, valid_temp_idx = valid_idx[split:], valid_idx[:split]
100
+ valid_temp_sampler = SubsetRandomSampler(valid_temp_idx)
101
+ valid_temp_loader = torch.utils.data.DataLoader(
102
+ valid_temp_dataset, batch_size=batch_size, sampler=valid_temp_sampler,
103
+ num_workers=num_workers, pin_memory=pin_memory,
104
+ )
105
+
106
+ train_sampler = SubsetRandomSampler(train_idx)
107
+ valid_sampler = SubsetRandomSampler(valid_idx)
108
+
109
+ train_loader = torch.utils.data.DataLoader(
110
+ train_dataset, batch_size=batch_size, sampler=train_sampler,
111
+ num_workers=num_workers, pin_memory=pin_memory,
112
+ )
113
+ valid_loader = torch.utils.data.DataLoader(
114
+ valid_dataset, batch_size=batch_size, sampler=valid_sampler,
115
+ num_workers=num_workers, pin_memory=pin_memory,
116
+ )
117
+ if get_val_temp > 0:
118
+ return (train_loader, valid_loader, valid_temp_loader)
119
+ else:
120
+ return (train_loader, valid_loader)
121
+
122
+
123
+ def get_test_loader(batch_size,
124
+ data_dir='/share/datasets/',
125
+ shuffle=False,
126
+ num_workers=4,
127
+ pin_memory=False,
128
+ drop_index=None):
129
+ """
130
+ Utility function for loading and returning a multi-process
131
+ test iterator over the CIFAR-10 dataset.
132
+ If using CUDA, num_workers should be set to 1 and pin_memory to True.
133
+ Params
134
+ ------
135
+ - batch_size: how many samples per batch to load.
136
+ - shuffle: whether to shuffle the dataset after every epoch.
137
+ - num_workers: number of subprocesses to use when loading the dataset.
138
+ - pin_memory: whether to copy tensors into CUDA pinned memory. Set it to
139
+ True if using GPU.
140
+ Returns
141
+ -------
142
+ - data_loader: test set iterator.
143
+ """
144
+ normalize = transforms.Normalize(
145
+ mean=[0.4914, 0.4822, 0.4465],
146
+ std=[0.2023, 0.1994, 0.2010],
147
+ )
148
+
149
+ # define transform
150
+ transform = transforms.Compose([
151
+ transforms.ToTensor(),
152
+ normalize,
153
+ ])
154
+
155
+ dataset = datasets.CIFAR10(
156
+ root=data_dir, train=False,
157
+ download=True, transform=transform,
158
+ )
159
+
160
+ data_loader = torch.utils.data.DataLoader(
161
+ dataset, batch_size=batch_size, shuffle=shuffle,
162
+ num_workers=num_workers, pin_memory=pin_memory,
163
+ )
164
+
165
+ return data_loader
AAAI2025-FC/dataset/cifar100.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Create train, valid, test iterators for CIFAR-100.
3
+ Train set size: 45000
4
+ Val set size: 5000
5
+ Test set size: 10000
6
+ """
7
+
8
+ import torch
9
+ import numpy as np
10
+
11
+ from torchvision import datasets
12
+ from torchvision import transforms
13
+ from torch.utils.data.sampler import SubsetRandomSampler
14
+
15
+
16
+ def get_train_valid_loader(batch_size,
17
+ augment,
18
+ random_seed,
19
+ data_dir='/share/datasets/',
20
+ valid_size=0.1,
21
+ shuffle=True,
22
+ num_workers=4,
23
+ pin_memory=False,
24
+ get_val_temp=0):
25
+ """
26
+ Utility function for loading and returning train and valid
27
+ multi-process iterators over the CIFAR-100 dataset.
28
+ Params:
29
+ ------
30
+ - batch_size: how many samples per batch to load.
31
+ - augment: whether to apply the data augmentation scheme
32
+ mentioned in the paper. Only applied on the train split.
33
+ - random_seed: fix seed for reproducibility.
34
+ - valid_size: percentage split of the training set used for
35
+ the validation set. Should be a float in the range [0, 1].
36
+ - shuffle: whether to shuffle the train/validation indices.
37
+ - num_workers: number of subprocesses to use when loading the dataset.
38
+ - pin_memory: whether to copy tensors into CUDA pinned memory. Set it to
39
+ True if using GPU.
40
+ - get_val_temp: set to 1 if temperature is to be set on a separate
41
+ val set other than normal val set.
42
+ Returns
43
+ -------
44
+ - train_loader: training set iterator.
45
+ - valid_loader: validation set iterator.
46
+ """
47
+ error_msg = "[!] valid_size should be in the range [0, 1]."
48
+ assert ((valid_size >= 0) and (valid_size <= 1)), error_msg
49
+
50
+ normalize = transforms.Normalize(
51
+ mean=[0.4914, 0.4822, 0.4465],
52
+ std=[0.2023, 0.1994, 0.2010],
53
+ )
54
+
55
+ # define transforms
56
+ valid_transform = transforms.Compose([
57
+ transforms.ToTensor(),
58
+ normalize,
59
+ ])
60
+ if augment:
61
+ train_transform = transforms.Compose([
62
+ transforms.RandomCrop(32, padding=4),
63
+ transforms.RandomHorizontalFlip(),
64
+ transforms.ToTensor(),
65
+ normalize,
66
+ ])
67
+ else:
68
+ train_transform = transforms.Compose([
69
+ transforms.ToTensor(),
70
+ normalize,
71
+ ])
72
+
73
+ # load the dataset
74
+ train_dataset = datasets.CIFAR100(
75
+ root=data_dir, train=True,
76
+ download=True, transform=train_transform,
77
+ )
78
+
79
+ valid_dataset = datasets.CIFAR100(
80
+ root=data_dir, train=True,
81
+ download=True, transform=valid_transform,
82
+ )
83
+
84
+ num_train = len(train_dataset)
85
+ indices = list(range(num_train))
86
+ split = int(np.floor(valid_size * num_train))
87
+
88
+ if shuffle:
89
+ np.random.seed(random_seed)
90
+ np.random.shuffle(indices)
91
+
92
+ train_idx, valid_idx = indices[split:], indices[:split]
93
+ if get_val_temp > 0:
94
+ valid_temp_dataset = datasets.CIFAR100(
95
+ root=data_dir, train=True,
96
+ download=True, transform=valid_transform,
97
+ )
98
+ split = int(np.floor(get_val_temp * split))
99
+ valid_idx, valid_temp_idx = valid_idx[split:], valid_idx[:split]
100
+ valid_temp_sampler = SubsetRandomSampler(valid_temp_idx)
101
+ valid_temp_loader = torch.utils.data.DataLoader(
102
+ valid_temp_dataset, batch_size=batch_size, sampler=valid_temp_sampler,
103
+ num_workers=num_workers, pin_memory=pin_memory,
104
+ )
105
+
106
+ train_sampler = SubsetRandomSampler(train_idx)
107
+ valid_sampler = SubsetRandomSampler(valid_idx)
108
+
109
+ train_loader = torch.utils.data.DataLoader(
110
+ train_dataset, batch_size=batch_size, sampler=train_sampler,
111
+ num_workers=num_workers, pin_memory=pin_memory,
112
+ )
113
+ valid_loader = torch.utils.data.DataLoader(
114
+ valid_dataset, batch_size=batch_size, sampler=valid_sampler,
115
+ num_workers=num_workers, pin_memory=pin_memory,
116
+ )
117
+ if get_val_temp > 0:
118
+ return (train_loader, valid_loader, valid_temp_loader)
119
+ else:
120
+ return (train_loader, valid_loader)
121
+
122
+
123
+ def get_test_loader(batch_size,
124
+ data_dir='/share/datasets/',
125
+ shuffle=True,
126
+ num_workers=4,
127
+ pin_memory=False):
128
+ """
129
+ Utility function for loading and returning a multi-process
130
+ test iterator over the CIFAR-100 dataset.
131
+ If using CUDA, num_workers should be set to 1 and pin_memory to True.
132
+ Params
133
+ ------
134
+ - data_dir: path directory to the dataset.
135
+ - batch_size: how many samples per batch to load.
136
+ - shuffle: whether to shuffle the dataset after every epoch.
137
+ - num_workers: number of subprocesses to use when loading the dataset.
138
+ - pin_memory: whether to copy tensors into CUDA pinned memory. Set it to
139
+ True if using GPU.
140
+ Returns
141
+ -------
142
+ - data_loader: test set iterator.
143
+ """
144
+ normalize = transforms.Normalize(
145
+ mean=[0.485, 0.456, 0.406],
146
+ std=[0.229, 0.224, 0.225],
147
+ )
148
+
149
+ # define transform
150
+ transform = transforms.Compose([
151
+ transforms.ToTensor(),
152
+ normalize,
153
+ ])
154
+
155
+ dataset = datasets.CIFAR100(
156
+ root=data_dir, train=False,
157
+ download=True, transform=transform,
158
+ )
159
+
160
+ data_loader = torch.utils.data.DataLoader(
161
+ dataset, batch_size=batch_size, shuffle=shuffle,
162
+ num_workers=num_workers, pin_memory=pin_memory,
163
+ )
164
+
165
+ return data_loader
AAAI2025-FC/dataset/svhn.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os
3
+ import torch
4
+ import numpy as np
5
+
6
+ from torchvision import datasets
7
+ from torchvision import transforms
8
+ from torch.utils.data import DataLoader
9
+ from torch.utils.data.sampler import SubsetRandomSampler
10
+
11
+
12
+ def get_train_valid_loader(batch_size,
13
+ augment,
14
+ random_seed,
15
+ valid_size=0.1,
16
+ shuffle=True,
17
+ num_workers=4,
18
+ pin_memory=False):
19
+ """
20
+ Utility function for loading and returning train and valid
21
+ multi-process iterators over the SVHN dataset.
22
+ Params:
23
+ ------
24
+ - batch_size: how many samples per batch to load.
25
+ - augment: whether to apply the data augmentation scheme
26
+ mentioned in the paper. Only applied on the train split.
27
+ - random_seed: fix seed for reproducibility.
28
+ - valid_size: percentage split of the training set used for
29
+ the validation set. Should be a float in the range [0, 1].
30
+ - shuffle: whether to shuffle the train/validation indices.
31
+ - num_workers: number of subprocesses to use when loading the dataset.
32
+ - pin_memory: whether to copy tensors into CUDA pinned memory. Set it to
33
+ True if using GPU.
34
+ Returns
35
+ -------
36
+ - train_loader: training set iterator.
37
+ - valid_loader: validation set iterator.
38
+ """
39
+ error_msg = "[!] valid_size should be in the range [0, 1]."
40
+ assert ((valid_size >= 0) and (valid_size <= 1)), error_msg
41
+
42
+ normalize = transforms.Normalize(
43
+ mean=[0.4914, 0.4822, 0.4465],
44
+ std=[0.2023, 0.1994, 0.2010],
45
+ )
46
+
47
+ # define transforms
48
+ valid_transform = transforms.Compose([
49
+ transforms.ToTensor(),
50
+ normalize,
51
+ ])
52
+ #if augment:
53
+ # train_transform = transforms.Compose([
54
+ # transforms.RandomCrop(32, padding=4),
55
+ # transforms.RandomHorizontalFlip(),
56
+ # transforms.ToTensor(),
57
+ # normalize,
58
+ # ])
59
+ #else:
60
+ # train_transform = transforms.Compose([
61
+ # transforms.ToTensor(),
62
+ # normalize,
63
+ # ])
64
+
65
+ # load the dataset
66
+ data_dir = '/share/datasets'
67
+ train_dataset = datasets.SVHN(
68
+ root=data_dir, split='train',
69
+ download=True, transform=valid_transform,
70
+ )
71
+
72
+ valid_dataset = datasets.SVHN(
73
+ root=data_dir, split='train',
74
+ download=True, transform=valid_transform,
75
+ )
76
+
77
+ num_train = len(train_dataset)
78
+ indices = list(range(num_train))
79
+ split = int(np.floor(valid_size * num_train))
80
+
81
+ if shuffle:
82
+ np.random.seed(random_seed)
83
+ np.random.shuffle(indices)
84
+
85
+ train_idx, valid_idx = indices[split:], indices[:split]
86
+ train_sampler = SubsetRandomSampler(train_idx)
87
+ valid_sampler = SubsetRandomSampler(valid_idx)
88
+
89
+ train_loader = torch.utils.data.DataLoader(
90
+ train_dataset, batch_size=batch_size, sampler=train_sampler,
91
+ num_workers=num_workers, pin_memory=pin_memory,
92
+ )
93
+ valid_loader = torch.utils.data.DataLoader(
94
+ valid_dataset, batch_size=batch_size, sampler=valid_sampler,
95
+ num_workers=num_workers, pin_memory=pin_memory,
96
+ )
97
+
98
+ return (train_loader, valid_loader)
99
+
100
+
101
+ def get_test_loader(batch_size,
102
+ shuffle=True,
103
+ num_workers=4,
104
+ pin_memory=False):
105
+ """
106
+ Utility function for loading and returning a multi-process
107
+ test iterator over the SVHN dataset.
108
+ If using CUDA, num_workers should be set to 1 and pin_memory to True.
109
+ Params
110
+ ------
111
+ - batch_size: how many samples per batch to load.
112
+ - shuffle: whether to shuffle the dataset after every epoch.
113
+ - num_workers: number of subprocesses to use when loading the dataset.
114
+ - pin_memory: whether to copy tensors into CUDA pinned memory. Set it to
115
+ True if using GPU.
116
+ Returns
117
+ -------
118
+ - data_loader: test set iterator.
119
+ """
120
+ normalize = transforms.Normalize(
121
+ mean=[0.4914, 0.4822, 0.4465],
122
+ std=[0.2023, 0.1994, 0.2010],
123
+ )
124
+
125
+ # define transform
126
+ transform = transforms.Compose([
127
+ transforms.ToTensor(),
128
+ normalize,
129
+ ])
130
+
131
+ data_dir = '/share/datasets'
132
+ dataset = datasets.SVHN(
133
+ root=data_dir, split='test',
134
+ download=True, transform=transform,
135
+ )
136
+
137
+ data_loader = torch.utils.data.DataLoader(
138
+ dataset, batch_size=batch_size, shuffle=shuffle,
139
+ num_workers=num_workers, pin_memory=pin_memory,
140
+ )
141
+
142
+ return data_loader
AAAI2025-FC/environment.yml ADDED
@@ -0,0 +1,514 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: feature-calibration
2
+ channels:
3
+ - defaults
4
+ dependencies:
5
+ - _anaconda_depends=2024.06=py312_mkl_2
6
+ - _libgcc_mutex=0.1=main
7
+ - _openmp_mutex=5.1=1_gnu
8
+ - abseil-cpp=20211102.0=hd4dd3e8_0
9
+ - aiobotocore=2.12.3=py312h06a4308_0
10
+ - aiohttp=3.9.5=py312h5eee18b_0
11
+ - aioitertools=0.7.1=pyhd3eb1b0_0
12
+ - aiosignal=1.2.0=pyhd3eb1b0_0
13
+ - alabaster=0.7.16=py312h06a4308_0
14
+ - altair=5.0.1=py312h06a4308_0
15
+ - anaconda-anon-usage=0.4.4=py312hfc0e8ea_100
16
+ - anaconda-catalogs=0.2.0=py312h06a4308_1
17
+ - anaconda-client=1.12.3=py312h06a4308_0
18
+ - anaconda-cloud-auth=0.5.1=py312h06a4308_0
19
+ - anaconda-navigator=2.6.0=py312h06a4308_0
20
+ - anaconda-project=0.11.1=py312h06a4308_0
21
+ - annotated-types=0.6.0=py312h06a4308_0
22
+ - anyio=4.2.0=py312h06a4308_0
23
+ - aom=3.6.0=h6a678d5_0
24
+ - appdirs=1.4.4=pyhd3eb1b0_0
25
+ - archspec=0.2.3=pyhd3eb1b0_0
26
+ - argon2-cffi=21.3.0=pyhd3eb1b0_0
27
+ - argon2-cffi-bindings=21.2.0=py312h5eee18b_0
28
+ - arrow=1.2.3=py312h06a4308_1
29
+ - arrow-cpp=14.0.2=h374c478_1
30
+ - astroid=2.14.2=py312h06a4308_0
31
+ - astropy=6.1.0=py312ha883a20_0
32
+ - astropy-iers-data=0.2024.6.3.0.31.14=py312h06a4308_0
33
+ - asttokens=2.0.5=pyhd3eb1b0_0
34
+ - async-lru=2.0.4=py312h06a4308_0
35
+ - atomicwrites=1.4.0=py_0
36
+ - attrs=23.1.0=py312h06a4308_0
37
+ - automat=20.2.0=py_0
38
+ - autopep8=2.0.4=pyhd3eb1b0_0
39
+ - aws-c-auth=0.6.19=h5eee18b_0
40
+ - aws-c-cal=0.5.20=hdbd6064_0
41
+ - aws-c-common=0.8.5=h5eee18b_0
42
+ - aws-c-compression=0.2.16=h5eee18b_0
43
+ - aws-c-event-stream=0.2.15=h6a678d5_0
44
+ - aws-c-http=0.6.25=h5eee18b_0
45
+ - aws-c-io=0.13.10=h5eee18b_0
46
+ - aws-c-mqtt=0.7.13=h5eee18b_0
47
+ - aws-c-s3=0.1.51=hdbd6064_0
48
+ - aws-c-sdkutils=0.1.6=h5eee18b_0
49
+ - aws-checksums=0.1.13=h5eee18b_0
50
+ - aws-crt-cpp=0.18.16=h6a678d5_0
51
+ - aws-sdk-cpp=1.10.55=h721c034_0
52
+ - babel=2.11.0=py312h06a4308_0
53
+ - bcrypt=3.2.0=py312h5eee18b_1
54
+ - beautifulsoup4=4.12.3=py312h06a4308_0
55
+ - binaryornot=0.4.4=pyhd3eb1b0_1
56
+ - black=24.4.2=py312h06a4308_0
57
+ - blas=1.0=mkl
58
+ - bleach=4.1.0=pyhd3eb1b0_0
59
+ - blinker=1.6.2=py312h06a4308_0
60
+ - blosc=1.21.3=h6a678d5_0
61
+ - bokeh=3.4.1=py312he106c6f_0
62
+ - boltons=23.0.0=py312h06a4308_0
63
+ - boost-cpp=1.82.0=hdb19cb5_2
64
+ - botocore=1.34.69=py312h06a4308_0
65
+ - bottleneck=1.3.7=py312ha883a20_0
66
+ - brotli=1.0.9=h5eee18b_8
67
+ - brotli-bin=1.0.9=h5eee18b_8
68
+ - brotli-python=1.0.9=py312h6a678d5_8
69
+ - brunsli=0.1=h2531618_0
70
+ - bzip2=1.0.8=h5eee18b_6
71
+ - c-ares=1.19.1=h5eee18b_0
72
+ - c-blosc2=2.12.0=h80c7b02_0
73
+ - ca-certificates=2024.3.11=h06a4308_0
74
+ - cachetools=5.3.3=py312h06a4308_0
75
+ - certifi=2024.6.2=py312h06a4308_0
76
+ - cffi=1.16.0=py312h5eee18b_1
77
+ - cfitsio=3.470=h5893167_7
78
+ - chardet=4.0.0=py312h06a4308_1003
79
+ - charls=2.2.0=h2531618_0
80
+ - charset-normalizer=2.0.4=pyhd3eb1b0_0
81
+ - click=8.1.7=py312h06a4308_0
82
+ - cloudpickle=2.2.1=py312h06a4308_0
83
+ - colorama=0.4.6=py312h06a4308_0
84
+ - colorcet=3.1.0=py312h06a4308_0
85
+ - comm=0.2.1=py312h06a4308_0
86
+ - conda=24.5.0=py312h06a4308_0
87
+ - conda-build=24.5.1=py312h06a4308_0
88
+ - conda-content-trust=0.2.0=py312h06a4308_1
89
+ - conda-index=0.5.0=py312h06a4308_0
90
+ - conda-libmamba-solver=24.1.0=pyhd3eb1b0_0
91
+ - conda-pack=0.7.1=py312h06a4308_0
92
+ - conda-package-handling=2.3.0=py312h06a4308_0
93
+ - conda-package-streaming=0.10.0=py312h06a4308_0
94
+ - conda-repo-cli=1.0.88=py312h06a4308_0
95
+ - conda-token=0.5.0=pyhd3eb1b0_0
96
+ - constantly=23.10.4=py312h06a4308_0
97
+ - contourpy=1.2.0=py312hdb19cb5_0
98
+ - cookiecutter=2.6.0=py312h06a4308_0
99
+ - cryptography=42.0.5=py312hdda0065_1
100
+ - cssselect=1.2.0=py312h06a4308_0
101
+ - curl=8.7.1=hdbd6064_0
102
+ - cycler=0.11.0=pyhd3eb1b0_0
103
+ - cyrus-sasl=2.1.28=h52b45da_1
104
+ - cytoolz=0.12.2=py312h5eee18b_0
105
+ - dask=2024.5.0=py312h06a4308_0
106
+ - dask-core=2024.5.0=py312h06a4308_0
107
+ - dask-expr=1.1.0=py312h06a4308_0
108
+ - datashader=0.16.2=py312h06a4308_0
109
+ - dav1d=1.2.1=h5eee18b_0
110
+ - dbus=1.13.18=hb2f20db_0
111
+ - debugpy=1.6.7=py312h6a678d5_0
112
+ - decorator=5.1.1=pyhd3eb1b0_0
113
+ - defusedxml=0.7.1=pyhd3eb1b0_0
114
+ - diff-match-patch=20200713=pyhd3eb1b0_0
115
+ - dill=0.3.8=py312h06a4308_0
116
+ - distributed=2024.5.0=py312h06a4308_0
117
+ - distro=1.9.0=py312h06a4308_0
118
+ - docstring-to-markdown=0.11=py312h06a4308_0
119
+ - docutils=0.18.1=py312h06a4308_3
120
+ - entrypoints=0.4=py312h06a4308_0
121
+ - et_xmlfile=1.1.0=py312h06a4308_1
122
+ - executing=0.8.3=pyhd3eb1b0_0
123
+ - expat=2.6.2=h6a678d5_0
124
+ - filelock=3.13.1=py312h06a4308_0
125
+ - flake8=7.0.0=py312h06a4308_0
126
+ - flask=3.0.3=py312h06a4308_0
127
+ - fmt=9.1.0=hdb19cb5_1
128
+ - fontconfig=2.14.1=h4c34cd2_2
129
+ - fonttools=4.51.0=py312h5eee18b_0
130
+ - freetype=2.12.1=h4a9f257_0
131
+ - frozendict=2.4.2=py312h06a4308_0
132
+ - frozenlist=1.4.0=py312h5eee18b_0
133
+ - fsspec=2024.3.1=py312h06a4308_0
134
+ - gensim=4.3.2=py312h526ad5a_0
135
+ - gflags=2.2.2=h6a678d5_1
136
+ - giflib=5.2.1=h5eee18b_3
137
+ - gitdb=4.0.7=pyhd3eb1b0_0
138
+ - gitpython=3.1.37=py312h06a4308_0
139
+ - glib=2.78.4=h6a678d5_0
140
+ - glib-tools=2.78.4=h6a678d5_0
141
+ - glog=0.5.0=h6a678d5_1
142
+ - greenlet=3.0.1=py312h6a678d5_0
143
+ - grpc-cpp=1.48.2=he1ff14a_1
144
+ - gst-plugins-base=1.14.1=h6a678d5_1
145
+ - gstreamer=1.14.1=h5eee18b_1
146
+ - h5py=3.11.0=py312h34c39bb_0
147
+ - hdf5=1.12.1=h2b7332f_3
148
+ - heapdict=1.0.1=pyhd3eb1b0_0
149
+ - holoviews=1.19.0=py312h06a4308_0
150
+ - hvplot=0.10.0=py312h06a4308_0
151
+ - hyperlink=21.0.0=pyhd3eb1b0_0
152
+ - icu=73.1=h6a678d5_0
153
+ - idna=3.7=py312h06a4308_0
154
+ - imagecodecs=2023.1.23=py312h81b8100_1
155
+ - imageio=2.33.1=py312h06a4308_0
156
+ - imagesize=1.4.1=py312h06a4308_0
157
+ - imbalanced-learn=0.12.3=py312h06a4308_1
158
+ - importlib-metadata=7.0.1=py312h06a4308_0
159
+ - incremental=22.10.0=pyhd3eb1b0_0
160
+ - inflection=0.5.1=py312h06a4308_1
161
+ - iniconfig=1.1.1=pyhd3eb1b0_0
162
+ - intake=0.7.0=py312h06a4308_0
163
+ - intel-openmp=2023.1.0=hdb19cb5_46306
164
+ - intervaltree=3.1.0=pyhd3eb1b0_0
165
+ - ipykernel=6.28.0=py312h06a4308_0
166
+ - ipython=8.25.0=py312h06a4308_0
167
+ - ipython_genutils=0.2.0=pyhd3eb1b0_1
168
+ - ipywidgets=7.8.1=py312h06a4308_0
169
+ - isort=5.13.2=py312h06a4308_0
170
+ - itemadapter=0.3.0=pyhd3eb1b0_0
171
+ - itemloaders=1.1.0=py312h06a4308_0
172
+ - itsdangerous=2.2.0=py312h06a4308_0
173
+ - jaraco.classes=3.2.1=pyhd3eb1b0_0
174
+ - jedi=0.18.1=py312h06a4308_1
175
+ - jeepney=0.7.1=pyhd3eb1b0_0
176
+ - jellyfish=1.0.1=py312hb02cf49_0
177
+ - jinja2=3.1.4=py312h06a4308_0
178
+ - jmespath=1.0.1=py312h06a4308_0
179
+ - joblib=1.4.2=py312h06a4308_0
180
+ - jpeg=9e=h5eee18b_1
181
+ - jq=1.6=h27cfd23_1000
182
+ - json5=0.9.6=pyhd3eb1b0_0
183
+ - jsonpatch=1.33=py312h06a4308_1
184
+ - jsonpointer=2.1=pyhd3eb1b0_0
185
+ - jsonschema=4.19.2=py312h06a4308_0
186
+ - jsonschema-specifications=2023.7.1=py312h06a4308_0
187
+ - jupyter=1.0.0=py312h06a4308_9
188
+ - jupyter-lsp=2.2.0=py312h06a4308_0
189
+ - jupyter_client=8.6.0=py312h06a4308_0
190
+ - jupyter_console=6.6.3=py312h06a4308_1
191
+ - jupyter_core=5.7.2=py312h06a4308_0
192
+ - jupyter_events=0.10.0=py312h06a4308_0
193
+ - jupyter_server=2.14.1=py312h06a4308_0
194
+ - jupyter_server_terminals=0.4.4=py312h06a4308_1
195
+ - jupyterlab=4.0.11=py312h06a4308_0
196
+ - jupyterlab-variableinspector=3.1.0=py312h06a4308_0
197
+ - jupyterlab_pygments=0.1.2=py_0
198
+ - jupyterlab_server=2.25.1=py312h06a4308_0
199
+ - jupyterlab_widgets=1.0.0=pyhd3eb1b0_1
200
+ - jxrlib=1.1=h7b6447c_2
201
+ - keyring=24.3.1=py312h06a4308_0
202
+ - kiwisolver=1.4.4=py312h6a678d5_0
203
+ - krb5=1.20.1=h143b758_1
204
+ - lazy-object-proxy=1.10.0=py312h5eee18b_0
205
+ - lazy_loader=0.4=py312h06a4308_0
206
+ - lcms2=2.12=h3be6417_0
207
+ - ld_impl_linux-64=2.38=h1181459_1
208
+ - lerc=3.0=h295c915_0
209
+ - libaec=1.0.4=he6710b0_1
210
+ - libarchive=3.6.2=h6ac8c49_3
211
+ - libavif=0.11.1=h5eee18b_0
212
+ - libboost=1.82.0=h109eef0_2
213
+ - libbrotlicommon=1.0.9=h5eee18b_8
214
+ - libbrotlidec=1.0.9=h5eee18b_8
215
+ - libbrotlienc=1.0.9=h5eee18b_8
216
+ - libclang=14.0.6=default_hc6dbbc7_1
217
+ - libclang13=14.0.6=default_he11475f_1
218
+ - libcups=2.4.2=h2d74bed_1
219
+ - libcurl=8.7.1=h251f7ec_0
220
+ - libdeflate=1.17=h5eee18b_1
221
+ - libedit=3.1.20230828=h5eee18b_0
222
+ - libev=4.33=h7f8727e_1
223
+ - libevent=2.1.12=hdbd6064_1
224
+ - libffi=3.4.4=h6a678d5_1
225
+ - libgcc-ng=11.2.0=h1234567_1
226
+ - libgfortran-ng=11.2.0=h00389a5_1
227
+ - libgfortran5=11.2.0=h1234567_1
228
+ - libglib=2.78.4=hdc74915_0
229
+ - libgomp=11.2.0=h1234567_1
230
+ - libiconv=1.16=h5eee18b_3
231
+ - liblief=0.12.3=h6a678d5_0
232
+ - libllvm14=14.0.6=hdb19cb5_3
233
+ - libmamba=1.5.8=hfe524e5_2
234
+ - libmambapy=1.5.8=py312h2dafd23_2
235
+ - libnghttp2=1.57.0=h2d74bed_0
236
+ - libpng=1.6.39=h5eee18b_0
237
+ - libpq=12.17=hdbd6064_0
238
+ - libprotobuf=3.20.3=he621ea3_0
239
+ - libsodium=1.0.18=h7b6447c_0
240
+ - libsolv=0.7.24=he621ea3_1
241
+ - libspatialindex=1.9.3=h2531618_0
242
+ - libssh2=1.11.0=h251f7ec_0
243
+ - libstdcxx-ng=11.2.0=h1234567_1
244
+ - libthrift=0.15.0=h1795dd8_2
245
+ - libtiff=4.5.1=h6a678d5_0
246
+ - libuuid=1.41.5=h5eee18b_0
247
+ - libwebp-base=1.3.2=h5eee18b_0
248
+ - libxcb=1.15=h7f8727e_0
249
+ - libxkbcommon=1.0.1=h5eee18b_1
250
+ - libxml2=2.10.4=hfdd30dd_2
251
+ - libxslt=1.1.37=h5eee18b_1
252
+ - libzopfli=1.0.3=he6710b0_0
253
+ - linkify-it-py=2.0.0=py312h06a4308_0
254
+ - llvmlite=0.42.0=py312h6a678d5_0
255
+ - locket=1.0.0=py312h06a4308_0
256
+ - lxml=5.2.1=py312hdbbb534_0
257
+ - lz4=4.3.2=py312h5eee18b_0
258
+ - lz4-c=1.9.4=h6a678d5_1
259
+ - lzo=2.10=h7b6447c_2
260
+ - markdown=3.4.1=py312h06a4308_0
261
+ - markdown-it-py=2.2.0=py312h06a4308_1
262
+ - markupsafe=2.1.3=py312h5eee18b_0
263
+ - matplotlib=3.8.4=py312h06a4308_0
264
+ - matplotlib-base=3.8.4=py312h526ad5a_0
265
+ - matplotlib-inline=0.1.6=py312h06a4308_0
266
+ - mccabe=0.7.0=pyhd3eb1b0_0
267
+ - mdit-py-plugins=0.3.0=py312h06a4308_0
268
+ - mdurl=0.1.0=py312h06a4308_0
269
+ - menuinst=2.1.1=py312h06a4308_0
270
+ - mistune=2.0.4=py312h06a4308_0
271
+ - mkl=2023.1.0=h213fc3f_46344
272
+ - mkl-service=2.4.0=py312h5eee18b_1
273
+ - mkl_fft=1.3.8=py312h5eee18b_0
274
+ - mkl_random=1.2.4=py312hdb19cb5_0
275
+ - more-itertools=10.1.0=py312h06a4308_0
276
+ - mpmath=1.3.0=py312h06a4308_0
277
+ - msgpack-python=1.0.3=py312hdb19cb5_0
278
+ - multidict=6.0.4=py312h5eee18b_0
279
+ - multipledispatch=0.6.0=py312h06a4308_0
280
+ - mypy=1.10.0=py312h5eee18b_0
281
+ - mypy_extensions=1.0.0=py312h06a4308_0
282
+ - mysql=5.7.24=h721c034_2
283
+ - navigator-updater=0.5.1=py312h06a4308_0
284
+ - nbclient=0.8.0=py312h06a4308_0
285
+ - nbconvert=7.10.0=py312h06a4308_0
286
+ - nbformat=5.9.2=py312h06a4308_0
287
+ - ncurses=6.4=h6a678d5_0
288
+ - nest-asyncio=1.6.0=py312h06a4308_0
289
+ - networkx=3.2.1=py312h06a4308_0
290
+ - nltk=3.8.1=py312h06a4308_0
291
+ - notebook=7.0.8=py312h06a4308_0
292
+ - notebook-shim=0.2.3=py312h06a4308_0
293
+ - nspr=4.35=h6a678d5_0
294
+ - nss=3.89.1=h6a678d5_0
295
+ - numba=0.59.1=py312h526ad5a_0
296
+ - numexpr=2.8.7=py312hf827012_0
297
+ - numpy=1.26.4=py312hc5e2394_0
298
+ - numpy-base=1.26.4=py312h0da6c21_0
299
+ - numpydoc=1.7.0=py312h06a4308_0
300
+ - oniguruma=6.9.7.1=h27cfd23_0
301
+ - openjpeg=2.4.0=h3ad879b_0
302
+ - openpyxl=3.1.2=py312h5eee18b_0
303
+ - openssl=3.0.14=h5eee18b_0
304
+ - orc=1.7.4=hb3bc3d3_1
305
+ - overrides=7.4.0=py312h06a4308_0
306
+ - packaging=23.2=py312h06a4308_0
307
+ - pandas=2.2.2=py312h526ad5a_0
308
+ - pandocfilters=1.5.0=pyhd3eb1b0_0
309
+ - panel=1.4.4=py312h06a4308_0
310
+ - param=2.1.0=py312h06a4308_0
311
+ - parsel=1.8.1=py312h06a4308_0
312
+ - parso=0.8.3=pyhd3eb1b0_0
313
+ - partd=1.4.1=py312h06a4308_0
314
+ - patch=2.7.6=h7b6447c_1001
315
+ - patchelf=0.17.2=h6a678d5_0
316
+ - pathspec=0.10.3=py312h06a4308_0
317
+ - patsy=0.5.6=py312h06a4308_0
318
+ - pcre2=10.42=hebb0a14_1
319
+ - pexpect=4.8.0=pyhd3eb1b0_3
320
+ - pickleshare=0.7.5=pyhd3eb1b0_1003
321
+ - pillow=10.3.0=py312h5eee18b_0
322
+ - pip=24.0=py312h06a4308_0
323
+ - pkce=1.0.3=py312h06a4308_0
324
+ - pkginfo=1.10.0=py312h06a4308_0
325
+ - platformdirs=3.10.0=py312h06a4308_0
326
+ - plotly=5.22.0=py312he106c6f_0
327
+ - pluggy=1.0.0=py312h06a4308_1
328
+ - ply=3.11=py312h06a4308_1
329
+ - prometheus_client=0.14.1=py312h06a4308_0
330
+ - prompt-toolkit=3.0.43=py312h06a4308_0
331
+ - prompt_toolkit=3.0.43=hd3eb1b0_0
332
+ - protego=0.1.16=py_0
333
+ - protobuf=3.20.3=py312h6a678d5_0
334
+ - psutil=5.9.0=py312h5eee18b_0
335
+ - ptyprocess=0.7.0=pyhd3eb1b0_2
336
+ - pure_eval=0.2.2=pyhd3eb1b0_0
337
+ - py-cpuinfo=9.0.0=py312h06a4308_0
338
+ - py-lief=0.12.3=py312h6a678d5_0
339
+ - pyarrow=14.0.2=py312hb107042_0
340
+ - pyasn1=0.4.8=pyhd3eb1b0_0
341
+ - pyasn1-modules=0.2.8=py_0
342
+ - pybind11-abi=5=hd3eb1b0_0
343
+ - pycodestyle=2.11.1=py312h06a4308_0
344
+ - pycosat=0.6.6=py312h5eee18b_1
345
+ - pycparser=2.21=pyhd3eb1b0_0
346
+ - pyct=0.5.0=py312h06a4308_0
347
+ - pycurl=7.45.2=py312hdbd6064_1
348
+ - pydantic=2.5.3=py312h06a4308_0
349
+ - pydantic-core=2.14.6=py312hb02cf49_0
350
+ - pydeck=0.8.0=py312h06a4308_2
351
+ - pydispatcher=2.0.5=py312h06a4308_3
352
+ - pydocstyle=6.3.0=py312h06a4308_0
353
+ - pyerfa=2.0.1.4=py312ha883a20_0
354
+ - pyflakes=3.2.0=py312h06a4308_0
355
+ - pygments=2.15.1=py312h06a4308_1
356
+ - pyjwt=2.8.0=py312h06a4308_0
357
+ - pylint=2.16.2=py312h06a4308_0
358
+ - pylint-venv=3.0.3=py312h06a4308_0
359
+ - pyls-spyder=0.4.0=pyhd3eb1b0_0
360
+ - pyodbc=5.0.1=py312h6a678d5_0
361
+ - pyopenssl=24.0.0=py312h06a4308_0
362
+ - pyparsing=3.0.9=py312h06a4308_0
363
+ - pyqt=5.15.10=py312h6a678d5_0
364
+ - pyqt5-sip=12.13.0=py312h5eee18b_0
365
+ - pyqtwebengine=5.15.10=py312h6a678d5_0
366
+ - pysocks=1.7.1=py312h06a4308_0
367
+ - pytables=3.9.2=py312h387d6ec_0
368
+ - pytest=7.4.4=py312h06a4308_0
369
+ - python=3.12.4=h5148396_1
370
+ - python-dateutil=2.9.0post0=py312h06a4308_2
371
+ - python-dotenv=0.21.0=py312h06a4308_0
372
+ - python-fastjsonschema=2.16.2=py312h06a4308_0
373
+ - python-json-logger=2.0.7=py312h06a4308_0
374
+ - python-libarchive-c=2.9=pyhd3eb1b0_1
375
+ - python-lmdb=1.4.1=py312h6a678d5_0
376
+ - python-lsp-black=2.0.0=py312h06a4308_0
377
+ - python-lsp-jsonrpc=1.1.2=pyhd3eb1b0_0
378
+ - python-lsp-server=1.10.0=py312h06a4308_0
379
+ - python-slugify=5.0.2=pyhd3eb1b0_0
380
+ - python-snappy=0.6.1=py312h6a678d5_0
381
+ - python-tzdata=2023.3=pyhd3eb1b0_0
382
+ - pytoolconfig=1.2.6=py312h06a4308_0
383
+ - pytz=2024.1=py312h06a4308_0
384
+ - pyviz_comms=3.0.2=py312h06a4308_0
385
+ - pywavelets=1.5.0=py312ha883a20_0
386
+ - pyxdg=0.27=pyhd3eb1b0_0
387
+ - pyyaml=6.0.1=py312h5eee18b_0
388
+ - pyzmq=25.1.2=py312h6a678d5_0
389
+ - qdarkstyle=3.2.3=pyhd3eb1b0_0
390
+ - qstylizer=0.2.2=py312h06a4308_0
391
+ - qt-main=5.15.2=h53bd1ea_10
392
+ - qt-webengine=5.15.9=h9ab4d14_7
393
+ - qtawesome=1.2.2=py312h06a4308_0
394
+ - qtconsole=5.5.1=py312h06a4308_0
395
+ - qtpy=2.4.1=py312h06a4308_0
396
+ - queuelib=1.6.2=py312h06a4308_0
397
+ - re2=2022.04.01=h295c915_0
398
+ - readline=8.2=h5eee18b_0
399
+ - referencing=0.30.2=py312h06a4308_0
400
+ - regex=2023.10.3=py312h5eee18b_0
401
+ - reproc=14.2.4=h6a678d5_2
402
+ - reproc-cpp=14.2.4=h6a678d5_2
403
+ - requests=2.32.2=py312h06a4308_0
404
+ - requests-file=1.5.1=pyhd3eb1b0_0
405
+ - requests-toolbelt=1.0.0=py312h06a4308_0
406
+ - rfc3339-validator=0.1.4=py312h06a4308_0
407
+ - rfc3986-validator=0.1.1=py312h06a4308_0
408
+ - rich=13.3.5=py312h06a4308_1
409
+ - rope=1.12.0=py312h06a4308_0
410
+ - rpds-py=0.10.6=py312hb02cf49_0
411
+ - rtree=1.0.1=py312h06a4308_0
412
+ - ruamel.yaml=0.17.21=py312h5eee18b_0
413
+ - ruamel_yaml=0.17.21=py312h5eee18b_0
414
+ - s2n=1.3.27=hdbd6064_0
415
+ - s3fs=2024.3.1=py312h06a4308_0
416
+ - scikit-image=0.23.2=py312h526ad5a_0
417
+ - scikit-learn=1.4.2=py312h526ad5a_1
418
+ - scipy=1.13.1=py312hc5e2394_0
419
+ - scrapy=2.11.1=py312h06a4308_0
420
+ - seaborn=0.13.2=py312h06a4308_0
421
+ - secretstorage=3.3.1=py312h06a4308_1
422
+ - semver=3.0.2=py312h06a4308_0
423
+ - send2trash=1.8.2=py312h06a4308_0
424
+ - service_identity=18.1.0=pyhd3eb1b0_1
425
+ - setuptools=69.5.1=py312h06a4308_0
426
+ - sip=6.7.12=py312h6a678d5_0
427
+ - six=1.16.0=pyhd3eb1b0_1
428
+ - smart_open=5.2.1=py312h06a4308_0
429
+ - smmap=4.0.0=pyhd3eb1b0_0
430
+ - snappy=1.1.10=h6a678d5_1
431
+ - sniffio=1.3.0=py312h06a4308_0
432
+ - snowballstemmer=2.2.0=pyhd3eb1b0_0
433
+ - sortedcontainers=2.4.0=pyhd3eb1b0_0
434
+ - soupsieve=2.5=py312h06a4308_0
435
+ - sphinx=7.3.7=py312h5eee18b_0
436
+ - sphinxcontrib-applehelp=1.0.2=pyhd3eb1b0_0
437
+ - sphinxcontrib-devhelp=1.0.2=pyhd3eb1b0_0
438
+ - sphinxcontrib-htmlhelp=2.0.0=pyhd3eb1b0_0
439
+ - sphinxcontrib-jsmath=1.0.1=pyhd3eb1b0_0
440
+ - sphinxcontrib-qthelp=1.0.3=pyhd3eb1b0_0
441
+ - sphinxcontrib-serializinghtml=1.1.10=py312h06a4308_0
442
+ - spyder=5.5.1=py312h06a4308_0
443
+ - spyder-kernels=2.5.0=py312h06a4308_0
444
+ - sqlalchemy=2.0.30=py312h5eee18b_0
445
+ - sqlite=3.45.3=h5eee18b_0
446
+ - stack_data=0.2.0=pyhd3eb1b0_0
447
+ - statsmodels=0.14.2=py312ha883a20_0
448
+ - streamlit=1.32.0=py312h06a4308_0
449
+ - sympy=1.12=py312h06a4308_0
450
+ - tabulate=0.9.0=py312h06a4308_0
451
+ - tbb=2021.8.0=hdb19cb5_0
452
+ - tblib=1.7.0=pyhd3eb1b0_0
453
+ - tenacity=8.2.2=py312h06a4308_1
454
+ - terminado=0.17.1=py312h06a4308_0
455
+ - text-unidecode=1.3=pyhd3eb1b0_0
456
+ - textdistance=4.2.1=pyhd3eb1b0_0
457
+ - threadpoolctl=2.2.0=pyh0d69192_0
458
+ - three-merge=0.1.1=pyhd3eb1b0_0
459
+ - tifffile=2023.4.12=py312h06a4308_0
460
+ - tinycss2=1.2.1=py312h06a4308_0
461
+ - tk=8.6.14=h39e8969_0
462
+ - tldextract=3.2.0=pyhd3eb1b0_0
463
+ - toml=0.10.2=pyhd3eb1b0_0
464
+ - tomli=2.0.1=py312h06a4308_1
465
+ - tomlkit=0.11.1=py312h06a4308_0
466
+ - toolz=0.12.0=py312h06a4308_0
467
+ - tornado=6.4.1=py312h5eee18b_0
468
+ - tqdm=4.66.4=py312he106c6f_0
469
+ - traitlets=5.14.3=py312h06a4308_0
470
+ - truststore=0.8.0=py312h06a4308_0
471
+ - twisted=23.10.0=py312h06a4308_0
472
+ - typing-extensions=4.11.0=py312h06a4308_0
473
+ - typing_extensions=4.11.0=py312h06a4308_0
474
+ - tzdata=2024a=h04d1e81_0
475
+ - uc-micro-py=1.0.1=py312h06a4308_0
476
+ - ujson=5.10.0=py312h6a678d5_0
477
+ - unicodedata2=15.1.0=py312h5eee18b_0
478
+ - unidecode=1.2.0=pyhd3eb1b0_0
479
+ - unixodbc=2.3.11=h5eee18b_0
480
+ - urllib3=2.2.2=py312h06a4308_0
481
+ - utf8proc=2.6.1=h5eee18b_1
482
+ - w3lib=1.21.0=pyhd3eb1b0_0
483
+ - watchdog=4.0.1=py312h06a4308_0
484
+ - wcwidth=0.2.5=pyhd3eb1b0_0
485
+ - webencodings=0.5.1=py312h06a4308_2
486
+ - websocket-client=1.8.0=py312h06a4308_0
487
+ - werkzeug=3.0.3=py312h06a4308_0
488
+ - whatthepatch=1.0.2=py312h06a4308_0
489
+ - wheel=0.43.0=py312h06a4308_0
490
+ - widgetsnbextension=3.6.6=py312h06a4308_0
491
+ - wrapt=1.14.1=py312h5eee18b_0
492
+ - wurlitzer=3.0.2=py312h06a4308_0
493
+ - xarray=2023.6.0=py312h06a4308_0
494
+ - xyzservices=2022.9.0=py312h06a4308_1
495
+ - xz=5.4.6=h5eee18b_1
496
+ - yaml=0.2.5=h7b6447c_0
497
+ - yaml-cpp=0.8.0=h6a678d5_1
498
+ - yapf=0.40.2=py312h06a4308_0
499
+ - yarl=1.9.3=py312h5eee18b_0
500
+ - zeromq=4.3.5=h6a678d5_0
501
+ - zfp=1.0.0=h6a678d5_0
502
+ - zict=3.0.0=py312h06a4308_0
503
+ - zipp=3.17.0=py312h06a4308_0
504
+ - zlib=1.2.13=h5eee18b_1
505
+ - zlib-ng=2.0.7=h5eee18b_0
506
+ - zope=1.0=py312h06a4308_1
507
+ - zope.interface=5.4.0=py312h5eee18b_0
508
+ - zstandard=0.22.0=py312h2c38b39_0
509
+ - zstd=1.5.5=hc292b87_2
510
+ - pip:
511
+ - nvidia-ml-py==12.535.161
512
+ - nvitop==1.3.2
513
+ - termcolor==2.4.0
514
+ prefix: /home/lwtao/anaconda3
AAAI2025-FC/evaluate.py ADDED
@@ -0,0 +1,622 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import argparse
3
+ from torch import nn
4
+ import torch.nn.functional as F
5
+ import torch.backends.cudnn as cudnn
6
+ import pandas as pd
7
+ import numpy as np
8
+ from omegaconf import OmegaConf # yaml config for group calibration
9
+ import torchvision
10
+ from torchvision import transforms
11
+ from torch.utils.data import DataLoader, random_split
12
+ import random
13
+ import os
14
+
15
+ # Import dataloaders
16
+ import dataset.cifar10 as cifar10
17
+ import dataset.cifar100 as cifar100
18
+
19
+ # Import network architectures
20
+ from models.resnet import resnet50, resnet110
21
+ from models.densenet import densenet121
22
+ from models.resnet_imagenet import ResNet_ImageNet
23
+ from models.densenet_imagenet import DenseNet121_ImageNet
24
+ from models.wide_resnet_imagenet import Wide_ResNet_ImageNet
25
+ from models.mobilenet_v2_imagenet import MobileNet_V2_ImageNet
26
+
27
+ # Import metrics to compute
28
+ from metrics.metrics import test_classification_net_logits
29
+ from metrics.metrics import ECELoss, AdaptiveECELoss, ClasswiseECELoss
30
+
31
+ # Import post hoc calibration methods
32
+ from calibration.feature_clipping import FeatureClippingCalibrator
33
+ from calibration.pts_cts_ets import calibrator, calibrator_mapping, dataloader, dataset_mapping, loss_mapping, opt
34
+ from calibration.group_calibration.methods import calibrate
35
+ from calibrator import LogitClippingCalibrator
36
+
37
+
38
+ # Dataset params
39
+ dataset_num_classes = {
40
+ 'cifar10': 10,
41
+ 'cifar100': 100,
42
+ 'imagenet': 1000
43
+ }
44
+
45
+ dataset_loader = {
46
+ 'cifar10': cifar10,
47
+ 'cifar100': cifar100,
48
+ }
49
+
50
+ # Mapping model name to model function
51
+ cifar_models = {
52
+ 'resnet50': resnet50,
53
+ 'resnet110': resnet110,
54
+ 'densenet121': densenet121
55
+ }
56
+ imagenet_models = {
57
+ 'resnet50': ResNet_ImageNet(weights=torchvision.models.ResNet50_Weights.IMAGENET1K_V1),
58
+ 'densenet121': DenseNet121_ImageNet(weights=torchvision.models.DenseNet121_Weights.IMAGENET1K_V1),
59
+ 'wide_resnet': Wide_ResNet_ImageNet(weights=torchvision.models.Wide_ResNet50_2_Weights.IMAGENET1K_V2),
60
+ 'mobilenet_v2': MobileNet_V2_ImageNet(weights=torchvision.models.MobileNet_V2_Weights.IMAGENET1K_V2),
61
+ 'vit_l_16':torchvision.models.vit_l_16(weights=torchvision.models.ViT_L_16_Weights.IMAGENET1K_V1),
62
+ }
63
+
64
+ def parseArgs():
65
+ default_dataset = 'cifar10'
66
+ dataset_root = '/share/datasets'
67
+ num_bins = 15
68
+ model_name = None
69
+ train_batch_size = 128
70
+ test_batch_size = 512
71
+ cross_validation_error = 'ece'
72
+
73
+ parser = argparse.ArgumentParser(
74
+ description="Evaluating a single model on calibration metrics.",
75
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter)
76
+ parser.add_argument("--dataset", type=str, default=default_dataset,
77
+ dest="dataset", help='dataset to test on')
78
+ parser.add_argument("--dataset-root", type=str, default=dataset_root,
79
+ dest="dataset_root", help='root path of the dataset')
80
+ parser.add_argument("--model-name", type=str, default=model_name,
81
+ dest="model_name", help='name of the model')
82
+ parser.add_argument("--num-bins", type=int, default=num_bins, dest="num_bins",
83
+ help='Number of bins')
84
+ parser.add_argument("-g", action="store_true", dest="gpu",
85
+ help="Use GPU")
86
+ parser.set_defaults(gpu=True)
87
+ parser.add_argument("-da", action="store_true", dest="data_aug",
88
+ help="Using data augmentation")
89
+ parser.set_defaults(data_aug=True)
90
+ parser.add_argument("-b", type=int, default=train_batch_size,
91
+ dest="train_batch_size", help="Batch size")
92
+ parser.add_argument("-tb", type=int, default=test_batch_size,
93
+ dest="test_batch_size", help="Test Batch size")
94
+ parser.add_argument("--feature_clamp", type=float, default=0.3)
95
+ parser.add_argument("--cverror", type=str, default=cross_validation_error,
96
+ dest="cross_validation_error", help='Error function to do temp scaling')
97
+ parser.add_argument("--debug", action="store_true", dest="debug",
98
+ help="whether to debug the code")
99
+ parser.add_argument("--loss", type=str, default='cross_entropy')
100
+ parser.add_argument("--weights_dir", type=str, default='/share/pretrained_weights')
101
+ parser.add_argument("--fc_type", type=str, default='fc')
102
+
103
+
104
+ return parser.parse_args()
105
+
106
+
107
+ def get_logits_labels(data_loader, net, return_feature=False):
108
+ logits_list = []
109
+ labels_list = []
110
+ features_list = []
111
+ net.eval()
112
+ if return_feature:
113
+ with torch.no_grad():
114
+ for data, label in data_loader:
115
+ data = data.cuda()
116
+ logits, features = net(data, return_feature=return_feature)
117
+ logits_list.append(logits)
118
+ labels_list.append(label)
119
+ features_detach = features.detach().cpu()
120
+ features_list.append(features_detach)
121
+ logits = torch.cat(logits_list).cuda()
122
+ labels = torch.cat(labels_list).cuda()
123
+ features = torch.cat(features_list).cuda()
124
+ return logits, labels, features
125
+ else:
126
+ with torch.no_grad():
127
+ for data, label in data_loader:
128
+ data = data.cuda()
129
+ logits = net(data)
130
+ logits_list.append(logits)
131
+ labels_list.append(label)
132
+ logits = torch.cat(logits_list).cuda()
133
+ labels = torch.cat(labels_list).cuda()
134
+ return logits, labels
135
+
136
+
137
+ if __name__ == "__main__":
138
+
139
+ # Checking if GPU is available
140
+ cuda = False
141
+ if (torch.cuda.is_available()):
142
+ cuda = True
143
+
144
+ # Setting additional parameters
145
+ torch.manual_seed(1)
146
+ device = torch.device("cuda" if cuda else "cpu")
147
+
148
+ args = parseArgs()
149
+
150
+ dataset = args.dataset
151
+ dataset_root = args.dataset_root
152
+ args.n_class = dataset_num_classes[dataset]
153
+ model_name = args.model_name
154
+ num_bins = args.num_bins
155
+ cross_validation_error = args.cross_validation_error
156
+
157
+ # define the calibration criterion
158
+ nll_criterion = nn.CrossEntropyLoss().cuda()
159
+ ece_criterion = ECELoss().cuda()
160
+ adaece_criterion = AdaptiveECELoss().cuda()
161
+ cece_criterion = ClasswiseECELoss().cuda()
162
+
163
+ # load the datasets
164
+ num_classes = dataset_num_classes[dataset]
165
+ if (args.dataset == 'tiny_imagenet'):
166
+ val_loader = dataset_loader[args.dataset].get_data_loader(
167
+ root=args.dataset_root,
168
+ split='val',
169
+ batch_size=args.test_batch_size,
170
+ pin_memory=args.gpu)
171
+
172
+ test_loader = dataset_loader[args.dataset].get_data_loader(
173
+ root=args.dataset_root,
174
+ split='val',
175
+ batch_size=args.test_batch_size,
176
+ pin_memory=args.gpu)
177
+ elif (args.dataset == 'cifar10' or args.dataset == 'cifar100'):
178
+ _, val_loader = dataset_loader[args.dataset].get_train_valid_loader(
179
+ batch_size=args.train_batch_size,
180
+ augment=args.data_aug,
181
+ random_seed=1,
182
+ pin_memory=args.gpu
183
+ )
184
+ test_loader = dataset_loader[args.dataset].get_test_loader(
185
+ batch_size=args.test_batch_size,
186
+ pin_memory=args.gpu,
187
+ )
188
+ elif (args.dataset == 'imagenet'):
189
+ # split 20% of the val set as validation set and the rest 80% as the test set
190
+ # Define the transformation
191
+ transform = transforms.Compose([
192
+ transforms.Resize(256),
193
+ transforms.CenterCrop(224),
194
+ transforms.ToTensor(),
195
+ transforms.Normalize(mean=[0.485, 0.456, 0.406],
196
+ std=[0.229, 0.224, 0.225]),
197
+ ])
198
+
199
+ # Load the entire validation dataset
200
+ full_val_set = torchvision.datasets.ImageFolder(
201
+ root=args.dataset_root + '/imagenet/val',
202
+ transform=transform,
203
+ )
204
+
205
+ # Calculate lengths for validation and test sets
206
+ val_size = int(0.2 * len(full_val_set))
207
+ test_size = len(full_val_set) - val_size
208
+
209
+ # Split the dataset
210
+ seed = 42
211
+ torch.manual_seed(seed)
212
+ random.seed(seed)
213
+ np.random.seed(seed)
214
+ val_set, test_set = random_split(full_val_set, [val_size, test_size])
215
+
216
+ # Create DataLoaders
217
+ val_loader = DataLoader(val_set, batch_size=args.test_batch_size, shuffle=True)
218
+ test_loader = DataLoader(test_set, batch_size=args.test_batch_size, shuffle=True)
219
+
220
+
221
+ # Load the model
222
+ if (args.dataset == 'cifar10' or args.dataset == 'cifar100'):
223
+ model = cifar_models[model_name]
224
+ net = model(num_classes=num_classes).cuda()
225
+ weight = torch.load(f"{args.weights_dir}/{args.dataset}_{args.model_name}_{args.loss}.model", weights_only=True)
226
+ # modify the key name, remove the 'module.'
227
+ new_weight = {k.replace('module.', ''): v for k, v in weight.items()}
228
+ net.load_state_dict(new_weight)
229
+ net.classifier = net.classifier
230
+ elif (args.dataset == 'imagenet'):
231
+ model = imagenet_models[model_name]
232
+ net = model.cuda()
233
+
234
+
235
+ # if file not exist, calculated logits, feature and labels
236
+ logit_path = f'pre_calculated_logits/{args.dataset}/{args.model_name}_{args.loss}.pt'
237
+ if not os.path.exists(logit_path):
238
+ os.makedirs(os.path.dirname(logit_path), exist_ok=True)
239
+ logits_val, labels_val, features_val = get_logits_labels(val_loader, net, return_feature=True)
240
+ logits_test, labels_test, features_test = get_logits_labels(test_loader, net, return_feature=True)
241
+
242
+ torch.save({
243
+ 'logits_val': logits_val,
244
+ 'labels_val': labels_val,
245
+ 'features_val': features_val,
246
+ 'logits_test': logits_test,
247
+ 'labels_test': labels_test,
248
+ 'features_test': features_test,
249
+ }, logit_path)
250
+
251
+ # load logits, feature and labels
252
+ data = torch.load(logit_path, weights_only=False)
253
+ logits_val = data['logits_val']
254
+ labels_val = data['labels_val']
255
+ features_val = data['features_val']
256
+ logits_test = data['logits_test']
257
+ labels_test = data['labels_test']
258
+ features_test = data['features_test']
259
+
260
+ '''
261
+ practice the feature clipping calibration
262
+ '''
263
+ fc_cal = FeatureClippingCalibrator(net, cross_validate=cross_validation_error)
264
+ C_opt_fc = fc_cal.set_feature_clip(features_val, logits_val, labels_val)
265
+
266
+ logits_val_fc, labels_val_fc, features_val_fc = fc_cal(features_val, C_opt_fc), labels_val, fc_cal.feature_clipping(features_val, C_opt_fc)
267
+ logits_test_fc, labels_test_fc, features_test_fc = fc_cal(features_test, C_opt_fc), labels_test, fc_cal.feature_clipping(features_test, C_opt_fc)
268
+ data['logits_val_fc'], data['labels_val_fc'], data['features_val_fc'] = logits_val_fc.detach(), labels_val_fc.detach(), features_val_fc.detach()
269
+ data['logits_test_fc'], data['labels_test_fc'], data['features_test_fc'] = logits_test_fc.detach(), labels_test_fc.detach(), features_test_fc.detach()
270
+ logits_val_fc = data['logits_val_fc']
271
+ labels_val_fc = data['labels_val_fc']
272
+ features_val_fc = data['features_val_fc']
273
+ logits_test_fc = data['logits_test_fc']
274
+ labels_test_fc = data['labels_test_fc']
275
+ features_test_fc = data['features_test_fc']
276
+
277
+ '''
278
+ practice the logit clipping calibration
279
+ '''
280
+ lc_cal = LogitClippingCalibrator()
281
+ C_opt_lc = lc_cal.fit(logits_val, labels_val)
282
+ logits_val_lc = lc_cal.calibrate(logits_val, return_logits=True)
283
+ logits_test_lc = lc_cal.calibrate(logits_test, return_logits=True)
284
+ labels_val_lc = data['labels_val']
285
+ labels_test_lc = data['labels_test']
286
+ data['logits_val_lc'], data['labels_val_lc'] = logits_val_lc.detach(), labels_val_lc.detach()
287
+ data['logits_test_lc'], data['labels_test_lc'] = logits_test_lc.detach(), labels_test_lc.detach()
288
+
289
+ fc_logit_path = f'pre_calculated_logits/{args.dataset}/{args.model_name}_{args.loss}_fc.pt'
290
+ torch.save(data, fc_logit_path)
291
+
292
+
293
+
294
+
295
+ print("=="*20)
296
+ print(args.model_name, args.dataset, args.loss)
297
+ print("=="*20)
298
+
299
+ # evalution results
300
+ results = {
301
+ "cal": [],
302
+ "ece":[],
303
+ "adaece":[],
304
+ "cece":[],
305
+ "nll":[],
306
+ "accuracy":[]
307
+ }
308
+ run_methods = ['Vanilla', 'TS', 'FC', 'FC_TS']
309
+ # run_methods = ['Vanilla', 'LC', 'FC', 'LC_TS', 'FC_TS', 'ETS', 'FC_ETS', 'PTS', 'FC_PTS', 'CTS', 'FC_CTS', 'GC', 'FC_GC']
310
+ # vanilla
311
+ if "Vanilla" in run_methods:
312
+ ece = ece_criterion(logits_test, labels_test).item()
313
+ adaece = adaece_criterion(logits_test, labels_test).item()
314
+ cece = cece_criterion(logits_test, labels_test).item()
315
+ nll = nll_criterion(logits_test, labels_test).item()
316
+ accuracy = logits_test.argmax(dim=1).eq(labels_test).float().mean().item()
317
+ print(f"Vanilla: ECE={round(ece*100, 2)}, Accuracy={round(accuracy*100, 2)}")
318
+ results['cal'].append('Vanilla')
319
+ results['ece'].append(ece)
320
+ results['adaece'].append(adaece)
321
+ results['cece'].append(cece)
322
+ results['nll'].append(nll)
323
+ results['accuracy'].append(accuracy)
324
+
325
+ # LC
326
+ if "LC" in run_methods:
327
+ accuracy_lc = logits_test_lc.argmax(dim=1).eq(labels_test_lc).float().mean().item()
328
+ ece_lc = ece_criterion(logits_test_lc, labels_test_lc).item()
329
+ adaece_lc = adaece_criterion(logits_test_lc, labels_test_lc).item()
330
+ cece_lc = cece_criterion(logits_test_lc, labels_test_lc).item()
331
+ nll_lc = nll_criterion(logits_test_lc, labels_test_lc).item()
332
+ print(f"LC(C={round(C_opt_lc,2)}): ECE={round(ece_lc*100, 2)}, Accuracy={round(accuracy_lc*100, 2)}")
333
+ results['cal'].append(f'LC(C={round(C_opt_lc,2)})')
334
+ results['ece'].append(ece_lc)
335
+ results['adaece'].append(adaece_lc)
336
+ results['cece'].append(cece_lc)
337
+ results['nll'].append(nll_lc)
338
+ results['accuracy'].append(accuracy_lc)
339
+
340
+ # FC
341
+ if "FC" in run_methods:
342
+ accuracy_fc = logits_test_fc.argmax(dim=1).eq(labels_test_fc).float().mean().item()
343
+ ece_fc = ece_criterion(logits_test_fc, labels_test_fc).item()
344
+ adaece_fc = adaece_criterion(logits_test_fc, labels_test_fc).item()
345
+ cece_fc = cece_criterion(logits_test_fc, labels_test_fc).item()
346
+ nll_fc = nll_criterion(logits_test_fc, labels_test_fc).item()
347
+ print(f"FC(C={round(C_opt_fc,2)}): ECE={round(ece_fc*100, 2)}, Accuracy={round(accuracy_fc*100, 2)}")
348
+ results['cal'].append(f'FC(C={round(C_opt_fc,2)})')
349
+ results['ece'].append(ece_fc)
350
+ results['adaece'].append(adaece_fc)
351
+ results['cece'].append(cece_fc)
352
+ results['nll'].append(nll_fc)
353
+ results['accuracy'].append(accuracy_fc)
354
+
355
+ # TS
356
+ if "TS" in run_methods:
357
+ args.cal = 'TS'
358
+ cbt = calibrator(args).cuda()
359
+ cbt.train(logits_val, labels_val)
360
+ logits_ts = cbt(logits_test)
361
+ ece_ts = ece_criterion(logits_ts, labels_test).item()
362
+ adaece_ts = adaece_criterion(logits_ts, labels_test).item()
363
+ cece_ts = cece_criterion(logits_ts, labels_test).item()
364
+ nll_ts = nll_criterion(logits_ts, labels_test).item()
365
+ accuracy_ts = logits_ts.argmax(dim=1).eq(labels_test).float().mean().item()
366
+ print(f"TS: ECE={round(ece_ts*100, 2)}, Accuracy={round(accuracy_ts*100, 2)}")
367
+ results['cal'].append('TS')
368
+ results['ece'].append(ece_ts)
369
+ results['adaece'].append(adaece_ts)
370
+ results['cece'].append(cece_ts)
371
+ results['nll'].append(nll_ts)
372
+ results['accuracy'].append(accuracy_ts)
373
+
374
+ # LC then TS
375
+ if "LC_TS" in run_methods:
376
+ args.cal = 'TS'
377
+ cbt = calibrator(args).cuda()
378
+ cbt.train(logits_val_lc, labels_val_lc)
379
+ logits_lc_ts = cbt(logits_test_lc)
380
+ ece_lc_ts = ece_criterion(logits_lc_ts, labels_test_lc).item()
381
+ adaece_lc_ts = adaece_criterion(logits_lc_ts, labels_test_lc).item()
382
+ cece_lc_ts = cece_criterion(logits_lc_ts, labels_test_lc).item()
383
+ nll_lc_ts = nll_criterion(logits_lc_ts, labels_test_lc).item()
384
+ accuracy_lc_ts = logits_lc_ts.argmax(dim=1).eq(labels_test_lc).float().mean().item()
385
+ print(f"LC_TS: ECE={round(ece_lc_ts*100, 2)}, Accuracy={round(accuracy_lc_ts*100, 2)}")
386
+ results['cal'].append('LC_TS')
387
+ results['ece'].append(ece_lc_ts)
388
+ results['adaece'].append(adaece_lc_ts)
389
+ results['cece'].append(cece_lc_ts)
390
+ results['nll'].append(nll_lc_ts)
391
+ results['accuracy'].append(accuracy_lc_ts)
392
+
393
+ # FC then TS
394
+ if "FC_TS" in run_methods:
395
+ args.cal = 'TS'
396
+ cbt = calibrator(args).cuda()
397
+ cbt.train(logits_val_fc, labels_val_fc)
398
+ logits_fc_ts = cbt(logits_test_fc)
399
+ ece_fc_ts = ece_criterion(logits_fc_ts, labels_test_fc).item()
400
+ adaece_fc_ts = adaece_criterion(logits_fc_ts, labels_test_fc).item()
401
+ cece_fc_ts = cece_criterion(logits_fc_ts, labels_test_fc).item()
402
+ nll_fc_ts = nll_criterion(logits_fc_ts, labels_test_fc).item()
403
+ accuracy_fc_ts = logits_fc_ts.argmax(dim=1).eq(labels_test_fc).float().mean().item()
404
+ print(f"FC_TS: ECE={round(ece_fc_ts*100, 2)}, Accuracy={round(accuracy_fc_ts*100, 2)}")
405
+ results['cal'].append('FC_TS')
406
+ results['ece'].append(ece_fc_ts)
407
+ results['adaece'].append(adaece_fc_ts)
408
+ results['cece'].append(cece_fc_ts)
409
+ results['nll'].append(nll_fc_ts)
410
+ results['accuracy'].append(accuracy_fc_ts)
411
+
412
+
413
+ # ETS
414
+ if "ETS" in run_methods:
415
+ args.cal = 'ETS'
416
+ cbt = calibrator(args).cuda()
417
+ cbt.train(logits_val, labels_val)
418
+ logits_ets = cbt(logits_test)
419
+ ece_ets = ece_criterion(logits_ets, labels_test).item()
420
+ adaece_ets = adaece_criterion(logits_ets, labels_test).item()
421
+ cece_ets = cece_criterion(logits_ets, labels_test).item()
422
+ nll_ets = nll_criterion(logits_ets, labels_test).item()
423
+ accuracy_ets = logits_ets.argmax(dim=1).eq(labels_test).float().mean().item()
424
+ print(f"ETS: ECE={round(ece_ets*100, 2)}, Accuracy={round(accuracy_ets*100, 2)}")
425
+ results['cal'].append('ETS')
426
+ results['ece'].append(ece_ets)
427
+ results['adaece'].append(adaece_ets)
428
+ results['cece'].append(cece_ets)
429
+ results['nll'].append(nll_ets)
430
+ results['accuracy'].append(accuracy_ets)
431
+
432
+ # FC then ETS
433
+ if "FC_ETS" in run_methods:
434
+ args.cal = 'ETS'
435
+ cbt = calibrator(args).cuda()
436
+ cbt.train(logits_val_fc, labels_val_fc)
437
+ logits_fc_ets = cbt(logits_test_fc)
438
+ ece_fc_ets = ece_criterion(logits_fc_ets, labels_test_fc).item()
439
+ adaece_fc_ets = adaece_criterion(logits_fc_ets, labels_test_fc).item()
440
+ cece_fc_ets = cece_criterion(logits_fc_ets, labels_test_fc).item()
441
+ nll_fc_ets = nll_criterion(logits_fc_ets, labels_test_fc).item()
442
+ accuracy_fc_ets = logits_fc_ets.argmax(dim=1).eq(labels_test_fc).float().mean().item()
443
+ print(f"FC_ETS: ECE={round(ece_fc_ets*100, 2)}, Accuracy={round(accuracy_fc_ets*100, 2)}")
444
+ results['cal'].append('FC_ETS')
445
+ results['ece'].append(ece_fc_ets)
446
+ results['adaece'].append(adaece_fc_ets)
447
+ results['cece'].append(cece_fc_ets)
448
+ results['nll'].append(nll_fc_ets)
449
+ results['accuracy'].append(accuracy_fc_ets)
450
+
451
+
452
+ # PTS
453
+ if "PTS" in run_methods:
454
+ args.cal = 'PTS'
455
+ cbt = calibrator(args).cuda()
456
+ cbt.train(logits_val, labels_val)
457
+ logits_pts = cbt(logits_test)
458
+ ece_pts = ece_criterion(logits_pts, labels_test).item()
459
+ adaece_pts = adaece_criterion(logits_pts, labels_test).item()
460
+ cece_pts = cece_criterion(logits_pts, labels_test).item()
461
+ nll_pts = nll_criterion(logits_pts, labels_test).item()
462
+ accuracy_pts = logits_pts.argmax(dim=1).eq(labels_test).float().mean().item()
463
+ print(f"PTS: ECE={round(ece_pts*100, 2)}, Accuracy={round(accuracy_pts*100, 2)}")
464
+ results['cal'].append('PTS')
465
+ results['ece'].append(ece_pts)
466
+ results['adaece'].append(adaece_pts)
467
+ results['cece'].append(cece_pts)
468
+ results['nll'].append(nll_pts)
469
+ results['accuracy'].append(accuracy_pts)
470
+
471
+ # FC then PTS
472
+ if "FC_PTS" in run_methods:
473
+ args.cal = 'PTS'
474
+ cbt = calibrator(args).cuda()
475
+ cbt.train(logits_val_fc, labels_val_fc)
476
+ logits_fc_pts = cbt(logits_test_fc)
477
+ ece_fc_pts = ece_criterion(logits_fc_pts, labels_test_fc).item()
478
+ adaece_fc_pts = adaece_criterion(logits_fc_pts, labels_test_fc).item()
479
+ cece_fc_pts = cece_criterion(logits_fc_pts, labels_test_fc).item()
480
+ nll_fc_pts = nll_criterion(logits_fc_pts, labels_test_fc).item()
481
+ accuracy_fc_pts = logits_fc_pts.argmax(dim=1).eq(labels_test_fc).float().mean().item()
482
+ print(f"FC_PTS: ECE={round(ece_fc_pts*100, 2)}, Accuracy={round(accuracy_fc_pts*100, 2)}")
483
+ results['cal'].append('FC_PTS')
484
+ results['ece'].append(ece_fc_pts)
485
+ results['adaece'].append(adaece_fc_pts)
486
+ results['cece'].append(cece_fc_pts)
487
+ results['nll'].append(nll_fc_pts)
488
+ results['accuracy'].append(accuracy_fc_pts)
489
+
490
+
491
+ # CTS
492
+ if "CTS" in run_methods:
493
+ args.cal = 'CTS'
494
+ cbt = calibrator(args).cuda()
495
+ cbt.train(logits_val, labels_val)
496
+ logits_cts = cbt(logits_test)
497
+ ece_cts = ece_criterion(logits_cts, labels_test).item()
498
+ adaece_cts = adaece_criterion(logits_cts, labels_test).item()
499
+ cece_cts = cece_criterion(logits_cts, labels_test).item()
500
+ nll_cts = nll_criterion(logits_cts, labels_test).item()
501
+ accuracy_cts = logits_cts.argmax(dim=1).eq(labels_test).float().mean().item()
502
+ print(f"CTS: ECE={round(ece_cts*100, 2)}, Accuracy={round(accuracy_cts*100, 2)}")
503
+ results['cal'].append('CTS')
504
+ results['ece'].append(ece_cts)
505
+ results['adaece'].append(adaece_cts)
506
+ results['cece'].append(cece_cts)
507
+ results['nll'].append(nll_cts)
508
+ results['accuracy'].append(accuracy_cts)
509
+
510
+ if "FC_CTS" in run_methods:
511
+ # FC then CTS
512
+ args.cal = 'PTS'
513
+ cbt = calibrator(args).cuda()
514
+ cbt.train(logits_val_fc, labels_val_fc)
515
+ logits_fc_cts = cbt(logits_test_fc)
516
+ ece_fc_cts = ece_criterion(logits_fc_cts, labels_test_fc).item()
517
+ adaece_fc_cts = adaece_criterion(logits_fc_cts, labels_test_fc).item()
518
+ cece_fc_cts = cece_criterion(logits_fc_cts, labels_test_fc).item()
519
+ nll_fc_cts = nll_criterion(logits_fc_cts, labels_test_fc).item()
520
+ accuracy_fc_cts = logits_fc_cts.argmax(dim=1).eq(labels_test_fc).float().mean().item()
521
+ print(f"FC_CTS: ECE={round(ece_fc_cts*100, 2)}, Accuracy={round(accuracy_fc_cts*100, 2)}")
522
+ results['cal'].append('FC_CTS')
523
+ results['ece'].append(ece_fc_cts)
524
+ results['adaece'].append(adaece_fc_cts)
525
+ results['cece'].append(cece_fc_cts)
526
+ results['nll'].append(nll_fc_cts)
527
+ results['accuracy'].append(accuracy_fc_cts)
528
+
529
+
530
+ if "GC" in run_methods:
531
+ # Group Calibration
532
+ conf = OmegaConf.load("calibration/group_calibration/conf/method/group_calibration_combine_ets.yaml")
533
+ logits_val, labels_val, features_val = logits_val.cpu(), labels_val.cpu(), features_val.cpu()
534
+ logits_test, labels_test, features_test = logits_test.cpu(), labels_test.cpu(), features_test.cpu()
535
+ calibrated_test_test = calibrate(method_config=conf,
536
+ val_data={"logits": logits_val, "labels": labels_val, "features": features_val},
537
+ test_train_data={"logits": logits_val, "labels": labels_val, "features": features_val},
538
+ test_test_data={"logits": logits_test, "labels": labels_test, "features": features_test},
539
+ seed=1,
540
+ cfg=None)
541
+ probs_gc = calibrated_test_test.get("prob", None)
542
+ ece_gc = ece_criterion(logits=None, labels=labels_test, probs=probs_gc).item()
543
+ adaece_gc = adaece_criterion(logits=None, labels=labels_test, probs=probs_gc).item()
544
+ cece_gc = cece_criterion(logits=None, labels=labels_test, probs=probs_gc).item()
545
+ nll_gc = torch.mean(-torch.log(probs_gc[range(len(labels_test)), labels_test])).item()
546
+ accuracy_gc = torch.mean(torch.argmax(probs_gc, dim=1).eq(labels_test).float()).item()
547
+ print(f"GC: ECE={round(ece_gc*100, 2)}, Accuracy={round(accuracy_gc*100, 2)}")
548
+ results['cal'].append('GC')
549
+ results['ece'].append(ece_gc)
550
+ results['adaece'].append(adaece_gc)
551
+ results['cece'].append(cece_gc)
552
+ results['nll'].append(nll_gc)
553
+ results['accuracy'].append(accuracy_gc)
554
+
555
+ if "FC_GC" in run_methods:
556
+ # FC then Group Calibration
557
+ conf = OmegaConf.load("calibration/group_calibration/conf/method/group_calibration_combine_ets.yaml")
558
+ logits_test_fc, labels_test_fc, features_test_fc = logits_test_fc.cpu(), labels_test_fc.cpu(), features_test_fc.cpu()
559
+ logits_test_fc, labels_test_fc, features_test_fc = logits_test_fc.cpu(), labels_test_fc.cpu(), features_test_fc.cpu()
560
+ calibrated_test_test = calibrate(method_config=conf,
561
+ val_data={"logits": logits_test_fc, "labels": labels_test_fc, "features": features_test_fc},
562
+ test_train_data={"logits": logits_test_fc, "labels": labels_test_fc, "features": features_test_fc},
563
+ test_test_data={"logits": logits_test_fc, "labels": labels_test_fc, "features": features_test_fc},
564
+ seed=1,
565
+ cfg=None)
566
+ probs_fc_gc = calibrated_test_test.get("prob", None)
567
+ ece_fc_gc = ece_criterion(logits=None, labels=labels_test_fc, probs=probs_fc_gc).item()
568
+ adaece_fc_gc = adaece_criterion(logits=None, labels=labels_test_fc, probs=probs_fc_gc).item()
569
+ cece_fc_gc = cece_criterion(logits=None, labels=labels_test_fc, probs=probs_fc_gc).item()
570
+ nll_fc_gc = torch.mean(-torch.log(probs_fc_gc[range(len(labels_test_fc)), labels_test_fc])).item()
571
+ accuracy_fc_gc = torch.mean(torch.argmax(probs_fc_gc, dim=1).eq(labels_test_fc).float()).item()
572
+ print(f"FC_GC: ECE={round(ece_fc_gc*100, 2)}({round(C_opt_fc,2)}), Accuracy={round(accuracy_fc_gc*100, 2)},")
573
+ results['cal'].append('FC_GC')
574
+ results['ece'].append(ece_fc_gc)
575
+ results['adaece'].append(adaece_fc_gc)
576
+ results['cece'].append(cece_fc_gc)
577
+ results['nll'].append(nll_fc_gc)
578
+ results['accuracy'].append(accuracy_fc_gc)
579
+
580
+
581
+ # print out a result table, drop the row index, decimal to 2
582
+ results_table = pd.DataFrame({
583
+ 'Model': args.model_name,
584
+ 'Dataset': args.dataset,
585
+ 'ECE': [round(i*100, 2) for i in results['ece']],
586
+ 'AdaECE': [round(i*100, 2) for i in results['adaece']],
587
+ 'CECE': [round(i*100, 2) for i in results['cece']],
588
+ 'NLL': [round(i*100, 2) for i in results['nll']],
589
+ 'Accuracy': [round(i*100, 2) for i in results['accuracy']]
590
+ }, index=results['cal'])
591
+ print("\n",results_table,"\n")
592
+
593
+ # # print latex scripts
594
+ # result_str = f"ECE Latex scipts: " \
595
+ # + f"{round(ece*100, 2):.2f}&\cellgray{round(ece_fc*100, 2):.2f}({round(C_opt_fc,2)}){' greendown' if ece_fc<ece else ' redup'}" \
596
+ # + f"&{round(ece_ts*100, 2):.2f}&\cellgray{round(ece_fc_ts*100, 2):.2f}{' greendown' if ece_fc_ts<ece_ts else ' redup'}" \
597
+ # + f"&{round(ece_ets*100, 2):.2f}&\cellgray{round(ece_fc_ets*100, 2):.2f}{' greendown' if ece_fc_ets<ece_ets else ' redup'}" \
598
+ # + f"&{round(ece_pts*100, 2):.2f}&\cellgray{round(ece_fc_pts*100, 2):.2f}{' greendown' if ece_fc_pts<ece_pts else ' redup'}" \
599
+ # + f"&{round(ece_cts*100, 2):.2f}&\cellgray{round(ece_fc_cts*100, 2):.2f}{' greendown' if ece_fc_cts<ece_cts else ' redup'}" \
600
+ # + f"&{round(ece_gc*100, 2):.2f}&\cellgray{round(ece_fc_gc*100, 2):.2f}{' greendown' if ece_fc_gc<ece_gc else ' redup'}" \
601
+ # + f"\\\\"
602
+ # # replace textcolor with \textcolor; replace blacktriangle with \blacktriangle
603
+ # result_str = result_str.replace('greendown', '\\greendown').replace('redup', '\\redup')
604
+ # # highlight the lowest results
605
+ # lowest_results = "{:.2f}".format(round(min(results['ece'])*100,2))
606
+ # result_str = result_str.replace(lowest_results, '\\textbf{'+lowest_results+'}')
607
+ # print(result_str)
608
+
609
+ # result_str = f"AdaECE Latex scipts: " \
610
+ # + f"{round(adaece*100, 2):.2f}&\cellgray{round(adaece_fc*100, 2):.2f}({round(C_opt_fc,2)}){' greendown' if adaece_fc<adaece else ' redup'}" \
611
+ # + f"&{round(adaece_ts*100, 2):.2f}&\cellgray{round(adaece_fc_ts*100, 2):.2f}{' greendown' if adaece_fc_ts<adaece_ts else ' redup'}" \
612
+ # + f"&{round(adaece_ets*100, 2):.2f}&\cellgray{round(adaece_fc_ets*100, 2):.2f}{' greendown' if adaece_fc_ets<adaece_ets else ' redup'}" \
613
+ # + f"&{round(adaece_pts*100, 2):.2f}&\cellgray{round(adaece_fc_pts*100, 2):.2f}{' greendown' if adaece_fc_pts<adaece_pts else ' redup'}" \
614
+ # + f"&{round(adaece_cts*100, 2):.2f}&\cellgray{round(adaece_fc_cts*100, 2):.2f}{' greendown' if adaece_fc_cts<adaece_cts else ' redup'}" \
615
+ # + f"&{round(adaece_gc*100, 2):.2f}&\cellgray{round(adaece_fc_gc*100, 2):.2f}{' greendown' if adaece_fc_gc<adaece_gc else ' redup'}" \
616
+ # + f"\\\\"
617
+ # # replace textcolor with \textcolor; replace blacktriangle with \blacktriangle
618
+ # result_str = result_str.replace('greendown', '\\greendown').replace('redup', '\\redup')
619
+ # # highlight the lowest results
620
+ # lowest_results = "{:.2f}".format(round(min(results['ece'])*100,2))
621
+ # result_str = result_str.replace(lowest_results, '\\textbf{'+lowest_results+'}')
622
+ # print(result_str)
AAAI2025-FC/evaluate_scripts_post_hoc.sh ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ conda activate feature-clipping
2
+
3
+ # cifar10
4
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar10 --model-name resnet50
5
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar10 --model-name resnet110
6
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar10 --model-name densenet121
7
+
8
+ # cifar100
9
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar100 --model-name resnet50
10
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar100 --model-name resnet110
11
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar100 --model-name densenet121
12
+
13
+ # imagenet
14
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset imagenet --model-name resnet50
15
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset imagenet --model-name densenet121
16
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset imagenet --model-name wide_resnet
17
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset imagenet --model-name mobilenet_v2
18
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset imagenet --model-name vit_l_16
AAAI2025-FC/evaluate_scripts_train_time.sh ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ conda activate feature-clipping
2
+
3
+ # cifar10
4
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar10 --model-name resnet50 --loss cross_entropy
5
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar10 --model-name resnet50 --loss brier_score
6
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar10 --model-name resnet50 --loss mmce
7
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar10 --model-name resnet50 --loss label_smoothing
8
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar10 --model-name resnet50 --loss focal_loss
9
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar10 --model-name resnet50 --loss focal_loss_53
10
+
11
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar10 --model-name resnet110 --loss cross_entropy
12
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar10 --model-name resnet110 --loss brier_score
13
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar10 --model-name resnet110 --loss mmce
14
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar10 --model-name resnet110 --loss label_smoothing
15
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar10 --model-name resnet110 --loss focal_loss
16
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar10 --model-name resnet110 --loss focal_loss_53
17
+
18
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar10 --model-name densenet121 --loss cross_entropy
19
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar10 --model-name densenet121 --loss brier_score
20
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar10 --model-name densenet121 --loss mmce
21
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar10 --model-name densenet121 --loss label_smoothing
22
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar10 --model-name densenet121 --loss focal_loss
23
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar10 --model-name densenet121 --loss focal_loss_53
24
+
25
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar10 --model-name wide_resnet --loss cross_entropy
26
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar10 --model-name wide_resnet --loss brier_score
27
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar10 --model-name wide_resnet --loss mmce
28
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar10 --model-name wide_resnet --loss label_smoothing
29
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar10 --model-name wide_resnet --loss focal_loss
30
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar10 --model-name wide_resnet --loss focal_loss_53
31
+
32
+
33
+
34
+
35
+
36
+ # # cifar100
37
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar100 --model-name resnet50 --loss cross_entropy
38
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar100 --model-name resnet50 --loss brier_score
39
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar100 --model-name resnet50 --loss mmce
40
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar100 --model-name resnet50 --loss label_smoothing
41
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar100 --model-name resnet50 --loss focal_loss
42
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar100 --model-name resnet50 --loss focal_loss_53
43
+
44
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar100 --model-name resnet110 --loss cross_entropy
45
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar100 --model-name resnet110 --loss brier_score
46
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar100 --model-name resnet110 --loss mmce
47
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar100 --model-name resnet110 --loss label_smoothing
48
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar100 --model-name resnet110 --loss focal_loss
49
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar100 --model-name resnet110 --loss focal_loss_53
50
+
51
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar100 --model-name densenet121 --loss cross_entropy
52
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar100 --model-name densenet121 --loss brier_score
53
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar100 --model-name densenet121 --loss mmce
54
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar100 --model-name densenet121 --loss label_smoothing
55
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar100 --model-name densenet121 --loss focal_loss
56
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar100 --model-name densenet121 --loss focal_loss_53
57
+
58
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar100 --model-name wide_resnet --loss cross_entropy
59
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar100 --model-name wide_resnet --loss brier_score
60
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar100 --model-name wide_resnet --loss mmce
61
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar100 --model-name wide_resnet --loss label_smoothing
62
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar100 --model-name wide_resnet --loss focal_loss
63
+ CUDA_VISIBLE_DEVICES=0 python evaluate.py --cverror nll --dataset cifar100 --model-name wide_resnet --loss focal_loss_53
AAAI2025-FC/losses/brier_score.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ Implementation of Brier Score.
3
+ '''
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ from torch.autograd import Variable
8
+
9
+ class BrierScore(nn.Module):
10
+ def __init__(self):
11
+ super(BrierScore, self).__init__()
12
+
13
+ def forward(self, input, target):
14
+ if input.dim()>2:
15
+ input = input.view(input.size(0),input.size(1),-1) # N,C,H,W => N,C,H*W
16
+ input = input.transpose(1,2) # N,C,H*W => N,H*W,C
17
+ input = input.contiguous().view(-1,input.size(2)) # N,H*W,C => N*H*W,C
18
+ target = target.view(-1,1)
19
+ target_one_hot = torch.FloatTensor(input.shape).to(target.get_device())
20
+ target_one_hot.zero_()
21
+ target_one_hot.scatter_(1, target, 1)
22
+
23
+ pt = F.softmax(input)
24
+ squared_diff = (target_one_hot - pt) ** 2
25
+
26
+ loss = torch.sum(squared_diff) / float(input.shape[0])
27
+ return loss
AAAI2025-FC/losses/focal_loss.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ Implementation of Focal Loss.
3
+ Reference:
4
+ [1] T.-Y. Lin, P. Goyal, R. Girshick, K. He, and P. Dollar, Focal loss for dense object detection.
5
+ arXiv preprint arXiv:1708.02002, 2017.
6
+ '''
7
+ import torch
8
+ import torch.nn as nn
9
+ import torch.nn.functional as F
10
+ from torch.autograd import Variable
11
+
12
+ class FocalLoss(nn.Module):
13
+ def __init__(self, gamma=0, size_average=False):
14
+ super(FocalLoss, self).__init__()
15
+ self.gamma = gamma
16
+ self.size_average = size_average
17
+
18
+ def forward(self, input, target):
19
+ if input.dim()>2:
20
+ input = input.view(input.size(0),input.size(1),-1) # N,C,H,W => N,C,H*W
21
+ input = input.transpose(1,2) # N,C,H*W => N,H*W,C
22
+ input = input.contiguous().view(-1,input.size(2)) # N,H*W,C => N*H*W,C
23
+ target = target.view(-1,1)
24
+
25
+ logpt = F.log_softmax(input)
26
+ logpt = logpt.gather(1,target)
27
+ logpt = logpt.view(-1)
28
+ pt = logpt.exp()
29
+
30
+ loss = -1 * (1-pt)**self.gamma * logpt
31
+ if self.size_average: return loss.mean()
32
+ else: return loss.sum()
AAAI2025-FC/losses/focal_loss_adaptive_gamma.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ Implementation of Focal Loss with adaptive gamma.
3
+ Reference:
4
+ [1] T.-Y. Lin, P. Goyal, R. Girshick, K. He, and P. Dollar, Focal loss for dense object detection.
5
+ arXiv preprint arXiv:1708.02002, 2017.
6
+ '''
7
+ import torch
8
+ import torch.nn as nn
9
+ import torch.nn.functional as F
10
+ from torch.autograd import Variable
11
+
12
+ from scipy.special import lambertw
13
+ import numpy as np
14
+
15
+
16
+ def get_gamma(p=0.2):
17
+ '''
18
+ Get the gamma for a given pt where the function g(p, gamma) = 1
19
+ '''
20
+ y = ((1-p)**(1-(1-p)/(p*np.log(p)))/(p*np.log(p)))*np.log(1-p)
21
+ gamma_complex = (1-p)/(p*np.log(p)) + lambertw(-y + 1e-12, k=-1)/np.log(1-p)
22
+ gamma = np.real(gamma_complex) #gamma for which p_t > p results in g(p_t,gamma)<1
23
+ return gamma
24
+
25
+ ps = [0.2, 0.5]
26
+ gammas = [5.0, 3.0]
27
+ i = 0
28
+ gamma_dic = {}
29
+ for p in ps:
30
+ gamma_dic[p] = gammas[i]
31
+ i += 1
32
+
33
+ class FocalLossAdaptive(nn.Module):
34
+ def __init__(self, gamma=0, size_average=False, device=None):
35
+ super(FocalLossAdaptive, self).__init__()
36
+ self.size_average = size_average
37
+ self.gamma = gamma
38
+ self.device = device
39
+
40
+ def get_gamma_list(self, pt):
41
+ gamma_list = []
42
+ batch_size = pt.shape[0]
43
+ for i in range(batch_size):
44
+ pt_sample = pt[i].item()
45
+ if (pt_sample >= 0.5):
46
+ gamma_list.append(self.gamma)
47
+ continue
48
+ # Choosing the gamma for the sample
49
+ for key in sorted(gamma_dic.keys()):
50
+ if pt_sample < key:
51
+ gamma_list.append(gamma_dic[key])
52
+ break
53
+ return torch.tensor(gamma_list).to(self.device)
54
+
55
+ def forward(self, input, target):
56
+ if input.dim()>2:
57
+ input = input.view(input.size(0),input.size(1),-1) # N,C,H,W => N,C,H*W
58
+ input = input.transpose(1,2) # N,C,H*W => N,H*W,C
59
+ input = input.contiguous().view(-1,input.size(2)) # N,H*W,C => N*H*W,C
60
+ target = target.view(-1,1)
61
+ logpt = F.log_softmax(input, dim=1)
62
+ logpt = logpt.gather(1,target)
63
+ logpt = logpt.view(-1)
64
+ pt = logpt.exp()
65
+ gamma = self.get_gamma_list(pt)
66
+ loss = -1 * (1-pt)**gamma * logpt
67
+ if self.size_average: return loss.mean()
68
+ else: return loss.sum()
AAAI2025-FC/losses/loss.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ Implementation of the following loss functions:
3
+ 1. Cross Entropy
4
+ 2. Focal Loss
5
+ 3. Cross Entropy + MMCE_weighted
6
+ 4. Cross Entropy + MMCE
7
+ 5. Brier Score
8
+ '''
9
+
10
+ from torch.nn import functional as F
11
+ from losses.focal_loss import FocalLoss
12
+ from losses.focal_loss_adaptive_gamma import FocalLossAdaptive
13
+ from losses.mmce import MMCE, MMCE_weighted
14
+ from losses.brier_score import BrierScore
15
+
16
+
17
+ def cross_entropy(logits, targets, **kwargs):
18
+ return F.cross_entropy(logits, targets, reduction='sum')
19
+
20
+
21
+ def focal_loss(logits, targets, **kwargs):
22
+ return FocalLoss(gamma=kwargs['gamma'])(logits, targets)
23
+
24
+
25
+ def focal_loss_adaptive(logits, targets, **kwargs):
26
+ return FocalLossAdaptive(gamma=kwargs['gamma'],
27
+ device=kwargs['device'])(logits, targets)
28
+
29
+
30
+ def mmce(logits, targets, **kwargs):
31
+ ce = F.cross_entropy(logits, targets)
32
+ mmce = MMCE(kwargs['device'])(logits, targets)
33
+ return ce + (kwargs['lamda'] * mmce)
34
+
35
+
36
+ def mmce_weighted(logits, targets, **kwargs):
37
+ ce = F.cross_entropy(logits, targets)
38
+ mmce = MMCE_weighted(kwargs['device'])(logits, targets)
39
+ return ce + (kwargs['lamda'] * mmce)
40
+
41
+
42
+ def brier_score(logits, targets, **kwargs):
43
+ return BrierScore()(logits, targets)
AAAI2025-FC/losses/mmce.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ Implementation of the MMCE (MMCE_m) and MMCE_weighted (MMCE_w).
3
+ Reference:
4
+ [1] A. Kumar, S. Sarawagi, U. Jain, Trainable Calibration Measures for Neural Networks from Kernel Mean Embeddings.
5
+ ICML, 2018.
6
+ '''
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+ import torch.nn.functional as F
11
+ from torch.autograd import Variable
12
+
13
+ class MMCE(nn.Module):
14
+ """
15
+ Computes MMCE_m loss.
16
+ """
17
+ def __init__(self, device):
18
+ super(MMCE, self).__init__()
19
+ self.device = device
20
+
21
+ def torch_kernel(self, matrix):
22
+ return torch.exp(-1.0*torch.abs(matrix[:, :, 0] - matrix[:, :, 1])/(0.4))
23
+
24
+ def forward(self, input, target):
25
+ if input.dim()>2:
26
+ input = input.view(input.size(0),input.size(1),-1) # N,C,H,W => N,C,H*W
27
+ input = input.transpose(1,2) # N,C,H*W => N,H*W,C
28
+ input = input.contiguous().view(-1,input.size(2)) # N,H*W,C => N*H*W,C
29
+
30
+ target = target.view(-1) #For CIFAR-10 and CIFAR-100, target.shape is [N] to begin with
31
+
32
+ predicted_probs = F.softmax(input, dim=1)
33
+ predicted_probs, pred_labels = torch.max(predicted_probs, 1)
34
+ correct_mask = torch.where(torch.eq(pred_labels, target),
35
+ torch.ones(pred_labels.shape).to(self.device),
36
+ torch.zeros(pred_labels.shape).to(self.device))
37
+
38
+ c_minus_r = correct_mask - predicted_probs
39
+
40
+ dot_product = torch.mm(c_minus_r.unsqueeze(1),
41
+ c_minus_r.unsqueeze(0))
42
+
43
+ prob_tiled = predicted_probs.unsqueeze(1).repeat(1, predicted_probs.shape[0]).unsqueeze(2)
44
+ prob_pairs = torch.cat([prob_tiled, prob_tiled.permute(1, 0, 2)],
45
+ dim=2)
46
+
47
+ kernel_prob_pairs = self.torch_kernel(prob_pairs)
48
+
49
+ numerator = dot_product*kernel_prob_pairs
50
+ #return torch.sum(numerator)/correct_mask.shape[0]**2
51
+ return torch.sum(numerator)/torch.pow(torch.tensor(correct_mask.shape[0]).type(torch.FloatTensor),2)
52
+
53
+
54
+
55
+ class MMCE_weighted(nn.Module):
56
+ """
57
+ Computes MMCE_w loss.
58
+ """
59
+ def __init__(self, device):
60
+ super(MMCE_weighted, self).__init__()
61
+ self.device = device
62
+
63
+ def torch_kernel(self, matrix):
64
+ return torch.exp(-1.0*torch.abs(matrix[:, :, 0] - matrix[:, :, 1])/(0.4))
65
+
66
+ def get_pairs(self, tensor1, tensor2):
67
+ correct_prob_tiled = tensor1.unsqueeze(1).repeat(1, tensor1.shape[0]).unsqueeze(2)
68
+ incorrect_prob_tiled = tensor2.unsqueeze(1).repeat(1, tensor2.shape[0]).unsqueeze(2)
69
+
70
+ correct_prob_pairs = torch.cat([correct_prob_tiled, correct_prob_tiled.permute(1, 0, 2)],
71
+ dim=2)
72
+ incorrect_prob_pairs = torch.cat([incorrect_prob_tiled, incorrect_prob_tiled.permute(1, 0, 2)],
73
+ dim=2)
74
+
75
+ correct_prob_tiled_1 = tensor1.unsqueeze(1).repeat(1, tensor2.shape[0]).unsqueeze(2)
76
+ incorrect_prob_tiled_1 = tensor2.unsqueeze(1).repeat(1, tensor1.shape[0]).unsqueeze(2)
77
+
78
+ correct_incorrect_pairs = torch.cat([correct_prob_tiled_1, incorrect_prob_tiled_1.permute(1, 0, 2)],
79
+ dim=2)
80
+ return correct_prob_pairs, incorrect_prob_pairs, correct_incorrect_pairs
81
+
82
+ def get_out_tensor(self, tensor1, tensor2):
83
+ return torch.mean(tensor1*tensor2)
84
+
85
+ def forward(self, input, target):
86
+ if input.dim()>2:
87
+ input = input.view(input.size(0),input.size(1),-1) # N,C,H,W => N,C,H*W
88
+ input = input.transpose(1,2) # N,C,H*W => N,H*W,C
89
+ input = input.contiguous().view(-1,input.size(2)) # N,H*W,C => N*H*W,C
90
+
91
+ target = target.view(-1) #For CIFAR-10 and CIFAR-100, target.shape is [N] to begin with
92
+
93
+ predicted_probs = F.softmax(input, dim=1)
94
+ predicted_probs, predicted_labels = torch.max(predicted_probs, 1)
95
+
96
+ correct_mask = torch.where(torch.eq(predicted_labels, target),
97
+ torch.ones(predicted_labels.shape).to(self.device),
98
+ torch.zeros(predicted_labels.shape).to(self.device))
99
+
100
+ k = torch.sum(correct_mask).type(torch.int64)
101
+ k_p = torch.sum(1.0 - correct_mask).type(torch.int64)
102
+ cond_k = torch.where(torch.eq(k,0),torch.tensor(0).to(self.device),torch.tensor(1).to(self.device))
103
+ cond_k_p = torch.where(torch.eq(k_p,0),torch.tensor(0).to(self.device),torch.tensor(1).to(self.device))
104
+ k = torch.max(k, torch.tensor(1).to(self.device))*cond_k*cond_k_p + (1 - cond_k*cond_k_p)*2
105
+ k_p = torch.max(k_p, torch.tensor(1).to(self.device))*cond_k_p*cond_k + ((1 - cond_k_p*cond_k)*
106
+ (correct_mask.shape[0] - 2))
107
+
108
+
109
+ correct_prob, _ = torch.topk(predicted_probs*correct_mask, k)
110
+ incorrect_prob, _ = torch.topk(predicted_probs*(1 - correct_mask), k_p)
111
+
112
+ correct_prob_pairs, incorrect_prob_pairs,\
113
+ correct_incorrect_pairs = self.get_pairs(correct_prob, incorrect_prob)
114
+
115
+ correct_kernel = self.torch_kernel(correct_prob_pairs)
116
+ incorrect_kernel = self.torch_kernel(incorrect_prob_pairs)
117
+ correct_incorrect_kernel = self.torch_kernel(correct_incorrect_pairs)
118
+
119
+ sampling_weights_correct = torch.mm((1.0 - correct_prob).unsqueeze(1), (1.0 - correct_prob).unsqueeze(0))
120
+
121
+ correct_correct_vals = self.get_out_tensor(correct_kernel,
122
+ sampling_weights_correct)
123
+ sampling_weights_incorrect = torch.mm(incorrect_prob.unsqueeze(1), incorrect_prob.unsqueeze(0))
124
+
125
+ incorrect_incorrect_vals = self.get_out_tensor(incorrect_kernel,
126
+ sampling_weights_incorrect)
127
+ sampling_correct_incorrect = torch.mm((1.0 - correct_prob).unsqueeze(1), incorrect_prob.unsqueeze(0))
128
+
129
+ correct_incorrect_vals = self.get_out_tensor(correct_incorrect_kernel,
130
+ sampling_correct_incorrect)
131
+
132
+ correct_denom = torch.sum(1.0 - correct_prob)
133
+ incorrect_denom = torch.sum(incorrect_prob)
134
+
135
+ m = torch.sum(correct_mask)
136
+ n = torch.sum(1.0 - correct_mask)
137
+ mmd_error = 1.0/(m*m + 1e-5) * torch.sum(correct_correct_vals)
138
+ mmd_error += 1.0/(n*n + 1e-5) * torch.sum(incorrect_incorrect_vals)
139
+ mmd_error -= 2.0/(m*n + 1e-5) * torch.sum(correct_incorrect_vals)
140
+ return torch.max((cond_k*cond_k_p).type(torch.FloatTensor).to(self.device).detach()*torch.sqrt(mmd_error + 1e-10), torch.tensor(0.0).to(self.device))
AAAI2025-FC/metrics/.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ __pycache__
AAAI2025-FC/metrics/__init__.py ADDED
File without changes
AAAI2025-FC/metrics/metrics.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ Metrics to measure calibration of a trained deep neural network.
3
+
4
+ References:
5
+ [1] C. Guo, G. Pleiss, Y. Sun, and K. Q. Weinberger. On calibration of modern neural networks.
6
+ arXiv preprint arXiv:1706.04599, 2017.
7
+ '''
8
+
9
+ import math
10
+ import torch
11
+ import numpy as np
12
+ from torch import nn
13
+ from torch.nn import functional as F
14
+
15
+
16
+ from sklearn.metrics import accuracy_score
17
+ from sklearn.metrics import confusion_matrix
18
+
19
+
20
+ # Some keys used for the following dictionaries
21
+ COUNT = 'count'
22
+ CONF = 'conf'
23
+ ACC = 'acc'
24
+ BIN_ACC = 'bin_acc'
25
+ BIN_CONF = 'bin_conf'
26
+
27
+
28
+ def _bin_initializer(bin_dict, num_bins=10):
29
+ for i in range(num_bins):
30
+ bin_dict[i][COUNT] = 0
31
+ bin_dict[i][CONF] = 0
32
+ bin_dict[i][ACC] = 0
33
+ bin_dict[i][BIN_ACC] = 0
34
+ bin_dict[i][BIN_CONF] = 0
35
+
36
+
37
+ def _populate_bins(confs, preds, labels, num_bins=10):
38
+ bin_dict = {}
39
+ for i in range(num_bins):
40
+ bin_dict[i] = {}
41
+ _bin_initializer(bin_dict, num_bins)
42
+ num_test_samples = len(confs)
43
+
44
+ for i in range(0, num_test_samples):
45
+ confidence = confs[i]
46
+ prediction = preds[i]
47
+ label = labels[i]
48
+ binn = int(math.ceil(((num_bins * confidence) - 1)))
49
+ bin_dict[binn][COUNT] = bin_dict[binn][COUNT] + 1
50
+ bin_dict[binn][CONF] = bin_dict[binn][CONF] + confidence
51
+ bin_dict[binn][ACC] = bin_dict[binn][ACC] + \
52
+ (1 if (label == prediction) else 0)
53
+
54
+ for binn in range(0, num_bins):
55
+ if (bin_dict[binn][COUNT] == 0):
56
+ bin_dict[binn][BIN_ACC] = 0
57
+ bin_dict[binn][BIN_CONF] = 0
58
+ else:
59
+ bin_dict[binn][BIN_ACC] = float(
60
+ bin_dict[binn][ACC]) / bin_dict[binn][COUNT]
61
+ bin_dict[binn][BIN_CONF] = bin_dict[binn][CONF] / \
62
+ float(bin_dict[binn][COUNT])
63
+ return bin_dict
64
+
65
+
66
+ def expected_calibration_error(confs, preds, labels, num_bins=10):
67
+ bin_dict = _populate_bins(confs, preds, labels, num_bins)
68
+ num_samples = len(labels)
69
+ ece = 0
70
+ for i in range(num_bins):
71
+ bin_accuracy = bin_dict[i][BIN_ACC]
72
+ bin_confidence = bin_dict[i][BIN_CONF]
73
+ bin_count = bin_dict[i][COUNT]
74
+ ece += (float(bin_count) / num_samples) * \
75
+ abs(bin_accuracy - bin_confidence)
76
+ return ece
77
+
78
+
79
+ def maximum_calibration_error(confs, preds, labels, num_bins=10):
80
+ bin_dict = _populate_bins(confs, preds, labels, num_bins)
81
+ ce = []
82
+ for i in range(num_bins):
83
+ bin_accuracy = bin_dict[i][BIN_ACC]
84
+ bin_confidence = bin_dict[i][BIN_CONF]
85
+ ce.append(abs(bin_accuracy - bin_confidence))
86
+ return max(ce)
87
+
88
+
89
+ def average_calibration_error(confs, preds, labels, num_bins=10):
90
+ bin_dict = _populate_bins(confs, preds, labels, num_bins)
91
+ non_empty_bins = 0
92
+ ace = 0
93
+ for i in range(num_bins):
94
+ bin_accuracy = bin_dict[i][BIN_ACC]
95
+ bin_confidence = bin_dict[i][BIN_CONF]
96
+ bin_count = bin_dict[i][COUNT]
97
+ if bin_count > 0:
98
+ non_empty_bins += 1
99
+ ace += abs(bin_accuracy - bin_confidence)
100
+ return ace / float(non_empty_bins)
101
+
102
+
103
+ def l2_error(confs, preds, labels, num_bins=15):
104
+ bin_dict = _populate_bins(confs, preds, labels, num_bins)
105
+ num_samples = len(labels)
106
+ l2_sum = 0
107
+ for i in range(num_bins):
108
+ bin_accuracy = bin_dict[i][BIN_ACC]
109
+ bin_confidence = bin_dict[i][BIN_CONF]
110
+ bin_count = bin_dict[i][COUNT]
111
+ l2_sum += (float(bin_count) / num_samples) * \
112
+ (bin_accuracy - bin_confidence)**2
113
+ l2_error = math.sqrt(l2_sum)
114
+ return l2_error
115
+
116
+
117
+ def test_classification_net_logits(logits, labels, probs=None):
118
+ '''
119
+ This function reports classification accuracy and confusion matrix given logits and labels
120
+ from a model.
121
+ '''
122
+ labels_list = []
123
+ predictions_list = []
124
+ confidence_vals_list = []
125
+
126
+ if logits is not None:
127
+ softmax = F.softmax(logits, dim=1)
128
+ else:
129
+ softmax = probs
130
+ confidence_vals, predictions = torch.max(softmax, dim=1)
131
+ labels_list.extend(labels.cpu().numpy().tolist())
132
+ predictions_list.extend(predictions.cpu().numpy().tolist())
133
+ confidence_vals_list.extend(confidence_vals.cpu().detach().numpy().tolist())
134
+ accuracy = accuracy_score(labels_list, predictions_list)
135
+ return confusion_matrix(labels_list, predictions_list), accuracy, labels_list,\
136
+ predictions_list, confidence_vals_list
137
+
138
+
139
+ def test_classification_net(model, data_loader, device):
140
+ '''
141
+ This function reports classification accuracy and confusion matrix over a dataset.
142
+ '''
143
+ model.eval()
144
+ labels_list = []
145
+ predictions_list = []
146
+ confidence_vals_list = []
147
+ with torch.no_grad():
148
+ for i, (data, label) in enumerate(data_loader):
149
+ data = data.to(device)
150
+ label = label.to(device)
151
+
152
+ logits = model(data)
153
+ softmax = F.softmax(logits, dim=1)
154
+ confidence_vals, predictions = torch.max(softmax, dim=1)
155
+
156
+ labels_list.extend(label.cpu().numpy().tolist())
157
+ predictions_list.extend(predictions.cpu().numpy().tolist())
158
+ confidence_vals_list.extend(confidence_vals.cpu().numpy().tolist())
159
+ accuracy = accuracy_score(labels_list, predictions_list)
160
+
161
+ return confusion_matrix(labels_list, predictions_list), accuracy, labels_list,\
162
+ predictions_list, confidence_vals_list
163
+
164
+
165
+ # Calibration error scores in the form of loss metrics
166
+ class ECELoss(nn.Module):
167
+ '''
168
+ Compute ECE (Expected Calibration Error)
169
+ '''
170
+ def __init__(self, n_bins=15):
171
+ super(ECELoss, self).__init__()
172
+ bin_boundaries = torch.linspace(0, 1, n_bins + 1)
173
+ self.bin_lowers = bin_boundaries[:-1]
174
+ self.bin_uppers = bin_boundaries[1:]
175
+
176
+ def forward(self, logits, labels, features=None, probs=None):
177
+ if logits is not None:
178
+ softmaxes = F.softmax(logits, dim=1)
179
+ else:
180
+ softmaxes = probs
181
+ confidences, predictions = torch.max(softmaxes, 1)
182
+ accuracies = predictions.eq(labels)
183
+ ce_per_sample = torch.zeros_like(confidences)
184
+
185
+ ece = torch.zeros(1, device=labels.device)
186
+ for bin_lower, bin_upper in zip(self.bin_lowers, self.bin_uppers):
187
+ # Calculated |confidence - accuracy| in each bin
188
+ in_bin = confidences.gt(bin_lower.item()) * confidences.le(bin_upper.item())
189
+ prop_in_bin = in_bin.float().mean()
190
+ if prop_in_bin.item() > 0:
191
+ accuracy_in_bin = accuracies[in_bin].float().mean()
192
+ avg_confidence_in_bin = confidences[in_bin].mean()
193
+
194
+ ### TODO
195
+ if bin_upper == 1:
196
+ # get all the index of in_bin data
197
+ indexs = torch.nonzero(in_bin).squeeze()
198
+ # # get the confidence values of in_bin data
199
+ # conf_in_bin = confidences[indexs]
200
+ # # get the index with high calibration error samples
201
+ # high_ce_indexs = torch.argsort(torch.abs(conf_in_bin - accuracy_in_bin), descending=True)
202
+ # # check the norm of the high calibration error samples
203
+ # norm_high_ce = torch.norm(conf_in_bin[high_ce_indexs], p=2)
204
+ # # get the indexs of wrongly classified samples
205
+ # wrong_indexs = torch.nonzero(accuracies.eq(0)).squeeze()
206
+ # # save to playground
207
+ # torch.save(in_bin, 'playground/in_bin.pth')
208
+ # torch.save(high_ce_indexs, 'playground/high_ce_indexs.pth')
209
+ # torch.save(wrong_indexs, 'playground/wrong_indexs.pth')
210
+ # torch.save(indexs, 'playground/indexs.pth')
211
+ # torch.save(features, 'playground/features.pth')
212
+ # torch.save(confidences, 'playground/confidences.pth')
213
+ ce_per_sample[in_bin]=torch.abs(confidences[in_bin] - accuracy_in_bin)
214
+ ece += torch.abs(avg_confidence_in_bin - accuracy_in_bin) * prop_in_bin
215
+ return ece
216
+
217
+
218
+ class AdaptiveECELoss(nn.Module):
219
+ '''
220
+ Compute Adaptive ECE
221
+ '''
222
+ def __init__(self, n_bins=15):
223
+ super(AdaptiveECELoss, self).__init__()
224
+ self.nbins = n_bins
225
+
226
+ def histedges_equalN(self, x):
227
+ npt = len(x)
228
+ return np.interp(np.linspace(0, npt, self.nbins + 1),
229
+ np.arange(npt),
230
+ np.sort(x))
231
+ def forward(self, logits, labels, probs=None):
232
+ if logits is not None:
233
+ softmaxes = F.softmax(logits, dim=1)
234
+ else:
235
+ softmaxes = probs
236
+ confidences, predictions = torch.max(softmaxes, 1)
237
+ accuracies = predictions.eq(labels)
238
+ n, bin_boundaries = np.histogram(confidences.cpu().detach(), self.histedges_equalN(confidences.cpu().detach()))
239
+ #print(n,confidences,bin_boundaries)
240
+ self.bin_lowers = bin_boundaries[:-1]
241
+ self.bin_uppers = bin_boundaries[1:]
242
+ ece = torch.zeros(1, device=labels.device)
243
+ for bin_lower, bin_upper in zip(self.bin_lowers, self.bin_uppers):
244
+ # Calculated |confidence - accuracy| in each bin
245
+ in_bin = confidences.gt(bin_lower.item()) * confidences.le(bin_upper.item())
246
+ prop_in_bin = in_bin.float().mean()
247
+ if prop_in_bin.item() > 0:
248
+ accuracy_in_bin = accuracies[in_bin].float().mean()
249
+ avg_confidence_in_bin = confidences[in_bin].mean()
250
+ ece += torch.abs(avg_confidence_in_bin - accuracy_in_bin) * prop_in_bin
251
+ return ece
252
+
253
+
254
+ class ClasswiseECELoss(nn.Module):
255
+ '''
256
+ Compute Classwise ECE
257
+ '''
258
+ def __init__(self, n_bins=15):
259
+ super(ClasswiseECELoss, self).__init__()
260
+ bin_boundaries = torch.linspace(0, 1, n_bins + 1)
261
+ self.bin_lowers = bin_boundaries[:-1]
262
+ self.bin_uppers = bin_boundaries[1:]
263
+
264
+ def forward(self, logits, labels, probs=None):
265
+ num_classes = int((torch.max(labels) + 1).item())
266
+ if logits is not None:
267
+ softmaxes = F.softmax(logits, dim=1)
268
+ else:
269
+ softmaxes = probs
270
+ per_class_sce = None
271
+
272
+ for i in range(num_classes):
273
+ class_confidences = softmaxes[:, i]
274
+ class_sce = torch.zeros(1, device=labels.device)
275
+ labels_in_class = labels.eq(i) # one-hot vector of all positions where the label belongs to the class i
276
+
277
+ for bin_lower, bin_upper in zip(self.bin_lowers, self.bin_uppers):
278
+ in_bin = class_confidences.gt(bin_lower.item()) * class_confidences.le(bin_upper.item())
279
+ prop_in_bin = in_bin.float().mean()
280
+ if prop_in_bin.item() > 0:
281
+ accuracy_in_bin = labels_in_class[in_bin].float().mean()
282
+ avg_confidence_in_bin = class_confidences[in_bin].mean()
283
+ class_sce += torch.abs(avg_confidence_in_bin - accuracy_in_bin) * prop_in_bin
284
+
285
+ if (i == 0):
286
+ per_class_sce = class_sce
287
+ else:
288
+ per_class_sce = torch.cat((per_class_sce, class_sce), dim=0)
289
+
290
+ sce = torch.mean(per_class_sce)
291
+ return sce
AAAI2025-FC/metrics/ood_test_utils.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Utility functions to get OOD detection ROC curves and AUROC scores
2
+ # Ideally should be agnostic of model architectures
3
+
4
+ import torch
5
+ import torch.nn.functional as F
6
+ from sklearn import metrics
7
+
8
+
9
+ def entropy(net_output):
10
+ p = F.softmax(net_output, dim=1)
11
+ logp = F.log_softmax(net_output, dim=1)
12
+ plogp = p * logp
13
+ entropy = - torch.sum(plogp, dim=1)
14
+ return entropy
15
+
16
+ def confidence(net_output):
17
+ p = F.softmax(net_output, dim=1)
18
+ confidence, _ = torch.max(p, dim=1)
19
+ return confidence
20
+
21
+
22
+ def get_roc_auc(net, test_loader, ood_test_loader, device):
23
+ bin_labels_entropies = None
24
+ bin_labels_confidences = None
25
+ entropies = None
26
+ confidences = None
27
+
28
+ net.eval()
29
+ with torch.no_grad():
30
+ # Getting entropies for in-distribution data
31
+ for i, (data, label) in enumerate(test_loader):
32
+ data = data.to(device)
33
+ label = label.to(device)
34
+
35
+ bin_label_entropy = torch.zeros(label.shape).to(device)
36
+ bin_label_confidence = torch.ones(label.shape).to(device)
37
+
38
+ net_output = net(data)
39
+
40
+ entrop = entropy(net_output)
41
+ conf = confidence(net_output)
42
+
43
+ if (i == 0):
44
+ bin_labels_entropies = bin_label_entropy
45
+ bin_labels_confidences = bin_label_confidence
46
+ entropies = entrop
47
+ confidences = conf
48
+ else:
49
+ bin_labels_entropies = torch.cat((bin_labels_entropies, bin_label_entropy))
50
+ bin_labels_confidences = torch.cat((bin_labels_confidences, bin_label_confidence))
51
+ entropies = torch.cat((entropies, entrop))
52
+ confidences = torch.cat((confidences, conf))
53
+
54
+ # Getting entropies for OOD data
55
+ for i, (data, label) in enumerate(ood_test_loader):
56
+ data = data.to(device)
57
+ label = label.to(device)
58
+
59
+ bin_label_entropy = torch.ones(label.shape).to(device)
60
+ bin_label_confidence = torch.zeros(label.shape).to(device)
61
+
62
+ net_output = net(data)
63
+ entrop = entropy(net_output)
64
+ conf = confidence(net_output)
65
+
66
+ bin_labels_entropies = torch.cat((bin_labels_entropies, bin_label_entropy))
67
+ bin_labels_confidences = torch.cat((bin_labels_confidences, bin_label_confidence))
68
+ entropies = torch.cat((entropies, entrop))
69
+ confidences = torch.cat((confidences, conf))
70
+
71
+ fpr_entropy, tpr_entropy, thresholds_entropy = metrics.roc_curve(bin_labels_entropies.cpu().numpy(), entropies.cpu().numpy())
72
+ fpr_confidence, tpr_confidence, thresholds_confidence = metrics.roc_curve(bin_labels_confidences.cpu().numpy(), confidences.cpu().numpy())
73
+ auc_entropy = metrics.roc_auc_score(bin_labels_entropies.cpu().numpy(), entropies.cpu().numpy())
74
+ auc_confidence = metrics.roc_auc_score(bin_labels_confidences.cpu().numpy(), confidences.cpu().numpy())
75
+
76
+ return (fpr_entropy, tpr_entropy, thresholds_entropy), (fpr_confidence, tpr_confidence, thresholds_confidence), auc_entropy, auc_confidence
AAAI2025-FC/metrics/plots.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ This file contains method for generating calibration related plots, eg. reliability plots.
3
+
4
+ References:
5
+ [1] C. Guo, G. Pleiss, Y. Sun, and K. Q. Weinberger. On calibration of modern neural networks.
6
+ arXiv preprint arXiv:1706.04599, 2017.
7
+ '''
8
+
9
+ import math
10
+ import matplotlib.pyplot as plt
11
+ plt.rcParams.update({'font.size': 20})
12
+
13
+ # Some keys used for the following dictionaries
14
+ COUNT = 'count'
15
+ CONF = 'conf'
16
+ ACC = 'acc'
17
+ BIN_ACC = 'bin_acc'
18
+ BIN_CONF = 'bin_conf'
19
+
20
+
21
+ def _bin_initializer(bin_dict, num_bins=10):
22
+ for i in range(num_bins):
23
+ bin_dict[i][COUNT] = 0
24
+ bin_dict[i][CONF] = 0
25
+ bin_dict[i][ACC] = 0
26
+ bin_dict[i][BIN_ACC] = 0
27
+ bin_dict[i][BIN_CONF] = 0
28
+
29
+
30
+ def _populate_bins(confs, preds, labels, num_bins=10):
31
+ bin_dict = {}
32
+ for i in range(num_bins):
33
+ bin_dict[i] = {}
34
+ _bin_initializer(bin_dict, num_bins)
35
+ num_test_samples = len(confs)
36
+
37
+ for i in range(0, num_test_samples):
38
+ confidence = confs[i]
39
+ prediction = preds[i]
40
+ label = labels[i]
41
+ binn = int(math.ceil(((num_bins * confidence) - 1)))
42
+ bin_dict[binn][COUNT] = bin_dict[binn][COUNT] + 1
43
+ bin_dict[binn][CONF] = bin_dict[binn][CONF] + confidence
44
+ bin_dict[binn][ACC] = bin_dict[binn][ACC] + \
45
+ (1 if (label == prediction) else 0)
46
+
47
+ for binn in range(0, num_bins):
48
+ if (bin_dict[binn][COUNT] == 0):
49
+ bin_dict[binn][BIN_ACC] = 0
50
+ bin_dict[binn][BIN_CONF] = 0
51
+ else:
52
+ bin_dict[binn][BIN_ACC] = float(
53
+ bin_dict[binn][ACC]) / bin_dict[binn][COUNT]
54
+ bin_dict[binn][BIN_CONF] = bin_dict[binn][CONF] / \
55
+ float(bin_dict[binn][COUNT])
56
+ return bin_dict
57
+
58
+
59
+ def reliability_plot(confs, preds, labels, num_bins=15):
60
+ '''
61
+ Method to draw a reliability plot from a model's predictions and confidences.
62
+ '''
63
+ bin_dict = _populate_bins(confs, preds, labels, num_bins)
64
+ bns = [(i / float(num_bins)) for i in range(num_bins)]
65
+ y = []
66
+ for i in range(num_bins):
67
+ y.append(bin_dict[i][BIN_ACC])
68
+ plt.figure(figsize=(10, 8)) # width:20, height:3
69
+ plt.bar(bns, bns, align='edge', width=0.05, color='pink', label='Expected')
70
+ plt.bar(bns, y, align='edge', width=0.05,
71
+ color='blue', alpha=0.5, label='Actual')
72
+ plt.ylabel('Accuracy')
73
+ plt.xlabel('Confidence')
74
+ plt.legend()
75
+ plt.show()
76
+
77
+
78
+ def bin_strength_plot(confs, preds, labels, num_bins=15):
79
+ '''
80
+ Method to draw a plot for the number of samples in each confidence bin.
81
+ '''
82
+ bin_dict = _populate_bins(confs, preds, labels, num_bins)
83
+ bns = [(i / float(num_bins)) for i in range(num_bins)]
84
+ num_samples = len(labels)
85
+ y = []
86
+ for i in range(num_bins):
87
+ n = (bin_dict[i][COUNT] / float(num_samples)) * 100
88
+ y.append(n)
89
+ plt.figure(figsize=(10, 8)) # width:20, height:3
90
+ plt.bar(bns, y, align='edge', width=0.05,
91
+ color='blue', alpha=0.5, label='Percentage samples')
92
+ plt.ylabel('Percentage of samples')
93
+ plt.xlabel('Confidence')
94
+ plt.show()
AAAI2025-FC/models/__init__.py ADDED
File without changes
AAAI2025-FC/models/densenet.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ Pytorch impplementation of DenseNet.
3
+
4
+ Reference:
5
+ [1] Gao Huang, Zhuang Liu, and Kilian Q. Weinberger. Densely connected convolutional networks.
6
+ arXiv preprint arXiv:1608.06993, 2016a.
7
+ '''
8
+
9
+ import math
10
+
11
+ import torch
12
+ import torch.nn as nn
13
+ import torch.nn.functional as F
14
+
15
+
16
+ class Bottleneck(nn.Module):
17
+ def __init__(self, in_planes, growth_rate):
18
+ super(Bottleneck, self).__init__()
19
+ self.bn1 = nn.BatchNorm2d(in_planes)
20
+ self.conv1 = nn.Conv2d(in_planes, 4*growth_rate, kernel_size=1, bias=False)
21
+ self.bn2 = nn.BatchNorm2d(4*growth_rate)
22
+ self.conv2 = nn.Conv2d(4*growth_rate, growth_rate, kernel_size=3, padding=1, bias=False)
23
+
24
+ def forward(self, x):
25
+ out = self.conv1(F.relu(self.bn1(x)))
26
+ out = self.conv2(F.relu(self.bn2(out)))
27
+ out = torch.cat([out,x], 1)
28
+ return out
29
+
30
+
31
+ class Transition(nn.Module):
32
+ def __init__(self, in_planes, out_planes):
33
+ super(Transition, self).__init__()
34
+ self.bn = nn.BatchNorm2d(in_planes)
35
+ self.conv = nn.Conv2d(in_planes, out_planes, kernel_size=1, bias=False)
36
+
37
+ def forward(self, x):
38
+ out = self.conv(F.relu(self.bn(x)))
39
+ out = F.avg_pool2d(out, 2)
40
+ return out
41
+
42
+
43
+ class DenseNet(nn.Module):
44
+ def __init__(self, block, nblocks, growth_rate=12, reduction=0.5, num_classes=10, temp=1.0, feature_clamp=1e6):
45
+ super(DenseNet, self).__init__()
46
+ self.growth_rate = growth_rate
47
+ self.temp = temp
48
+
49
+ num_planes = 2*growth_rate
50
+ self.conv1 = nn.Conv2d(3, num_planes, kernel_size=3, padding=1, bias=False)
51
+
52
+ self.dense1 = self._make_dense_layers(block, num_planes, nblocks[0])
53
+ num_planes += nblocks[0]*growth_rate
54
+ out_planes = int(math.floor(num_planes*reduction))
55
+ self.trans1 = Transition(num_planes, out_planes)
56
+ num_planes = out_planes
57
+
58
+ self.dense2 = self._make_dense_layers(block, num_planes, nblocks[1])
59
+ num_planes += nblocks[1]*growth_rate
60
+ out_planes = int(math.floor(num_planes*reduction))
61
+ self.trans2 = Transition(num_planes, out_planes)
62
+ num_planes = out_planes
63
+
64
+ self.dense3 = self._make_dense_layers(block, num_planes, nblocks[2])
65
+ num_planes += nblocks[2]*growth_rate
66
+ out_planes = int(math.floor(num_planes*reduction))
67
+ self.trans3 = Transition(num_planes, out_planes)
68
+ num_planes = out_planes
69
+
70
+ self.dense4 = self._make_dense_layers(block, num_planes, nblocks[3])
71
+ num_planes += nblocks[3]*growth_rate
72
+
73
+ self.bn = nn.BatchNorm2d(num_planes)
74
+ self.linear = nn.Linear(num_planes, num_classes)
75
+ self.feature_clamp = feature_clamp
76
+
77
+ def _make_dense_layers(self, block, in_planes, nblock):
78
+ layers = []
79
+ for i in range(nblock):
80
+ layers.append(block(in_planes, self.growth_rate))
81
+ in_planes += self.growth_rate
82
+ return nn.Sequential(*layers)
83
+
84
+ def forward(self, x, return_feature=False):
85
+ out = self.conv1(x)
86
+ out = self.trans1(self.dense1(out))
87
+ out = self.trans2(self.dense2(out))
88
+ out = self.trans3(self.dense3(out))
89
+ out = self.dense4(out)
90
+ out = F.avg_pool2d(F.relu(self.bn(out)), 4)
91
+ feature = out.view(out.size(0), -1)
92
+ out = self.linear(feature) / self.temp
93
+ if return_feature:
94
+ return out, feature
95
+ else:
96
+ return out
97
+
98
+
99
+ def classifier(self, x):
100
+ return self.linear(x)
101
+
102
+
103
+
104
+ def densenet121(temp=1.0, **kwargs):
105
+ return DenseNet(Bottleneck, [6,12,24,16], growth_rate=32, temp=temp, **kwargs)
106
+
107
+
108
+ def densenet169(temp=1.0, **kwargs):
109
+ return DenseNet(Bottleneck, [6,12,32,32], growth_rate=32, temp=temp, **kwargs)
110
+
111
+
112
+ def densenet201(temp=1.0, **kwargs):
113
+ return DenseNet(Bottleneck, [6,12,48,32], growth_rate=32, temp=temp, **kwargs)
114
+
115
+
116
+ def densenet161(temp=1.0, **kwargs):
117
+ return DenseNet(Bottleneck, [6,12,36,24], growth_rate=48, temp=temp, **kwargs)