Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

experiment_manager.py 20 KB

You have to be logged in to leave a comment. Sign In
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
  1. import abc
  2. import csv
  3. import os
  4. import time
  5. import tensorflow as tf
  6. import numpy as np
  7. from datetime import datetime
  8. from sklearn.metrics import f1_score
  9. from src.model.mnist_model import MNISTModel
  10. from src.model.cifar10_model import Cifar10Model
  11. from src.sampler import (
  12. ALRandomSampler,
  13. LeastConfidenceSampler,
  14. UCBBanditSampler
  15. )
  16. from src.utils.log_utils import (
  17. set_up_experiment_logging,
  18. time_display,
  19. )
  20. from src.utils.utils import (
  21. batch_sample_indices,
  22. )
  23. config = tf.compat.v1.ConfigProto()
  24. config.gpu_options.allow_growth = True
  25. session = tf.compat.v1.Session(config=config)
  26. class ActiveLearningExperimentManagerT(abc.ABC):
  27. """
  28. - handles managing data set
  29. - interface between model and raw data
  30. - logging
  31. - model generation
  32. """
  33. def __init__(self, args):
  34. self.args = args
  35. # these don't change run to run
  36. self._init_data()
  37. self.optimizer = self._get_optimizer()
  38. self.loss_fn = self._get_loss()
  39. # we only seed once
  40. tf.random.set_seed(args.seed)
  41. np.random.seed(args.seed)
  42. # these are none until you call _init_experiment
  43. self.logger = None
  44. self.tf_summary_writer = None
  45. self.model = None
  46. self.start_time = None
  47. self.run_dir = None
  48. self.AL_sampler = None
  49. def _init_data(self) -> None:
  50. args = self.args
  51. if args.dataset == "mnist":
  52. # loads from keras cache
  53. (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
  54. # normalizes the features
  55. x_train, x_test = x_train[..., np.newaxis]/255.0, x_test[..., np.newaxis]/255.0
  56. elif args.dataset == "cifar10":
  57. (x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()
  58. # Normalize pixel values to be between 0 and 1
  59. x_train, x_test = x_train / 255.0, x_test / 255.0
  60. y_train = y_train.flatten()
  61. y_test = y_test.flatten()
  62. else:
  63. raise NotImplementedError("experiment for dataset not supported")
  64. # debug datset
  65. if self.args.debug:
  66. n_points = 1000
  67. idx = np.random.choice(
  68. len(x_train), n_points)
  69. x_train = x_train[idx]
  70. y_train = y_train[idx]
  71. idx = np.random.choice(
  72. len(x_test), n_points)
  73. x_test = x_test[idx]
  74. y_test = y_test[idx]
  75. def build_rare_class_dataset(data, rare_class, rare_class_percentage):
  76. x, y = data
  77. # keep nonrare class data as is
  78. x_non_rare = x[y!=rare_class]
  79. y_non_rare = y[y!=rare_class]
  80. # in test and training, we make 1 of the classes really rare
  81. unique, counts = np.unique(y, return_counts=True)
  82. rare_class_count = counts[unique==rare_class]
  83. count_to_keep = int(rare_class_count * rare_class_percentage)
  84. x_rare = x[y==rare_class][:count_to_keep]
  85. y_rare = y[y==rare_class][:count_to_keep]
  86. return (np.concatenate((x_non_rare, x_rare)),
  87. np.concatenate((y_non_rare, y_rare)))
  88. if args.rare_class:
  89. x_train, y_train = build_rare_class_dataset(
  90. (x_train, y_train),
  91. args.rare_class,
  92. args.rare_class_percentage)
  93. x_test, y_test = build_rare_class_dataset(
  94. (x_test, y_test),
  95. args.rare_class,
  96. args.rare_class_percentage)
  97. # change to 1 hot
  98. y_train = np.eye(10)[y_train]
  99. y_test = np.eye(10)[y_test]
  100. # build validation dataset
  101. num_validation = int(len(x_train) * args.validation_percentage)
  102. idx = np.random.choice(len(x_train), num_validation)
  103. mask = np.ones(len(x_train), np.bool)
  104. mask[idx] = 0
  105. x_val = x_train[~mask]
  106. y_val = y_train[~mask]
  107. x_train = x_train[mask]
  108. y_train = y_train[mask]
  109. # we keep as raw numpy as it's easier to index only the labelled set
  110. self.train_data = (x_train, y_train)
  111. self.val_data = (x_train, y_train)
  112. self.test_data = (x_test, y_test)
  113. def _get_model(self) -> tf.keras.Model:
  114. args = self.args
  115. if args.dataset == "mnist":
  116. return MNISTModel(
  117. args.model_num_filters,
  118. args.model_filter_size,
  119. args.model_pool_size,
  120. args.model_num_classes,
  121. )
  122. elif args.dataset == "cifar10":
  123. return Cifar10Model()
  124. else:
  125. raise NotImplementedError("model for dataset not implemented")
  126. def _get_optimizer(self):
  127. # TODO add args
  128. return tf.keras.optimizers.Adam()
  129. def _get_loss(self):
  130. # TODO switch to BinaryCrossentropy
  131. # weight the class(?)
  132. # return tf.keras.losses.BinaryCrossentropy(
  133. # from_logits=True,
  134. # reduction=tf.keras.losses.Reduction.SUM_OVER_BATCH_SIZE)
  135. return tf.keras.losses.CategoricalCrossentropy(
  136. from_logits=True,
  137. reduction=tf.keras.losses.Reduction.SUM_OVER_BATCH_SIZE)
  138. @abc.abstractmethod
  139. def _get_sampler(self):
  140. raise NotImplementedError("pick a sampler")
  141. @abc.abstractmethod
  142. def label_n_elements(self, sampler, n_elements):
  143. raise NotImplementedError("using sampler not implemented")
  144. def get_labelled_train_data(self, sampler):
  145. labelled_indices = list(sampler.labelled_idx_set)
  146. train_x = self.train_data[0][labelled_indices]
  147. train_y = self.train_data[1][labelled_indices]
  148. return (train_x, train_y)
  149. def train_model_step(self, data):
  150. """
  151. single pass of labelled train data
  152. """
  153. # TODO we don't retrain here, is that sensible?
  154. model = self.model
  155. args = self.args
  156. logger = self.logger
  157. optimizer = self.optimizer
  158. loss_fn = self.loss_fn
  159. total_loss = 0
  160. count = 0
  161. elapsed = None
  162. train_x, train_y = data
  163. data_size = len(train_x)
  164. for idx, batch in enumerate(batch_sample_indices(data_size, batch_size=args.batch_size)):
  165. batch_x, batch_y = train_x[batch], train_y[batch]
  166. with tf.GradientTape() as tape:
  167. prediction = model(batch_x)
  168. loss = loss_fn(batch_y, prediction)
  169. grads = tape.gradient(loss, model.trainable_variables)
  170. optimizer.apply_gradients(zip(grads, model.trainable_variables))
  171. total_loss += loss.numpy()
  172. count += len(batch_x)
  173. if self.start_time:
  174. elapsed = time.monotonic() - self.start_time
  175. if args.train_log_interval > 0 and (idx+1) % args.train_log_interval == 0:
  176. cur_loss = total_loss / count
  177. logger.info(f"Batch: {(idx+1)*args.batch_size}/{data_size}"
  178. f"\tLoss: {cur_loss}"
  179. f"\tElapsed Time: {time_display(elapsed)}")
  180. total_loss = 0
  181. count = 0
  182. def evaluate_model_step(self, data):
  183. args = self.args
  184. model = self.model
  185. logger = self.logger
  186. optimizer = self.optimizer
  187. loss_fn = self.loss_fn
  188. # TODO rely on model compiling here?
  189. loss_metric = tf.keras.metrics.Mean(name="loss")
  190. micro_f1_metric = tf.keras.metrics.Mean(name="micro_f1_metric")
  191. macro_f1_metric = tf.keras.metrics.Mean(name="macro_f1_metric")
  192. accuracy_metric = tf.keras.metrics.Accuracy(name="accuracy_metric")
  193. if args.rare_class:
  194. rare_class_f1_metric = tf.keras.metrics.Mean(name="rare_f1_metric")
  195. test_x, test_y = data
  196. data_size = len(test_x)
  197. total_prediction_count = np.zeros(args.model_num_classes)
  198. total_true_label_count = np.zeros(args.model_num_classes)
  199. rare_class_count = 0
  200. for idx, test_batch in enumerate(
  201. batch_sample_indices(data_size, batch_size=args.batch_size)):
  202. batch_x, batch_y = test_x[test_batch], test_y[test_batch]
  203. raw_prediction = model(batch_x, training=False)
  204. loss_metric(loss_fn(batch_y, raw_prediction))
  205. # min class ratio
  206. min_class_prediction_ratio = np.min(total_prediction_count)/data_size
  207. min_class_true_ratio = np.min(total_true_label_count)/data_size
  208. # max class ratio
  209. max_class_prediction_ratio = np.max(total_prediction_count)/data_size
  210. max_class_true_ratio = np.max(total_true_label_count)/data_size
  211. prediction = np.argmax(raw_prediction, axis=1)
  212. unique, counts = np.unique(prediction, return_counts=True)
  213. for i, count in zip(unique, counts):
  214. total_prediction_count[i] += count
  215. batch_y = np.argmax(batch_y, axis=1) # 1 hot to class
  216. unique, counts = np.unique(batch_y, return_counts=True)
  217. for i, count in zip(unique, counts):
  218. total_true_label_count[i] += count
  219. micro_f1_metric(
  220. f1_score(batch_y, prediction, average="micro", labels=np.arange(10)))
  221. macro_f1_metric(
  222. f1_score(batch_y, prediction, average="macro", labels=np.arange(10)))
  223. accuracy_metric(batch_y, prediction)
  224. if args.rare_class:
  225. rare_class_f1_metric(
  226. f1_score(batch_y, prediction, average=None, labels=np.arange(10))[args.rare_class])
  227. rare_class_count += len(batch_y[batch_y==args.rare_class])
  228. result = {
  229. "loss": loss_metric.result(),
  230. "micro_f1_metric": micro_f1_metric.result(),
  231. "macro_f1_metric": macro_f1_metric.result(),
  232. "accuracy_metric": accuracy_metric.result(),
  233. "min_class_prediction_ratio": min_class_prediction_ratio,
  234. "min_class_true_ratio": min_class_true_ratio,
  235. "max_class_prediction_ratio": max_class_prediction_ratio,
  236. "max_class_true_ratio": max_class_true_ratio,
  237. }
  238. if args.rare_class:
  239. # rare class ratio
  240. rare_class_prediction_ratio = total_prediction_count[args.rare_class]/data_size
  241. rare_class_true_ratio = total_true_label_count[args.rare_class]/data_size
  242. result.update({
  243. "rare_class_f1_metric": rare_class_f1_metric.result(),
  244. "rare_class_prediction_ratio": rare_class_prediction_ratio,
  245. "rare_class_true_ratio": rare_class_true_ratio,
  246. "rare_class_count": rare_class_count,
  247. })
  248. return result
  249. def log_metrics(
  250. self,
  251. metrics,
  252. step: int, # training step (number data point labeled)
  253. data_type: str, # test, train
  254. ):
  255. # we copy to make mit immutable
  256. metrics = metrics.copy()
  257. # metric output
  258. with self.tf_summary_writer.as_default():
  259. for metric_key, metric_value in metrics.items():
  260. tf.summary.scalar(f"{data_type} {metric_key}", metric_value, step=step)
  261. # log output
  262. for metric_key, metric_value in metrics.items():
  263. self.logger.info(f"{data_type} {metric_key}: {metric_value}")
  264. # log output, tensorboard output, save to a master csv
  265. # TODO keep this open for faster run
  266. metrics["step"] = step
  267. # we cast to float before storing to csv
  268. for metric_key, metric_value in metrics.items():
  269. metrics[metric_key] = float(metric_value)
  270. csv_file = os.path.join(self.run_dir, f"{data_type}_results.csv")
  271. with open(csv_file, 'a') as f:
  272. writer = csv.DictWriter(f, fieldnames=list(metrics.keys()))
  273. if f.tell() == 0:
  274. writer.writeheader()
  275. writer.writerow(metrics)
  276. def run_experiment(self):
  277. try:
  278. for _ in range(self.args.n_experiment_runs):
  279. self._init_experiment()
  280. self._run_experiment()
  281. except KeyboardInterrupt:
  282. self.logger.warning('Exiting from training early!')
  283. def _init_experiment(self):
  284. args = self.args
  285. #using timestamp as unique identifier for run
  286. timestamp_str = datetime.now().strftime("%Y-%m-%d_%H:%M:%S")
  287. self.run_dir = os.path.join(args.experiment_dir, timestamp_str)
  288. if not os.path.exists(self.run_dir):
  289. os.makedirs(self.run_dir)
  290. # setting logs, tf sumary writer and some
  291. self.logger, self.tf_summary_writer, self.model_snapshot_dir = (
  292. set_up_experiment_logging(
  293. args.experiment_name,
  294. log_fpath=os.path.join(self.run_dir, "experiment.log"),
  295. model_snapshot_dir=os.path.join(self.run_dir, "model_snapshots"),
  296. metrics_dir=os.path.join(self.run_dir, "metrics"),
  297. stdout=args.stdout,
  298. clear_old_data=True,
  299. )
  300. )
  301. self.model = self._get_model()
  302. self.AL_sampler = self._get_sampler()
  303. self.start_time = time.monotonic()
  304. def _run_experiment(self):
  305. start_time = self.start_time
  306. args = self.args
  307. train_data = self.train_data
  308. test_data = self.test_data
  309. logger = self.logger
  310. AL_sampler = self.AL_sampler
  311. labelled_indices = set()
  312. logger.info(f"Starting {args.experiment_name} experiment")
  313. n_to_label = int((len(train_data[0]) * args.al_step_percentage))
  314. train_dataset_size = len(train_data[0])
  315. # TODO bug of missing final count of labelled
  316. for curr_AL_epoch in range(args.al_epochs):
  317. # AL step
  318. self.label_n_elements(AL_sampler, n_to_label)
  319. labelled_indices = AL_sampler.labelled_idx_set
  320. n_labeled = len(labelled_indices)
  321. logger.info("-" * 118)
  322. logger.info(
  323. f"AL Epoch: {curr_AL_epoch+1}/{args.al_epochs}"
  324. f"\tTrain Data Labeled: {n_labeled}/{train_dataset_size}"
  325. f"\tElapsed Time: {time_display(time.monotonic()-start_time)}")
  326. # train step
  327. if args.retrain_model_from_scratch:
  328. self.model = self._get_model()
  329. train_data = self.get_labelled_train_data(AL_sampler)
  330. for epoch in range(1, args.train_epochs+1):
  331. self.train_model_step(train_data)
  332. # final train loss (full data)
  333. train_metrics = self.evaluate_model_step(train_data)
  334. self.log_metrics(train_metrics, n_labeled, "train")
  335. # test metrics
  336. test_metrics = self.evaluate_model_step(test_data)
  337. self.log_metrics(test_metrics, n_labeled, "test")
  338. # save model
  339. if (args.save_model_interval > 0 and
  340. ((curr_AL_epoch+1) % args.save_model_interval == 0)):
  341. model_fpath = os.path.join(
  342. self.model_snapshot_dir,
  343. f"model_AL_epoch_{curr_AL_epoch}_{args.al_epochs}.ckpt")
  344. self.model.save_weights(model_fpath)
  345. class RandomExperimentManager(ActiveLearningExperimentManagerT):
  346. def _get_sampler(self):
  347. return ALRandomSampler(len(self.train_data[0]))
  348. def label_n_elements(self, sampler, n_elements):
  349. sampler.label_n_elements(n_elements)
  350. class LCExperimentManager(ActiveLearningExperimentManagerT):
  351. def _get_sampler(self):
  352. return LeastConfidenceSampler(self.train_data[0])
  353. def label_n_elements(self, sampler, n_elements):
  354. sampler.label_n_elements(n_elements, self.model)
  355. class RLExperimentManagerT(ActiveLearningExperimentManagerT):
  356. def log_RL_metrics(self, step):
  357. AL_sampler = self.AL_sampler
  358. with self.tf_summary_writer.as_default():
  359. tf.summary.scalar("Action selected", self.action, step=step)
  360. tf.summary.scalar("Reward", self.reward, step=step)
  361. for i, arm_count in enumerate(AL_sampler.arm_count):
  362. tf.summary.scalar(
  363. f"{AL_sampler.get_action(i)} action count", arm_count, step=step)
  364. self.logger.info(f"selected {AL_sampler.get_action(self.action)}")
  365. self.logger.info(f"reward: {self.reward}")
  366. # TODO add in CSV to log arm + sampler state
  367. def _init_experiment(self):
  368. super()._init_experiment()
  369. self.reward = None # keeps track of reward
  370. self.state = None # and state
  371. self.action = None # track of most recent action
  372. # these are all thigns relevent to compute ^
  373. self.val_metrics = None
  374. @abc.abstractmethod
  375. def update_state(self):
  376. """
  377. updates state of system and sets it in self.state
  378. we store reward in part of class since we don't know what we need to keep track of
  379. in actual experiment
  380. """
  381. ...
  382. @abc.abstractmethod
  383. def update_reward(self):
  384. """
  385. updates reward and set its in self.reward
  386. we store reward in part of class since we don't know what we need to keep track of
  387. in actual experiment
  388. """
  389. ...
  390. @abc.abstractmethod
  391. def update_agent_sampler(self, sampler, action, reward, state):
  392. # TODO add in batch option (?)
  393. ...
  394. def _run_experiment(self):
  395. start_time = self.start_time
  396. args = self.args
  397. train_data = self.train_data
  398. test_data = self.test_data
  399. logger = self.logger
  400. AL_sampler = self.AL_sampler
  401. labelled_indices = set()
  402. logger.info(f"Starting {args.experiment_name} experiment")
  403. n_to_label = int(len(train_data[0]) * args.al_step_percentage)
  404. train_dataset_size = len(train_data[0])
  405. # TODO bug of missing final count of labelled
  406. for curr_AL_epoch in range(args.al_epochs):
  407. # AL step
  408. self.action, _ = self.label_n_elements(AL_sampler, n_to_label)
  409. labelled_indices = AL_sampler.labelled_idx_set
  410. n_labeled = len(labelled_indices)
  411. logger.info("-" * 118)
  412. logger.info(
  413. f"AL Epoch: {curr_AL_epoch+1}/{args.al_epochs}"
  414. f"\tTrain Data Labeled: {n_labeled}/{train_dataset_size}"
  415. f"\tElapsed Time: {time_display(time.monotonic()-start_time)}")
  416. # train step
  417. if args.retrain_model_from_scratch:
  418. self.model = self._get_model()
  419. # train step
  420. train_data = self.get_labelled_train_data(AL_sampler)
  421. for epoch in range(1, args.train_epochs+1):
  422. self.train_model_step(train_data)
  423. # final train loss (full data)
  424. train_metrics = self.evaluate_model_step(train_data)
  425. self.log_metrics(train_metrics, n_labeled, "train")
  426. # test metrics
  427. test_metrics = self.evaluate_model_step(test_data)
  428. self.log_metrics(test_metrics, n_labeled, "test")
  429. val_metrics = self.evaluate_model_step(self.val_data)
  430. self.log_metrics(val_metrics, n_labeled, "val")
  431. self.val_metrics = val_metrics
  432. self.update_reward()
  433. self.update_state()
  434. self.update_agent_sampler(
  435. AL_sampler, self.action, self.reward, self.state)
  436. self.log_RL_metrics(n_labeled)
  437. # TODO save RL agent
  438. # save model
  439. if (args.save_model_interval > 0 and
  440. ((curr_AL_epoch+1) % args.save_model_interval == 0)):
  441. model_fpath = os.path.join(
  442. self.model_snapshot_dir,
  443. f"model_AL_epoch_{curr_AL_epoch}_{args.al_epochs}.ckpt")
  444. self.model.save_weights(model_fpath)
  445. class UCBBanditExperimentManager(RLExperimentManagerT):
  446. def __init__(self, args):
  447. assert args.reward_metric_name is not None
  448. super().__init__(args)
  449. def _get_sampler(self):
  450. return UCBBanditSampler(self.train_data[0])
  451. def label_n_elements(self, sampler, n_elements):
  452. return sampler.label_n_elements(n_elements, self.model)
  453. def _init_experiment(self):
  454. super()._init_experiment()
  455. self.previous_metric_value = 0
  456. def update_state(self):
  457. self.state = None
  458. def update_reward(self):
  459. curr_metric_value = self.val_metrics[self.args.reward_metric_name]
  460. # TODO explore scaling down based on state
  461. self.reward = curr_metric_value - self.previous_metric_value
  462. self.previous_metric_value = curr_metric_value
  463. def update_agent_sampler(self, sampler, action, reward, state):
  464. self.AL_sampler.update_q_value(self.action, reward)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...