Skip to content

Commit ced97ec

Browse files
Jianguo99Shinning-Zhoujanqsong
authored
Version 1.0.3 (#80)
* docs: update prefixes * add normalize residual score in regression (#68) * 🐞 fix(classification.utils.metrics): fix covgap Fix CovGap calculation to only consider existing labels' coverage gap * fix vioclasses and covgap metric * add norabs score for regression * add test for norabs score * fix norabs score * update readme.md for regression * Feature/optimized cp (#67) * feat: optimized_cp * fix(classification): fix bug of optimized cp * refactor(classification): refactor loss of optimized cp * delete(examples): delete the example of optimized cp * docs(classification): annotation of scpo * docs(readme): add scpo to classification * Feature/rc3p (#65) * add RC3P * update info of RC3P in the readme.md * Add EntmaxScore module to the classification score (#64) * Add EntmaxScore module to the classification score * add the reference of entmax inREADME.md * add AgACI algorithm in regression (#44) * update agaci algorithm * 🧪 test(regression.predictor.agaci) * update agaci in README.md * update TODO in README.md --------- Co-authored-by: Jianguo Huang <80951029+Jianguo99@users.noreply.github.com> * hotfix(metric): add criteria of efficiency for cp (#69) * hotfix(metric): add criteria of efficiency for cp * fix(p_values) * fix(pvalue): add smooth switch * docs(metrics for pvalue): add annotations * fix(pvalue): add smooth switch * docs(readme): rectify the venue * Revert "fix(pvalue): add smooth switch" This reverts commit c7e0c85. * Revert "Revert "fix(pvalue): add smooth switch"" This reverts commit ba67945. * Revert "docs(readme): rectify the venue" This reverts commit f305aeb. * test(metric_pvalue): add test for metric of pvalue * fix(metric_pvalue): fix smooth * test(scpo): add test for optimized cp * fix(device): the default device is cpu * refactor(device): * test(device): fix test * fix(test): fix test coverage * change name "THR" to "LAC" (#71) * change name "THR" to "LAC" * change classwise to classconditional and update the reference of ABS score * update class_conditioanl.py * update test_scpo (#72) * add online_classification (#73) * add online examples (#74) * add online examples * fix online regression example * fix online regression examples * Refactor/predictor alpha (#75) * refactor(predictor): classification and graph * refactor(predictor): change the position of alpha in __init__ * refactor(test): add test for predictor of classification, graph, llm * refactor(regression): refactor predictors, add alpha in the init * fix(examples): timeseries aci synthetic * Revise trainer (#76) * revise trainer * revise trainer * Feature/contr trainer (#77) * add ConfTrTrainer * add example, test, annotation of conftr * fix(examples): fix the example of conftr --------- Co-authored-by: jianguo.huang <jianguo.huang@ntu.edu.sg> * rename (#78) * rename * update conftr_cifar100 exmaple * Update/info 1.0.3 (#79) * update changelog * update .rst --------- Co-authored-by: Xuanning Zhou <shinning_zhou@163.com> Co-authored-by: Jianqing Song <45555860+janqsong@users.noreply.github.com> Co-authored-by: janqsong <janqsong@gmail.com>
1 parent 20c1d5f commit ced97ec

94 files changed

Lines changed: 2899 additions & 399 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

.gitignore

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,4 +25,6 @@ docs/buildA
2525
**/__pycache__/
2626
.vscode
2727
.coverage
28-
torch_scae.egg-info
28+
torch_scae.egg-info
29+
*.so
30+
*.egg-info

README.md

Lines changed: 34 additions & 15 deletions
Large diffs are not rendered by default.

docs/source/CHANGELOG.rst

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,15 @@
11
Changelog
22
=========
33

4+
1.0.4 (2025-07-10)
5+
------------------
6+
* Refactored `__init__` of predictors to include `alpha` and `device` parameters for greater flexibility.
7+
* Added EntmaxScore, SCPO and RC3P methods for classification tasks.
8+
* Added the normalized residual score in regression task.
9+
* Added p-value computation and efficiency metrics from the paper "Criteria of Efficiency for Conformal Prediction".
10+
11+
12+
413
1.0.2 (2025-02-17)
514
------------------
615
* Refactored examples codebase for better organization and clarity
@@ -48,5 +57,5 @@ Changelog
4857

4958
0.1.0 (2023-12-23)
5059
------------------
51-
* Introduced CP algorithms for classification, including ConfTr, THR, APS, RAPS, SAPS, Classwise CP, Clustered CP and Weighted CP.
60+
* Introduced CP algorithms for classification, including ConfTr, LAC, APS, RAPS, SAPS, ClassConditional CP, Clustered CP and Weighted CP.
5261
* Introduced CP algorithms for regression, including ACI, ABS and CQR.

docs/source/installation.rst

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
Installation
22
=====================
3+
34
Latest version (|version|)
4-
---------------------
5+
--------------------------
56

67
Installing TorchCP itself
78

docs/source/torchcp.classification.rst

Lines changed: 34 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,16 +12,17 @@ score function
1212
.. autosummary::
1313
:nosignatures:
1414

15-
THR
15+
LAC
1616
APS
1717
RAPS
1818
SAPS
1919
Margin
2020
TOPK
2121
KNN
22+
EntmaxScore
2223

2324

24-
.. autoclass:: THR
25+
.. autoclass:: LAC
2526
:members:
2627

2728
.. autoclass:: APS
@@ -42,6 +43,10 @@ score function
4243
.. autoclass:: KNN
4344
:members:
4445

46+
.. autoclass:: EntmaxScore
47+
:members:
48+
49+
4550
.. automodule:: torchcp.classification.predictor
4651

4752
predictor
@@ -51,23 +56,28 @@ predictor
5156
:nosignatures:
5257

5358
SplitPredictor
54-
ClassWisePredictor
59+
ClassConditionalPredictor
5560
ClusteredPredictor
61+
RC3PPredictor
5662
WeightedPredictor
5763

5864
.. autoclass:: SplitPredictor
5965
:members:
6066

61-
.. autoclass:: ClassWisePredictor
67+
.. autoclass:: ClassConditionalPredictor
6268
:members:
6369

6470
.. autoclass:: ClusteredPredictor
6571
:members:
6672

73+
.. autoclass:: RC3PPredictor
74+
:members:
75+
6776
.. autoclass:: WeightedPredictor
6877
:members:
6978

7079

80+
7181
.. automodule:: torchcp.classification.loss
7282

7383
loss function
@@ -106,6 +116,8 @@ trainer
106116
TSTrainer
107117
OrdinalTrainer
108118
UncertaintyAwareTrainer
119+
SCPOTrainer
120+
109121

110122
.. autoclass:: BaseTrainer
111123
:members:
@@ -122,6 +134,10 @@ trainer
122134
.. autoclass:: UncertaintyAwareTrainer
123135
:members:
124136

137+
.. autoclass:: SCPOTrainer
138+
:members:
139+
140+
125141
.. automodule:: torchcp.classification.utils.metrics
126142

127143
metrics
@@ -146,6 +162,20 @@ metrics
146162
.. autofunction:: SSCV
147163
.. autofunction:: WSC
148164
.. autofunction:: singleton_hit_ratio
165+
.. autofunction:: compute_p_values
166+
.. autofunction:: pvalue_criterion_S
167+
.. autofunction:: pvalue_criterion_N
168+
.. autofunction:: pvalue_criterion_U
169+
.. autofunction:: pvalue_criterion_F
170+
.. autofunction:: pvalue_criterion_M
171+
.. autofunction:: pvalue_criterion_E
172+
.. autofunction:: pvalue_criterion_OU
173+
.. autofunction:: pvalue_criterion_OF
174+
.. autofunction:: pvalue_criterion_OM
175+
.. autofunction:: pvalue_criterion_OE
176+
177+
178+
149179

150180
.. automodule:: torchcp.classification.utils
151181

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
# Copyright (c) 2023-present, SUSTech-ML.
2+
# All rights reserved.
3+
#
4+
# This source code is licensed under the license found in the
5+
# LICENSE file in the root directory of this source tree.
6+
#
7+
8+
import torch
9+
import torchvision
10+
import torchvision.transforms as trn
11+
from transformers import set_seed
12+
13+
from examples.utils import get_dataset_dir
14+
from torchcp.classification.predictor import SplitPredictor
15+
from torchcp.classification.score import LAC
16+
from torchcp.classification.trainer import ConfTrTrainer
17+
18+
set_seed(seed=2025)
19+
20+
#######################################
21+
# Preparing a calibration data and a test data
22+
#######################################
23+
transform = trn.Compose([
24+
trn.ToTensor(),
25+
trn.Normalize(mean=[0.5071, 0.4867, 0.4408],
26+
std=[0.2675, 0.2565, 0.2761])
27+
])
28+
dataset = torchvision.datasets.CIFAR100(
29+
root=get_dataset_dir(),
30+
train=False,
31+
download=True,
32+
transform=transform
33+
)
34+
train_dataset, cal_dataset, test_dataset = torch.utils.data.random_split(dataset, [3000, 2000, 5000])
35+
train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=64, shuffle=True, num_workers=4, pin_memory=True)
36+
cal_dataloader = torch.utils.data.DataLoader(cal_dataset, batch_size=64, shuffle=False, num_workers=4, pin_memory=True)
37+
test_dataloader = torch.utils.data.DataLoader(test_dataset, batch_size=64, shuffle=False, num_workers=4,
38+
pin_memory=True)
39+
test_instance, test_label = test_dataset[0]
40+
test_instance = test_instance.unsqueeze(0)
41+
42+
#######################################
43+
# Preparing a pytorch model
44+
#######################################
45+
init_model = torch.hub.load("chenyaofo/pytorch-cifar-models", "cifar100_resnet20", pretrained=True)
46+
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
47+
init_model.to(device)
48+
init_model.eval()
49+
50+
#######################################
51+
# Conformal Training
52+
#######################################
53+
54+
trainer = ConfTrTrainer(
55+
model=init_model,
56+
alpha=0.1,
57+
device=device
58+
)
59+
60+
trained_model = trainer.train(train_dataloader, num_epochs=10)
61+
62+
########################################
63+
# Conformal prediction
64+
########################################
65+
66+
predictor = SplitPredictor(score_function=LAC(), model=trained_model, alpha=0.1)
67+
predictor.calibrate(cal_dataloader)
68+
predict_set = predictor.predict(test_instance)
69+

examples/classification_confts_cifar100.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,9 +52,9 @@
5252
init_temperature = 1.0
5353

5454
trainer = ConfTSTrainer(
55+
model=model,
5556
init_temperature=init_temperature,
5657
alpha=0.1,
57-
model=model,
5858
device=device,
5959
verbose=True
6060
)

examples/classification_splitcp_cifar100.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@
1212

1313
from examples.utils import get_dataset_dir
1414
from torchcp.classification.predictor import SplitPredictor
15-
from torchcp.classification.score import THR
15+
from torchcp.classification.predictor import RC3PPredictor, ClassConditionalPredictor
16+
from torchcp.classification.score import LAC
1617

1718
set_seed(seed=0)
1819

@@ -47,7 +48,8 @@
4748
# A standard process of conformal prediction
4849
#######################################
4950
alpha = 0.1 # Significance level
50-
predictor = SplitPredictor(score_function=THR(), model=model)
51+
predictor = SplitPredictor(score_function=LAC(), model=model)
52+
# predictor = ClassConditionalPredictor(score_function=LAC(), model=model)
5153
predictor.calibrate(cal_dataloader, alpha=0.1)
5254

5355
test_instances, test_labels = test_dataset[0]
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
import torch
2+
import torchvision
3+
import torchvision.transforms as trn
4+
from transformers import set_seed
5+
from tqdm import tqdm
6+
7+
from examples.utils import get_dataset_dir
8+
from torchcp.classification.predictor import SplitPredictor
9+
from torchcp.classification.score import LAC
10+
11+
set_seed(seed=0)
12+
13+
#######################################
14+
# Dataset preparation
15+
#######################################
16+
transform = trn.Compose([
17+
trn.ToTensor(),
18+
trn.Normalize(mean=[0.5071, 0.4867, 0.4408],
19+
std=[0.2675, 0.2565, 0.2761])
20+
])
21+
22+
dataset = torchvision.datasets.CIFAR100(
23+
root=get_dataset_dir(),
24+
train=False,
25+
download=True,
26+
transform=transform
27+
)
28+
cal_dataset, test_dataset = torch.utils.data.random_split(dataset, [5000, 5000])
29+
30+
#######################################
31+
# Model preparation
32+
#######################################
33+
model = torch.hub.load("chenyaofo/pytorch-cifar-models", "cifar100_resnet20", pretrained=True)
34+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
35+
model.to(device)
36+
model.eval()
37+
38+
cal_logits, cal_labels = [], []
39+
for x, y in cal_dataset:
40+
cal_logits.append(model(x.unsqueeze(0).to(device)))
41+
cal_labels.append(y)
42+
43+
cal_logits = torch.cat(cal_logits, dim=0)
44+
cal_labels = torch.tensor(cal_labels)
45+
46+
47+
test_logits, test_labels = [], []
48+
for x, y in test_dataset:
49+
test_logits.append(model(x.unsqueeze(0).to(device)))
50+
test_labels.append(y)
51+
52+
test_logits = torch.cat(test_logits, dim=0)
53+
test_labels = torch.tensor(test_labels)
54+
55+
#######################################
56+
# Online Conformal Prediction
57+
#######################################
58+
alpha = 0.1
59+
60+
predictor = SplitPredictor(score_function=LAC(), model=model, device=device)
61+
62+
cover_count = 0
63+
total = 0
64+
set_size_sum = 0
65+
66+
for i in tqdm(range(len(test_dataset))):
67+
predictor.calculate_threshold(cal_logits, cal_labels, alpha)
68+
69+
x, y = test_dataset[i]
70+
logits = model(x.unsqueeze(0).to(device))
71+
72+
73+
pred_set = predictor.predict_with_logits(logits)[0]
74+
covered = 1 if pred_set[y] else 0
75+
76+
cover_count += int(covered)
77+
set_size_sum += pred_set.sum()
78+
total += 1
79+
80+
cal_logits = torch.cat((cal_logits, logits), dim=0)
81+
cal_labels = torch.cat((cal_labels, torch.tensor([y])), dim=0)
82+
83+
coverage_rate = cover_count / total
84+
average_set_size = set_size_sum / total
85+
86+
print(f"Online CP Coverage Rate: {coverage_rate:.4f}")
87+
print(f"Online CP Average Set Size: {average_set_size:.4f}")

examples/gnn_trainer_coraml.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ def train(model, optimizer, graph_data, train_idx):
107107
graph_data['train_idx'] = train_idx
108108
graph_data['val_idx'] = test_idx
109109
graph_data['calib_train_idx'] = calib_train_idx
110-
cf_trainer = CFGNNTrainer(graph_data, model)
110+
cf_trainer = CFGNNTrainer(model, graph_data)
111111

112112
# Train conformalized gnn
113113
model = cf_trainer.train()

0 commit comments

Comments
 (0)