-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunctions.py
3852 lines (3385 loc) · 117 KB
/
functions.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
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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import torch
from collections.abc import Generator, Sequence, Iterable, Callable
from collections import defaultdict
import scipy
import matplotlib.pyplot as plt
import torch.nn.functional as F
import datasets
from sklearn.decomposition import TruncatedSVD
from sklearn.feature_extraction.text import TfidfVectorizer
import tqdm
import gymnasium as gym
from IPython.display import Image
import moviepy.editor as mpy
import os
from PIL import Image as PILImage
import torch
from typing import Optional
import math
import itertools
from abc import (
ABC,
abstractmethod
)
def add_column_of_1s(
matrix: torch.Tensor
) -> torch.Tensor:
"""
Adds a column of 1s to a matrix.
Parameters
----------
matrix : torch.Tensor
A 2-dimensional tensor, that is a matrix.
Returns
-------
A new tensor that is the matrix
augmented by a column of 1s on the right.
"""
matrix_aug = torch.concatenate(
[
matrix,
torch.ones_like(matrix[:, :1])
],
dim=1
)
return matrix_aug
def load_preprocessed_dataset(
config: dict
) -> tuple[
tuple[torch.Tensor, torch.Tensor],
tuple[torch.Tensor, torch.Tensor],
tuple[torch.Tensor, torch.Tensor]
]:
"""
Loads a dataset that was saved with `torch.save`.
We expect that the object that was saved is a dictionary with keys
`train_features`, `train_labels`
`valid_features`, `valid_labels`,
`test_features`, `test_labels`
storing the appropriate data in tensors.
Parameters
----------
config : dict
Configuration dictionary. Required keys:
dataset_preprocessed_path : str
The path where the preprocessed dataset was saved to.
device : torch.device | int | str
The device to map the tensors to.
features_dtype : torch.dtype
The datatype to convert feature tensors to.
Returns
-------
The triple of pairs
`(train_features, train_labels),
(valid_feautres, valid_labels),
(test_features, test_labels)`
"""
loaded = torch.load(
config["dataset_preprocessed_path"],
weights_only=True
)
(
train_features,
train_labels,
valid_features,
valid_labels,
test_features,
test_labels
) = (
loaded[key].to(config["device"])
for key in [
"train_features",
"train_labels",
"valid_features",
"valid_labels",
"test_features",
"test_labels"
]
)
train_features, valid_features, test_features = (
features.to(config["features_dtype"])
for features in (train_features, valid_features, test_features)
)
return (
(train_features, train_labels),
(valid_features, valid_labels),
(test_features, test_labels)
)
def flatten_images(
images: torch.Tensor,
dtype=torch.float32,
scale=1/255
) -> torch.Tensor:
"""
Given as input a batch of images of shape
`(batch_size, channel_num, height, width)`
flatten it and output a tensor of shape `(batch_size, feature_dim)`.
Moreover:
1. transform the tensor to `dtype` and
2. multiply it by `scale`.
Parameters
----------
images : torch.Tensor
The images in `torch.Tensor` format.
dtype : torch.dtype, optional
The dtype to transform the tensor to. Default: `torch.float32`.
scale : float, optional
The value to scale the tensor with. Default: `1 / 255`.
"""
batch_size, channel_num, height, width = images.shape
feature_dim = channel_num * height * width
images = (
images
.reshape(batch_size, feature_dim)
.to(dtype)
* scale
)
return images
def load_preprocessed_dataset(
config: dict
) -> tuple[
tuple[torch.Tensor, torch.Tensor],
tuple[torch.Tensor, torch.Tensor],
tuple[torch.Tensor, torch.Tensor]
]:
"""
Loads a dataset that was saved with `torch.save`.
We expect that the object that was saved is a dictionary with keys
`train_features`, `train_labels`
`valid_features`, `valid_labels`,
`test_features`, `test_labels`
storing the appropriate data in tensors.
Parameters
----------
config : dict
Configuration dictionary. Required keys:
dataset_preprocessed_path : str
The path where the preprocessed dataset was saved to.
device : torch.device | int | str
The device to map the tensors to.
features_dtype : torch.dtype
The datatype to convert feature tensors to.
Returns
-------
The triple of pairs
`(train_features, train_labels),
(valid_feautres, valid_labels),
(test_features, test_labels)`
"""
loaded = torch.load(
config["dataset_preprocessed_path"],
weights_only=True
)
(
train_features,
train_labels,
valid_features,
valid_labels,
test_features,
test_labels
) = (
loaded[key].to(config["device"])
for key in [
"train_features",
"train_labels",
"valid_features",
"valid_labels",
"test_features",
"test_labels"
]
)
train_features, valid_features, test_features = (
features.to(config["features_dtype"])
for features in (train_features, valid_features, test_features)
)
return (
(train_features, train_labels),
(valid_features, valid_labels),
(test_features, test_labels)
)
def get_accuracy(
labels: torch.Tensor,
logits: torch.Tensor
) -> torch.Tensor:
"""
Given logits output by a classification model, calculate the accuracy.
Supports model ensembles of arbitrary ensemble shape.
Parameters
----------
labels : torch.Tensor
Label tensor of shape
`(dataset_size,)` or
`ensemble_shape + (dataset_size,)`.
logits : torch.Tensor
Logit tensor of shape
`ensemble_shape + (dataset_size, label_num)`.
Returns
-------
The tensor of accuracies of shape `ensemble_shape`.
"""
labels_predict = logits.argmax(dim=-1)
accuracy = (labels == labels_predict).to(torch.float32).mean(dim=-1)
return accuracy
def get_cross_entropy(
labels: torch.Tensor,
logits: torch.Tensor
) -> torch.Tensor:
"""
Given logits output by a classification model,
calculate the cross-entropy.
Supports model ensembles of arbitrary ensemble shape.
Parameters
----------
labels : torch.Tensor
Label tensor of shape
`(dataset_size,)` or
`ensemble_shape + (dataset_size,)`.
logits : torch.Tensor
Logit tensor of shape
`ensemble_shape + (dataset_size, label_num)`.
Returns
-------
The tensor of accuracies of shape `ensemble_shape`.
"""
return F.cross_entropy(
logits.movedim((-2, -1), (0, 1)),
labels.broadcast_to(logits.shape[:-1]).movedim(-1, 0),
reduction="none"
).mean(dim=0)
def get_dataloader_random_reshuffle(
config: dict,
features: torch.Tensor,
labels: torch.Tensor
) -> Generator[tuple[torch.Tensor, torch.Tensor]]:
"""
Given a feature and a label tensor,
creates a random reshuffling (without replacement) dataloader
that yields pairs `minibatch_features, minibatch_labels` indefinitely.
Support arbitrary ensemble shapes.
Parameters
----------
config : dict
Configuration dictionary. Required keys:
ensemble_shape : tuple[int]
The required ensemble shapes of the outputs.
minibatch_size : int
The size of the minibatches.
features : torch.Tensor
Tensor of dataset features.
We assume that the first dimension is the batch dimension
labels : torch.Tensor
Tensor of dataset labels.
Returns
-------
A generator of tuples `minibatch_features, minibatch_labels`.
"""
for indices in get_random_reshuffler(
len(labels),
config["minibatch_size"],
device=config["device"],
ensemble_shape=config["ensemble_shape"]
):
yield features[indices], labels[indices]
def get_random_reshuffler(
dataset_size: int,
minibatch_size: int,
device="cpu",
ensemble_shape=()
) -> Generator[torch.Tensor]:
"""
Generate minibatch indices for a random shuffling dataloader.
Supports arbitrary ensemble shapes.
Parameters
----------
dataset_size : int
The size of the dataset to yield batches of minibatch indices for.
minibatch_size : int
The minibatch size.
device : int | str | torch.device, optional
The device to store the index tensors on. Default: "cpu"
ensemble_shape : tuple[int], optional
The ensemble shape of the minibatch indices. Default: ()
"""
q, r = divmod(dataset_size, minibatch_size)
minibatch_num = q + min(1, r)
minibatch_index = minibatch_num
while True:
if minibatch_index == minibatch_num:
minibatch_index = 0
shuffled_indices = get_shuffled_indices(
dataset_size,
device=device,
ensemble_shape=ensemble_shape
)
yield shuffled_indices[
...,
minibatch_index * minibatch_size
:(minibatch_index + 1) * minibatch_size
]
minibatch_index += 1
def line_plot_confidence_band(
x: Sequence,
y: torch.Tensor,
color=None,
confidence_level=.95,
label="",
opacity=.2
):
"""
Plot training curves from an ensemble with a pointwise confidence band.
Parameters
----------
x : Sequence
The sequence of time indicators (eg. number of train steps)
when the measurements took place.
y : torch.Tensor
The tensor of measurements of shape `(len(x), ensemble_num)`.
color : str | tuple[float] | None, optional
The color of the plot. Default: `None`
confidence_level : float, optional
The confidence level of the confidence band. Default: 0.95
label : str, optional
The label of the plot. Default: ""
opacity : float, optional
The opacity of the confidence band, to be set via the
`alpha` keyword argument of `plt.fill_between`. Default: 0.2
"""
sample_size = y.shape[1]
student_coefficient = -scipy.stats.t(sample_size - 1).ppf(
2 * (1 - confidence_level)
)
y_mean = y.mean(dim=-1)
y_std = y.std(dim=-1)
interval_half_length = student_coefficient * y_std / sample_size ** .5
y_low = y_mean - interval_half_length
y_high = y_mean + interval_half_length
plt.fill_between(x, y_low, y_high, alpha=opacity, color=color)
plt.plot(x, y_mean, color=color, label=label)
def get_random_reshuffler(
dataset_size: int,
minibatch_size: int,
device="cpu",
ensemble_shape=()
) -> Generator[torch.Tensor]:
"""
Generate minibatch indices for a random shuffling dataloader.
Supports arbitrary ensemble shapes.
Parameters
----------
dataset_size : int
The size of the dataset to yield batches of minibatch indices for.
minibatch_size : int
The minibatch size.
device : int | str | torch.device, optional
The device to store the index tensors on. Default: "cpu"
ensemble_shape : tuple[int], optional
The ensemble shape of the minibatch indices. Default: ()
"""
q, r = divmod(dataset_size, minibatch_size)
minibatch_num = q + min(1, r)
minibatch_index = minibatch_num
while True:
if minibatch_index == minibatch_num:
minibatch_index = 0
shuffled_indices = get_shuffled_indices(
dataset_size,
device=device,
ensemble_shape=ensemble_shape
)
yield shuffled_indices[
...,
minibatch_index * minibatch_size
:(minibatch_index + 1) * minibatch_size
]
minibatch_index += 1
def get_shuffled_indices(
dataset_size: int,
device="cpu",
ensemble_shape=(),
) -> torch.Tensor:
"""
Get a tensor of a batch of shuffles of indices `0,...,dataset_size - 1`.
Parameters
----------
dataset_size : int
The size of the dataset the indices of which to shuffle
device : int | str | torch.device, optional
The device to store the resulting tensor on. Default: "cpu"
ensemble_shape : tuple[int], optional
The batch shape of the shuffled index tensors. Default: ()
"""
total_shape = ensemble_shape + (dataset_size,)
uniform = torch.rand(
total_shape,
device=device
)
indices = uniform.argsort(dim=-1)
return indices
def get_binary_accuracy(
labels: torch.Tensor,
logits: torch.Tensor
) -> torch.Tensor:
"""
Get the binary accuracy between a label and a logit tensor.
It can handle arbitrary ensemble shapes.
Parameters
----------
labels : torch.Tensor
The tensor of true labels. We assume it has shape
`(dataset_size,)` or `ensemble_shape + (dataset_size,)`.
logits : torch.Tensor
The logit tensor. We assume it has shape
`ensemble_shape + (dataset_size, 1)`.
Returns
-------
The tensor of binary accuracies per ensemble member
of shape `ensemble_shape`.
"""
predict_positives = logits[..., 0] > 0
true_positives = labels.broadcast_to(
predict_positives.shape
).to(torch.bool)
return (
predict_positives == true_positives
).to(torch.float32).mean(dim=-1)
def get_seed(
upper=1 << 31
) -> int:
"""
Generates a random integer by the `torch` PRNG,
to be used as seed in a stochastic function.
Parameters
----------
upper : int, optional
Exclusive upper bound of the interval to generate integers from.
Default: 1 << 31.
Returns
-------
A random integer.
"""
return int(torch.randint(upper, size=()))
def lsa(
config: dict,
training_dataset: datasets.Dataset,
validation_datasets: Iterable[datasets.Dataset] = ()
) -> Generator[tuple[torch.Tensor, torch.Tensor]]:
"""
Fit a composite of a `TfidfVectorizer` and a `TruncatedSVD`
on the corpus at the `"text"` key of the training dataset.
Then use this composite to transform the training corpus
and the optional validation corpora to feature matrices.
Also returns the labels in the datasets as tensors.
Parameters
----------
config : dict
Configuration dictionary. Required keys:
"device" : torch.device
The device to store feature matrices and label vectors on.
"features_dtype" : torch.dtype
The datatype of feature matrices.
"labels_dtype" : torch.dtype
The datatype of label vectors.
"n_components": int
The number of dimensions to reduce the feature dimensions to
with truncated SVD.
training_dataset : datasets.Dataset
The training dataset. Required keys:
"text" : Iterable[str]
The dataset corpus
"label" : Iterable[int]
The dataset labels
validation_datasets : Iterable[datasets.Dataset], optional
An iterable of additional datasets,
of the same structure as `training_dataset`.
Default: `()`.
Returns
-------
A generator of pairs of feature matrices and label vectors.
The first pair is the training data.
Then the optional validation data follows.
"""
tf_idf = TfidfVectorizer()
train_features = tf_idf.fit_transform(training_dataset["text"])
truncated_svd = TruncatedSVD(
n_components=config["n_components"],
random_state=get_seed()
)
train_features = truncated_svd.fit_transform(train_features)
train_features = torch.asarray(
train_features,
device=config["device"],
dtype=config["features_dtype"]
)
train_labels = training_dataset.with_format(
"torch",
device=config["device"]
)["label"].to(config["labels_dtype"])
yield train_features, train_labels
for validation_dataset in validation_datasets:
valid_features = tf_idf.transform(validation_dataset["text"])
valid_features = truncated_svd.transform(valid_features)
valid_features = torch.asarray(
valid_features,
device=config["device"],
dtype=config["features_dtype"]
)
valid_labels = validation_dataset.with_format(
"torch",
device=config["device"]
)["label"].to(config["labels_dtype"])
yield (valid_features, valid_labels)
def train_logistic_regression(
config: dict,
get_loss: Callable[[torch.Tensor, torch.Tensor], torch.Tensor],
get_metric: Callable[[torch.Tensor, torch.Tensor], torch.Tensor],
label_num: int,
train_dataloader: Generator[tuple[torch.Tensor, torch.Tensor]],
valid_features: torch.Tensor,
valid_labels: torch.Tensor,
loss_name="loss",
metric_name="metric"
) -> dict:
"""
Train a logistic regression model on a classification task.
Support model ensembles of arbitrary shape.
Parameters
----------
config : dict
Configuration dictionary. Required keys:
ensemble_shape : tuple[int]
The shape of the model ensemble.
improvement_threshold : float
Making the best validation score this much better
counts as an improvement.
learning_rate : float | torch.Tensor
The learning rate of the SGD optimization.
If a tensor, then it should have shape
broadcastable to `ensemble_shape`.
In that case, the members of the ensemble are trained with
different learning rates.
steps_num : int
The maximum number of training steps to take.
steps_without_improvement : int
The maximum number of training steps without improvement to take.
valid_interval : int
The frequency of evaluations,
measured in the number of train steps.
get_loss : Callable[[torch.Tensor, torch.Tensor], torch.Tensor]
Function that calculates the loss values of an ensemble
from a label tensor and a logit tensor.
get_metric : Callable[[torch.Tensor, torch.Tensor], torch.Tensor]
Function that calculates the metric values of an ensemble
from a label tensor and a logit tensor.
label_num : int
The number of distinct labels in the classification task.
train_dataloader : Generator[tuple[torch.Tensor, torch.Tensor]]
A training minibatch dataloader, that yields pairs of
feature and label tensors indefinitely.
We assume that these have shape
`ensemble_shape + (minibatch_size, feature_dim)`
and `ensemble_shape + (minibatch_size,)`
respectively.
valid_features : torch.Tensor
Validation feature matrix.
valid_labels : torch.Tensor
Validation label vector.
loss_name : str, optional
The name of the loss values in the output dictionary.
Default: "loss"
metric_name : str, optional
The name of the metric values in the output dictionary.
Default: "metric"
Returns
-------
An output dictionary with the following keys:
best scores : torch.Tensor
The best validation accuracy per each ensemble member
best weights : torch.Tensor
The logistic regression weights
that were the best per each ensemble member.
training {metric_name} : torch.Tensor
The tensor of training metric values, of shape
`(evaluation_num,) + ensemble_shape`.
training {loss_name} : torch.Tensor
The tensor of training loss values, of shape
`(evaluation_num,) + ensemble_shape`.
training steps : list[int]
The list of the number of training steps at each evaluation.
validation {metric_name} : torch.Tensor
The tensor of validation metric values, of shape
`(evaluation_num,) + ensemble_shape`.
validation {loss_name} : torch.Tensor
The tensor of validation loss values, of shape
`(evaluation_num,) + ensemble_shape`.
"""
device = valid_features.device
features_dtype = valid_features.dtype
output = defaultdict(list)
best_scores = torch.zeros(
config["ensemble_shape"],
device=device,
dtype=features_dtype
).log()
steps_without_improvement = 0
if isinstance(config["learning_rate"], torch.Tensor):
learning_rate = config["learning_rate"][..., None, None]
else:
learning_rate = config["learning_rate"]
train_accuracies_step = torch.zeros(
config["ensemble_shape"],
device=device,
dtype=features_dtype
)
train_entries = 0
train_losses_step = torch.zeros(
config["ensemble_shape"],
device=device,
dtype=features_dtype
)
progress_bar = tqdm.trange(config["steps_num"])
step_id = 0
weights = torch.zeros(
config["ensemble_shape"] + (valid_features.shape[1], label_num),
device=device,
dtype=features_dtype,
requires_grad=True
)
best_weights = torch.empty_like(weights, requires_grad=False)
for minibatch_features, minibatch_labels in train_dataloader:
minibatch_size = minibatch_labels.shape[-1]
weights.grad = None
logits = minibatch_features @ weights
train_accuracies_step += get_metric(
minibatch_labels,
logits.detach()
) * minibatch_size
loss = get_loss(
minibatch_labels,
logits
)
loss.sum().backward()
with torch.no_grad():
weights -= learning_rate * weights.grad
train_losses_step += loss.detach() * minibatch_size
train_entries += minibatch_size
progress_bar.update()
step_id += 1
if step_id % config["valid_interval"] == 0:
with torch.no_grad():
logits = valid_features @ weights
valid_accuracy = get_metric(
valid_labels,
logits
)
valid_loss = get_loss(
valid_labels,
logits
)
output[f"training {metric_name}"].append(
(train_accuracies_step / train_entries)
)
output[f"training {loss_name}"].append(
(train_losses_step / train_entries)
)
output["training steps"].append(step_id)
output[f"validation {metric_name}"].append(valid_accuracy)
output[f"validation {loss_name}"].append(valid_loss)
train_accuracies_step.zero_()
train_entries = 0
train_losses_step.zero_()
improvement = valid_accuracy - best_scores
improvement_mask = improvement > config["improvement_threshold"]
if improvement_mask.any():
best_scores[improvement_mask] \
= valid_accuracy[improvement_mask]
best_weights[improvement_mask] = weights[improvement_mask]
steps_without_improvement = 0
else:
steps_without_improvement += config["valid_interval"]
if (
step_id >= config["steps_num"]
or (
steps_without_improvement
>= config["steps_without_improvement"]
)
):
for key in (
f"training {metric_name}",
f"training {loss_name}",
f"validation {metric_name}",
f"validation {loss_name}"
):
output[key] = torch.stack(output[key]).cpu()
output["best scores"] = best_scores
output["best weights"] = best_weights
progress_bar.close()
return output
def get_binary_cross_entropy(
labels: torch.Tensor,
logits: torch.Tensor
) -> torch.Tensor:
"""
Get the binary cross-entropy between a label and a logit tensor.
It can handle arbitrary ensemble shapes.
Parameters
----------
labels : torch.Tensor
The tensor of true labels. We assume it has shape
`(dataset_size,)` or `ensemble_shape + (dataset_size, 1)`.
logits : torch.Tensor
The logit tensor. We assume it has shape
`ensemble_shape + (dataset_size,)`.
Returns
-------
The tensor of binary cross-entropies per ensemble member
of shape `ensemble_shape`.
"""
return F.binary_cross_entropy_with_logits(
logits[..., 0],
labels.broadcast_to(logits.shape[:-1]),
reduction="none"
).mean(dim=-1)
def run_episode(
config: dict,
env: gym.Env,
gif_name="test.gif",
policy: Optional[Callable[[int], int]]=None,
) -> float:
"""
Run an episode in a `gym.Env`
with discrete observation and action spaces,
following a policy.
Make a gif video of the gameplay.
Parameters
----------
config : dict
Configuration dictionary. Required key-value pairs:
gif_fps : int
Frames per second in the gif.
video_directory : str
Path to a dictionary to save the gif to.
env : gym.Env
The environment to get an episode in.
gif_name : str, optional
The name of the gif video to save in the video directory.
Default: `"test.gif"`.
policy : Callable[[int], int], optional
The policy to get an episode with. Default: random policy.
Returns
-------
The discounted return of the episode.
"""
if policy is None:
policy = lambda observation: env.action_space.sample()
episode_return = 0
frames = []
step_id = 0
observation, _ = env.reset()
os.makedirs(config["videos_directory"], exist_ok=True)
frames.append(env.render())
while True:
action = policy(observation)
observation, reward, _, terminated, _ = env.step(action)
episode_return += reward * config["discount"] ** step_id
frames.append(env.render())
if terminated:
break
step_id += 1
# https://stackoverflow.com/a/64796174
clip = mpy.ImageSequenceClip(frames, fps=config["gif_fps"])
gif_path = os.path.join(config["videos_directory"], "test.gif")
clip.write_gif(gif_path, fps=config["gif_fps"])
return episode_return
import torch
from collections.abc import Generator, Sequence, Iterable, Callable
import scipy
import matplotlib.pyplot as plt
import torch.nn.functional as F
import datasets
from sklearn.decomposition import TruncatedSVD
from sklearn.feature_extraction.text import TfidfVectorizer
from typing import Optional
def add_column_of_1s(
matrix: torch.Tensor
) -> torch.Tensor:
"""
Adds a column of 1s to a matrix.
Parameters
----------
matrix : torch.Tensor
A 2-dimensional tensor, that is a matrix.
Returns
-------
A new tensor that is the matrix
augmented by a column of 1s on the right.
"""
matrix_aug = torch.concatenate(
[
matrix,
torch.ones_like(matrix[:, :1])
],
dim=1
)
return matrix_aug
def load_preprocessed_dataset(
config: dict
) -> tuple[
tuple[torch.Tensor, torch.Tensor],
tuple[torch.Tensor, torch.Tensor],
tuple[torch.Tensor, torch.Tensor]
]:
"""
Loads a dataset that was saved with `torch.save`.
We expect that the object that was saved is a dictionary with keys
`train_features`, `train_labels`
`valid_features`, `valid_labels`,
`test_features`, `test_labels`
storing the appropriate data in tensors.
Parameters
----------
config : dict
Configuration dictionary. Required keys:
dataset_preprocessed_path : str
The path where the preprocessed dataset was saved to.
device : torch.device | int | str
The device to map the tensors to.
features_dtype : torch.dtype
The datatype to convert feature tensors to.
Returns
-------
The triple of pairs
`(train_features, train_labels),
(valid_feautres, valid_labels),
(test_features, test_labels)`
"""
loaded = torch.load(
config["dataset_preprocessed_path"],
weights_only=True
)
(
train_features,
train_labels,
valid_features,
valid_labels,
test_features,
test_labels
) = (
loaded[key].to(config["device"])
for key in [
"train_features",
"train_labels",
"valid_features",
"valid_labels",
"test_features",
"test_labels"
]
)
train_features, valid_features, test_features = (
features.to(config["features_dtype"])
for features in (train_features, valid_features, test_features)
)
return (
(train_features, train_labels),
(valid_features, valid_labels),
(test_features, test_labels)
)
def flatten_images(
images: torch.Tensor,
dtype=torch.float32,
scale=1/255
) -> torch.Tensor:
"""