-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample.py
235 lines (213 loc) · 9 KB
/
example.py
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
################################################################################
# Copyright (c) 2023 Paolo Cudrano. #
# Copyrights licensed under the MIT License. #
# See the accompanying LICENSE file for terms. #
# #
# Date: 03-07-2023 #
# Author(s): Paolo Cudrano #
# E-mail: paolo.cudrano@polimi.it #
# #
# Adapted from code under: #
# Copyright (c) 2021 ContinualAI. #
# Copyrights licensed under the MIT License. #
# See the accompanying LICENSE file for terms. #
# #
# Date: 30-12-2020 #
# Author(s): Lorenzo Pellegrini #
# E-mail: contact@continualai.org #
# Website: www.continualai.org #
################################################################################
"""
This is a simple example on how to use the Evaluation Plugin.
"""
import torch
import argparse
from torch.nn import CrossEntropyLoss
from torch.optim import SGD
from torchvision import transforms
from torchvision.datasets import MNIST
from torchvision.transforms import ToTensor, RandomCrop
from avalanche.benchmarks import nc_benchmark
from avalanche.benchmarks.classic import PermutedMNIST, RotatedMNIST, SplitMNIST
from avalanche.benchmarks.datasets.dataset_utils import default_dataset_location
from avalanche.evaluation.metrics import (
forgetting_metrics,
accuracy_metrics,
labels_repartition_metrics,
loss_metrics,
cpu_usage_metrics,
timing_metrics,
gpu_usage_metrics,
ram_usage_metrics,
disk_usage_metrics,
MAC_metrics,
bwt_metrics,
forward_transfer_metrics,
class_accuracy_metrics,
amca_metrics,
)
from avalanche.models import SimpleMLP
from avalanche.logging import (
InteractiveLogger,
TextLogger,
CSVLogger,
TensorboardLogger,
)
from avalanche.training.plugins import EvaluationPlugin
from avalanche.training.supervised import Naive
from evaluation.metrics.torchmetrics_metrics import *
from evaluation.metrics.sklearn_metrics import *
import torchmetrics
import sklearn.metrics as skmetrics
def main(args):
# --- CONFIG
device = torch.device(
f"cuda:{args.cuda}" if torch.cuda.is_available() and args.cuda >= 0 else "cpu"
)
# ---------
print(device)
n_classes = 10
benchmark = PermutedMNIST(n_experiences=5, seed=1)
# MODEL CREATION
model = SimpleMLP(num_classes=n_classes)
# DEFINE THE EVALUATION PLUGIN AND LOGGER
# The evaluation plugin manages the metrics computation.
# It takes as argument a list of metrics and a list of loggers.
# The evaluation plugin calls the loggers to serialize the metrics
# and save them in persistent memory or print them in the standard output.
# log to text file
text_logger = TextLogger(open("./log.txt", "a"))
# print to stdout
interactive_logger = InteractiveLogger()
csv_logger = CSVLogger()
tb_logger = TensorboardLogger()
eval_plugin = EvaluationPlugin(
accuracy_metrics(
minibatch=True,
epoch=True,
epoch_running=True,
experience=True,
stream=True,
),
loss_metrics(
minibatch=True,
epoch=True,
epoch_running=True,
experience=True,
stream=True,
),
torchmetrics_metrics(torchmetrics.F1Score, task="multiclass", num_classes=n_classes, threshold=0.5,
minibatch=True,
epoch=True,
epoch_running=True,
experience=True,
stream=True
),
torchmetrics_metrics(torchmetrics.AUROC, task="multiclass", num_classes=n_classes, thresholds=200,
minibatch=True,
epoch=True,
epoch_running=True,
experience=True,
stream=True
),
torchmetrics_metrics(torchmetrics.Precision, task="multiclass", num_classes=n_classes, threshold=0.5,
minibatch=True,
epoch=True,
epoch_running=True,
experience=True,
stream=True
),
torchmetrics_metrics(torchmetrics.Recall, task="multiclass", num_classes=n_classes, threshold=0.5,
minibatch=True,
epoch=True,
epoch_running=True,
experience=True,
stream=True
),
sklearn_metrics(skmetrics.roc_auc_score, average='macro', multi_class='ovr',
use_logits=True, running_average=False, regression=False,
minibatch=True,
epoch=True,
epoch_running=True,
experience=True,
stream=True
),
sklearn_metrics(skmetrics.f1_score, average='micro',
use_logits=False, running_average=False,
minibatch=True,
epoch=True,
epoch_running=True,
experience=True,
stream=True
),
sklearn_metrics(skmetrics.precision_score, average='micro',
use_logits=False, running_average=False, regression=False,
minibatch=True,
epoch=True,
epoch_running=True,
experience=True,
stream=True
),
sklearn_metrics(skmetrics.recall_score, average='micro',
use_logits=False, running_average=False, regression=False,
minibatch=True,
epoch=True,
epoch_running=True,
experience=True,
stream=True
),
sklearn_metrics(skmetrics.accuracy_score,
use_logits=False, running_average=False, regression=False,
minibatch=True,
epoch=True,
epoch_running=True,
experience=True,
stream=True
),
loggers=[interactive_logger, text_logger, csv_logger, tb_logger],
collect_all=True,
) # collect all metrics (set to True by default)
# CREATE THE STRATEGY INSTANCE (NAIVE)
cl_strategy = Naive(
model,
SGD(model.parameters(), lr=0.01, momentum=0.9),
CrossEntropyLoss(),
train_mb_size=512,
train_epochs=1,
eval_mb_size=512,
device=device,
evaluator=eval_plugin,
eval_every=1,
)
# TRAINING LOOP
print("Starting experiment...")
results = []
for i, experience in enumerate(benchmark.train_stream):
print("Start of experience: ", experience.current_experience)
print("Current Classes: ", experience.classes_in_this_experience)
# train returns a dictionary containing last recorded value
# for each metric.
res = cl_strategy.train(experience) # , eval_streams=[benchmark.test_stream])
print("Training completed")
print("Computing accuracy on the whole test set")
# test returns a dictionary with the last metric collected during
# evaluation on that stream
results.append(cl_strategy.eval(benchmark.test_stream))
print(f"Test metrics:\n{results}")
# Dict with all the metric curves,
# only available when `collect_all` is True.
# Each entry is a (x, metric value) tuple.
# You can use this dictionary to manipulate the
# metrics without avalanche.
all_metrics = cl_strategy.evaluator.get_all_metrics()
print(f"Stored metrics: {list(all_metrics.keys())}")
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"--cuda",
type=int,
default=0,
help="Select zero-indexed cuda device. -1 to use CPU.",
)
args = parser.parse_args()
main(args)