/
cnn.py
1808 lines (1534 loc) · 72.8 KB
/
cnn.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
"""classes for pytorch machine learning models in opensoundscape
For tutorials, see notebooks on opensoundscape.org
"""
from pathlib import Path
import warnings
import copy
import os
import types
import yaml
import numpy as np
import pandas as pd
import torch
import torch.nn.functional as F
import wandb
from tqdm.autonotebook import tqdm
import opensoundscape
from opensoundscape.ml import cnn_architectures
from opensoundscape.ml.utils import apply_activation_layer
from opensoundscape.preprocess.preprocessors import SpectrogramPreprocessor
from opensoundscape.ml.loss import (
BCEWithLogitsLoss_hot,
CrossEntropyLoss_hot,
ResampleLoss,
)
from opensoundscape.ml.dataloaders import SafeAudioDataloader
from opensoundscape.ml.datasets import AudioFileDataset
from opensoundscape.ml.cnn_architectures import inception_v3
from opensoundscape.sample import collate_audio_samples_to_dict
from opensoundscape.utils import identity
from opensoundscape.logging import wandb_table
from opensoundscape.ml.cam import CAM
import pytorch_grad_cam
from pytorch_grad_cam.utils.model_targets import ClassifierOutputTarget
from opensoundscape.metrics import (
single_target_metrics,
multi_target_metrics,
)
class BaseClassifier(torch.nn.Module):
"""
Base class for a deep-learning classification model.
Implements .predict(), .eval() and .generate_samples() but not .train()
Sub-class this class for flexible behavior. This class is not meant to be used directly.
Child classes: CNN, TensorFlowHubModel
"""
name = "BaseClassifier"
def __init__(self, classes):
super(BaseClassifier, self).__init__()
self.name = "BaseClassifier"
self.classes = classes
self.inference_dataloader_cls = SafeAudioDataloader
### Logging ###
self.wandb_logging = dict(
n_preview_samples=8, # before train/predict, log n random samples
top_samples_classes=None, # specify list of classes to see top samples from
n_top_samples=3, # after prediction, log n top scoring samples per class
# logs histograms of params & grads every n batches;
watch_freq=10, # use None for no logging of params & grads
gradcam=True, # if True, logs GradCAMs for top scoring samples during predict()
# log the model graph to wandb - seems to cause issues when attempting to
# continue training the model, so True is not recommended
log_graph=False,
)
self.log_file = None # specify a path to save output to a text file
self.logging_level = 1 # 0 for nothing, 1,2,3 for increasing logged info
self.verbose = 1 # 0 for nothing, 1,2,3 for increasing printed output
### metrics ###
self.prediction_threshold = 0.5 # used for threshold-specific metrics
def _log(self, message, level=1):
txt = str(message)
if self.logging_level >= level and self.log_file is not None:
with open(self.log_file, "a") as logfile:
logfile.write(txt + "\n")
if self.verbose >= level:
print(txt)
def predict(
self,
samples,
batch_size=1,
num_workers=0,
activation_layer=None,
split_files_into_clips=True,
overlap_fraction=0,
final_clip=None,
bypass_augmentations=True,
invalid_samples_log=None,
raise_errors=False,
wandb_session=None,
return_invalid_samples=False,
progress_bar=True,
**kwargs,
):
"""Generate predictions on a set of samples
Return dataframe of model output scores for each sample.
Optional activation layer for scores
(softmax, sigmoid, softmax then logit, or None)
Args:
samples:
the files to generate predictions for. Can be:
- a dataframe with index containing audio paths, OR
- a dataframe with multi-index (file, start_time, end_time), OR
- a list (or np.ndarray) of audio file paths
batch_size:
Number of files to load simultaneously [default: 1]
num_workers:
parallelization (ie cpus or cores), use 0 for current process
[default: 0]
activation_layer:
Optionally apply an activation layer such as sigmoid or
softmax to the raw outputs of the model.
options:
- None: no activation, return raw scores (ie logit, [-inf:inf])
- 'softmax': scores all classes sum to 1
- 'sigmoid': all scores in [0,1] but don't sum to 1
- 'softmax_and_logit': applies softmax first then logit
[default: None]
split_files_into_clips:
If True, internally splits and predicts on clips from longer audio files
Otherwise, assumes each row of `samples` corresponds to one complete sample
overlap_fraction: fraction of overlap between consecutive clips when
predicting on clips of longer audio files. For instance, 0.5
gives 50% overlap between consecutive clips.
final_clip: see `opensoundscape.utils.generate_clip_times_df`
bypass_augmentations: If False, Actions with
is_augmentation==True are performed. Default True.
invalid_samples_log: if not None, samples that failed to preprocess
will be listed in this text file.
raise_errors:
if True, raise errors when preprocessing fails
if False, just log the errors to unsafe_samples_log
wandb_session: a wandb session to log to
- pass the value returned by wandb.init() to progress log to a
Weights and Biases run
- if None, does not log to wandb
return_invalid_samples: bool, if True, returns second argument, a set
containing file paths of samples that caused errors during preprocessing
[default: False]
progress_bar: bool, if True, shows a progress bar with tqdm [default: True]
**kwargs: additional arguments to inference_dataloader_cls.__init__
Returns:
df of post-activation_layer scores
- if return_invalid_samples is True, returns (df,invalid_samples)
where invalid_samples is a set of file paths that failed to preprocess
Effects:
(1) wandb logging
If wandb_session is provided, logs progress and samples to Weights
and Biases. A random set of samples is preprocessed and logged to
a table. Progress over all batches is logged. Afte prediction,
top scoring samples are logged.
Use self.wandb_logging dictionary to change the number of samples
logged or which classes have top-scoring samples logged.
(2) unsafe sample logging
If unsafe_samples_log is not None, saves a list of all file paths that
failed to preprocess in unsafe_samples_log as a text file
Note: if loading an audio file raises a PreprocessingError, the scores
for that sample will be np.nan
"""
# create dataloader to generate batches of AudioSamples
dataloader = self.inference_dataloader_cls(
samples,
self.preprocessor,
split_files_into_clips=split_files_into_clips,
overlap_fraction=overlap_fraction,
final_clip=final_clip,
bypass_augmentations=bypass_augmentations,
batch_size=batch_size,
num_workers=num_workers,
raise_errors=raise_errors,
**kwargs,
)
# check for matching class list
if len(dataloader.dataset.dataset.classes) > 0 and list(self.classes) != list(
dataloader.dataset.dataset.classes
):
warnings.warn(
"The columns of input samples df differ from `model.classes`."
)
# Initialize Weights and Biases (wandb) logging
if wandb_session is not None:
# update the run config with information about the model
wandb_session.config.update(self._generate_wandb_config())
# update the run config with prediction parameters
wandb_session.config.update(
dict(
batch_size=batch_size,
num_workers=num_workers,
activation_layer=activation_layer,
)
)
# Log a table of preprocessed samples to wandb
wandb_session.log(
{
"Samples / Preprocessed samples": wandb_table(
dataloader.dataset.dataset,
self.wandb_logging["n_preview_samples"],
)
}
)
### Prediction/Inference ###
# iterate dataloader and run inference (forward pass) to generate scores
pred_scores = self.__call__(dataloader, wandb_session, progress_bar)
### Apply activation layer ### #TODO: test speed vs. doing it in __call__ on batches
pred_scores = apply_activation_layer(pred_scores, activation_layer)
# return DataFrame with same index/columns as prediction_dataset's df
df_index = dataloader.dataset.dataset.label_df.index
score_df = pd.DataFrame(index=df_index, data=pred_scores, columns=self.classes)
# warn the user if there were invalid samples (failed to preprocess)
# and log them to a file
invalid_samples = dataloader.dataset.report(log=invalid_samples_log)
# log top-scoring samples per class to wandb table
if wandb_session is not None:
classes_to_log = self.wandb_logging["top_samples_classes"]
if classes_to_log is None: # pick the first few classes if none specified
classes_to_log = self.classes
if len(classes_to_log) > 5: # don't accidentally log hundreds of tables
classes_to_log = classes_to_log[0:5]
for i, c in enumerate(classes_to_log):
top_samples = score_df.nlargest(
n=self.wandb_logging["n_top_samples"], columns=[c]
)
# note: the "labels" of these samples are actually prediction scores
dataset = AudioFileDataset(
samples=top_samples,
preprocessor=self.preprocessor,
bypass_augmentations=True,
)
table = wandb_table(
dataset=dataset,
classes_to_extract=[c],
drop_labels=True,
gradcam_model=self if self.wandb_logging["gradcam"] else None,
raise_exceptions=True, # TODO back to false when done debugging
)
wandb_session.log({f"Samples / Top scoring [{c}]": table})
if return_invalid_samples:
return score_df, invalid_samples
else:
return score_df
def __call__(self, dataloader, wandb_session):
raise NotImplementedError
def generate_samples(
self,
samples,
invalid_samples_log=None,
return_invalid_samples=False,
**kwargs,
):
"""
Generate AudioSample objects. Input options same as .predict()
Args:
samples: (same as CNN.predict())
the files to generate predictions for. Can be:
- a dataframe with index containing audio paths, OR
- a dataframe with multi-index (file, start_time, end_time), OR
- a list (or np.ndarray) of audio file paths
see .predict() documentation for other args
**kwargs: any arguments to inference_dataloader_cls.__init__
(default class is SafeAudioDataloader)
Returns:
a list of AudioSample objects
- if return_invalid_samples is True, returns second value: list of paths to
samples that failed to preprocess
Example:
```
from opensoundscappe.preprocess.utils import show_tensor_grid
samples = generate_samples(['/path/file1.wav','/path/file2.wav'])
tensors = [s.data for s in samples]
show_tensor_grid(tensors,columns=3)
```
"""
# create dataloader to generate batches of AudioSamples
dataloader = self.inference_dataloader_cls(samples, self.preprocessor, **kwargs)
# move model to device
try:
self.network.to(self.device)
self.network.eval()
except AttributeError:
pass # not a PyTorch model object
# generate samples in batches
generated_samples = []
for batch in dataloader:
generated_samples.extend(batch)
# get & log list of any sampls that failed to preprocess
invalid_samples = dataloader.dataset.report(log=invalid_samples_log)
if return_invalid_samples:
return generated_samples, invalid_samples
else:
return generated_samples
def eval(self, targets, scores, logging_offset=0):
"""compute single-target or multi-target metrics from targets and scores
By default, the overall model score is "map" (mean average precision)
for multi-target models (self.single_target=False) and "f1" (average
of f1 score across classes) for single-target models).
Override this function to use a different set of metrics.
It should always return (1) a single score (float) used as an overall
metric of model quality and (2) a dictionary of computed metrics
Args:
targets: 0/1 for each sample and each class
scores: continuous values in 0/1 for each sample and class
logging_offset: modify verbosity - for example, -1 will reduce
the amount of printing/logging by 1 level
"""
# remove all samples with NaN for a prediction
targets = targets[~np.isnan(scores).any(axis=1), :]
scores = scores[~np.isnan(scores).any(axis=1), :]
if len(scores) < 1:
warnings.warn("Recieved empty list of predictions (or all nan)")
return np.nan, np.nan
if self.single_target:
metrics_dict = single_target_metrics(targets, scores)
else:
metrics_dict = multi_target_metrics(
targets, scores, self.classes, self.prediction_threshold
)
# decide what to print/log:
self._log("Metrics:")
if not self.single_target:
self._log(f"\tMAP: {metrics_dict['map']:0.3f}", level=1 - logging_offset)
self._log(
f"\tAU_ROC: {metrics_dict['au_roc']:0.3f} ", level=2 - logging_offset
)
self._log(
f"\tJacc: {metrics_dict['jaccard']:0.3f} "
f"Hamm: {metrics_dict['hamming_loss']:0.3f} ",
level=2 - logging_offset,
)
self._log(
f"\tPrec: {metrics_dict['precision']:0.3f} "
f"Rec: {metrics_dict['recall']:0.3f} "
f"F1: {metrics_dict['f1']:0.3f}",
level=2 - logging_offset,
)
# choose one metric to be used for the overall model evaluation
if self.single_target:
score = metrics_dict["f1"]
else:
score = metrics_dict["map"]
return score, metrics_dict
class CNN(BaseClassifier):
"""
Generic CNN Model with .train(), .predict(), and .save()
flexible architecture, optimizer, loss function, parameters
for tutorials and examples see opensoundscape.org
Args:
architecture:
*EITHER* a pytorch model object (subclass of torch.nn.Module),
for example one generated with the `cnn_architectures` module
*OR* a string matching one of the architectures listed by
cnn_architectures.list_architectures(), eg 'resnet18'.
- If a string is provided, uses default parameters
(including pretrained weights, `weights="DEFAULT"`)
Note: if num channels != 3, copies weights from original
channels by averaging (<3 channels) or recycling (>3 channels)
classes:
list of class names. Must match with training dataset classes if training.
single_target:
- True: model expects exactly one positive class per sample
- False: samples can have any number of positive classes
[default: False]
preprocessor_class: class of Preprocessor object
sample_shape: tuple of height, width, channels for created sample
[default: (224,224,3)] #TODO: consider changing to (ch,h,w) to match torchww
"""
def __init__(
self,
architecture,
classes,
sample_duration,
single_target=False,
preprocessor_class=SpectrogramPreprocessor,
sample_shape=(224, 224, 3),
):
super(CNN, self).__init__(classes=classes)
self.name = "CNN"
# model characteristics
self.current_epoch = 0
self.classes = classes
self.single_target = single_target # if True: predict only class w max score
self.opensoundscape_version = opensoundscape.__version__
self.scheduler = None
# to use a custom DataLoader or Sampler, change these attributes
# to the custom class (init must take same arguments)
self.train_dataloader_cls = SafeAudioDataloader
# self.inference_dataloader_cls = SafeAudioDataloader #inherited from BaseClassifier
### architecture ###
# can be a pytorch CNN such as Resnet18 or a custom object
# must have .forward(), .train(), .eval(), .to(), .state_dict()
# for convenience, also allows user to provide string matching
# a key from cnn_architectures.ARCH_DICT
num_channels = sample_shape[2]
if type(architecture) == str:
assert architecture in cnn_architectures.list_architectures(), (
f"architecture must be a pytorch model object or string matching "
f"one of cnn_architectures.list_architectures() options. Got {architecture}"
)
self.architecture_name = architecture
architecture = cnn_architectures.ARCH_DICT[architecture](
len(classes), num_channels=num_channels
)
else:
assert issubclass(
type(architecture), torch.nn.Module
), "architecture must be a string or an instance of a subclass of torch.nn.Module"
if num_channels != 3:
warnings.warn(
f"Make sure your architecture expects the number of channels in "
f"your input samples ({num_channels}). "
f"Pytorch architectures expect 3 channels by default."
)
self.architecture_name = str(type(architecture))
self.network = architecture
### network device ###
# automatically gpu (default is 'cuda:0') if available
# can override after init, eg model.device='cuda:1'
# network and samples are moved to gpu during training/inference
# devices could be 'cuda:0', torch.device('cuda'), torch.device('cpu'), torch.device('mps') etc
self.device = _gpu_if_available()
### sample loading/preprocessing ###
# preprocessor will have attributes .sample_duration (seconds)
# and height, width, channels for output shape
self.preprocessor = preprocessor_class(
sample_duration=sample_duration,
height=sample_shape[0],
width=sample_shape[1],
channels=sample_shape[2],
)
### loss function ###
if self.single_target: # use cross entropy loss by default
self.loss_fn = CrossEntropyLoss_hot()
else: # for multi-target, use binary cross entropy
self.loss_fn = BCEWithLogitsLoss_hot()
### training parameters ###
# optimizer
self.opt_net = None # don't set directly. initialized during training
self.optimizer_cls = torch.optim.SGD # or torch.optim.Adam, etc
# instead of putting "params" key here, we only add it during
# _init_optimizer, just before initializing the optimizers
# this avoids an issue when re-loading a model of
# having the wrong .parameters() list
self.optimizer_params = {
# "params": self.network.parameters(),
"lr": 0.01,
"momentum": 0.9,
"weight_decay": 0.0005,
}
# lr_scheduler
self.lr_update_interval = 10 # update learning rates every # epochs
self.lr_cooling_factor = 0.7 # multiply learning rates by # on each update
### metrics ###
self.prediction_threshold = 0.5
# override self.eval() to change what metrics are
# computed and displayed during training/validation
### Logging ### attributes initialized in parent class
# dictionaries to store accuracy metrics & loss for each epoch
self.train_metrics = {}
self.valid_metrics = {}
self.loss_hist = {} # could add TensorBoard tracking
def _init_optimizer(self):
"""initialize an instance of self.optimizer
This function is called during .train() so that the user
has a chance to swap/modify the optimizer before training.
To modify the optimizer, change the value of
self.optimizer_cls and/or self.optimizer_params
prior to calling .train().
"""
param_dict = self.optimizer_params
param_dict["params"] = self.network.parameters()
return self.optimizer_cls([param_dict])
def _init_train_dataloader(self, train_df, batch_size, num_workers, raise_errors):
"""Prepare network for training on train_df
Args:
batch_size: number of training files to load/process before
re-calculating the loss function and backpropagation
num_workers: parallelization (number of cores or cpus)
raise_errors: if True, raise errors when loading samples
if False, skip samples that throw errors
Effects:
Sets up the optimization, loss function, and network
"""
######################
# Dataloader setup #
######################
# train_loader samples batches of images + labels from training set
return self.train_dataloader_cls(
train_df,
self.preprocessor,
split_files_into_clips=True,
overlap_fraction=0,
final_clip=None,
bypass_augmentations=False,
batch_size=batch_size,
num_workers=num_workers,
raise_errors=raise_errors,
collate_fn=identity,
shuffle=True, # SHUFFLE SAMPLES because we are training
# use pin_memory=True when loading files on CPU and training on GPU
pin_memory=False if self.device == torch.device("cpu") else True,
)
def _train_epoch(self, train_loader, wandb_session=None, progress_bar=True):
"""perform forward pass, loss, and backpropagation for one epoch
If wandb_session is passed, logs progress to wandb run
Args:
train_loader: DataLoader object to create samples
wandb_session: a wandb session to log to
- pass the value returned by wandb.init() to progress log to a
Weights and Biases run
- if None, does not log to wandb
Returns: (targets, scores) on training files
"""
self.network.train()
epoch_labels = []
epoch_scores = []
batch_loss = []
for batch_idx, samples in enumerate(
tqdm(train_loader, disable=not progress_bar)
):
# load a batch of images and labels from the train loader
# all augmentation occurs in the Preprocessor (train_loader)
# we collate here rather than in the DataLoader so that
# we can still access the AudioSamples and thier information
batch_data = collate_audio_samples_to_dict(samples)
batch_tensors = batch_data["samples"].to(self.device)
batch_labels = batch_data["labels"].to(self.device)
if len(self.classes) > 1: # squeeze one dimension [1,2] -> [1,1]
batch_labels = batch_labels.squeeze(1)
####################
# Forward and loss #
####################
# forward pass: feature extractor and classifier
logits = self.network(batch_tensors)
# save targets and predictions
epoch_scores.extend(list(logits.detach().cpu().numpy()))
epoch_labels.extend(list(batch_labels.detach().cpu().numpy()))
# calculate loss
loss = self.loss_fn(logits, batch_labels)
# save loss for each batch; later take average for epoch
batch_loss.append(loss.detach().cpu().numpy())
#############################
# Backward and optimization #
#############################
# zero gradients for optimizer
self.opt_net.zero_grad()
# backward pass: calculate the gradients
loss.backward()
# update the network using the gradients*lr
self.opt_net.step()
###########
# Logging #
###########
# log basic train info (used to print every batch)
if batch_idx % self.log_interval == 0:
# show some basic progress metrics during the epoch
N = len(train_loader)
self._log(
f"Epoch: {self.current_epoch} "
f"[batch {batch_idx}/{N}, {100 * batch_idx / N :.2f}%] "
)
# Log the Jaccard score and Hamming loss, and Loss function
epoch_loss_avg = np.mean(batch_loss)
self._log(f"\tDistLoss: {epoch_loss_avg:.3f}")
# Evaluate with model's eval function
tgts = batch_labels.int().detach().cpu().numpy()
scores = logits.int().detach().cpu().numpy()
self.eval(tgts, scores, logging_offset=-1)
# update learning parameters each epoch
self.scheduler.step()
# save the loss averaged over all batches
self.loss_hist[self.current_epoch] = np.mean(batch_loss)
if wandb_session is not None:
wandb_session.log({"loss": np.mean(batch_loss)})
# return labels, continuous scores
return np.array(epoch_labels), np.array(epoch_scores)
def _generate_wandb_config(self):
# create a dictinoary of parameters to save for this run
wandb_config = dict(
architecture=self.architecture_name,
sample_duration=self.preprocessor.sample_duration,
cuda_device_count=torch.cuda.device_count(),
mps_available=torch.backends.mps.is_available(),
classes=self.classes,
single_target=self.single_target,
opensoundscape_version=self.opensoundscape_version,
)
if "weight_decay" in self.optimizer_params:
wandb_config["l2_regularization"] = self.optimizer_params["weight_decay"]
else:
wandb_config["l2_regularization"] = "n/a"
if "lr" in self.optimizer_params:
wandb_config["learning_rate"] = self.optimizer_params["lr"]
else:
wandb_config["learning_rate"] = "n/a"
try:
wandb_config["sample_shape"] = [
self.preprocessor.height,
self.preprocessor.width,
self.preprocessor.channels,
]
except:
wandb_config["sample_shape"] = "n/a"
return wandb_config
def train(
self,
train_df,
validation_df=None,
epochs=1,
batch_size=1,
num_workers=0,
save_path=".",
save_interval=1, # save weights every n epochs
log_interval=10, # print metrics every n batches
validation_interval=1, # compute validation metrics every n epochs
invalid_samples_log="./invalid_training_samples.log",
raise_errors=False,
wandb_session=None,
progress_bar=True,
):
"""train the model on samples from train_dataset
If customized loss functions, networks, optimizers, or schedulers
are desired, modify the respective attributes before calling .train().
Args:
train_df:
a dataframe of files and labels for training the model
- either has index `file` or multi-index (file,start_time,end_time)
validation_df:
a dataframe of files and labels for evaluating the model
[default: None means no validation is performed]
epochs:
number of epochs to train for
(1 epoch constitutes 1 view of each training sample)
batch_size:
number of training files simultaneously passed through
forward pass, loss function, and backpropagation
num_workers:
number of parallel CPU tasks for preprocessing
Note: use 0 for single (root) process (not 1)
save_path:
location to save intermediate and best model objects
[default=".", ie current location of script]
save_interval:
interval in epochs to save model object with weights [default:1]
Note: the best model is always saved to best.model
in addition to other saved epochs.
log_interval:
interval in batches to print training loss/metrics
validation_interval:
interval in epochs to test the model on the validation set
Note that model will only update it's best score and save best.model
file on epochs that it performs validation.
invalid_samples_log:
file path: log all samples that failed in preprocessing
(file written when training completes)
- if None, does not write a file
raise_errors:
if True, raise errors when preprocessing fails
if False, just log the errors to unsafe_samples_log
wandb_session: a wandb session to log to
- pass the value returned by wandb.init() to progress log to a
Weights and Biases run
- if None, does not log to wandb
For example:
```
import wandb
wandb.login(key=api_key) #find your api_key at https://wandb.ai/settings
session = wandb.init(enitity='mygroup',project='project1',name='first_run')
...
model.train(...,wandb_session=session)
session.finish()
```
progress_bar: bool, if True, shows a progress bar with tqdm [default: True]
Effects:
If wandb_session is provided, logs progress and samples to Weights
and Biases. A random set of training and validation samples
are preprocessed and logged to a table. Training progress, loss,
and metrics are also logged.
Use self.wandb_logging dictionary to change the number of samples
logged.
"""
### Input Validation ###
class_err = """
Train and validation datasets must have same classes
and class order as model object. Consider using
`train_df=train_df[cnn.classes]` or `cnn.classes=train_df.columns`
before training.
"""
assert list(self.classes) == list(train_df.columns), class_err
if validation_df is not None:
assert list(self.classes) == list(validation_df.columns), class_err
# Validation: warn user if no validation set
if validation_df is None:
warnings.warn(
"No validation set was provided. Model will be "
"evaluated using the performance on the training set."
)
# Initialize attributes
self.log_interval = log_interval
self.save_interval = save_interval
self.save_path = save_path
# Initialize Weights and Biases (wandb) logging ###
if wandb_session is not None:
# update the run config with information about the model
wandb_session.config.update(self._generate_wandb_config())
# update the run config with training parameters
wandb_session.config.update(
dict(
epochs=epochs,
batch_size=batch_size,
num_workers=num_workers,
lr_update_interval=self.lr_update_interval,
lr_cooling_factor=self.lr_cooling_factor,
optimizer_cls=self.optimizer_cls,
model_save_path=Path(save_path).resolve(),
)
)
# use wandb.watch to log histograms of parameter and gradient values
# value of None for log_freq means do not use wandb.watch()
log_freq = self.wandb_logging["watch_freq"]
if log_freq is not None:
wandb_session.watch(
self.network,
log="all",
log_freq=log_freq,
log_graph=(self.wandb_logging["log_graph"]),
)
# log tables of preprocessed samples
wandb_session.log(
{
"Samples / training samples": wandb_table(
AudioFileDataset(
train_df, self.preprocessor, bypass_augmentations=False
),
self.wandb_logging["n_preview_samples"],
),
"Samples / training samples no aug": wandb_table(
AudioFileDataset(
train_df, self.preprocessor, bypass_augmentations=True
),
self.wandb_logging["n_preview_samples"],
),
"Samples / validation samples": wandb_table(
AudioFileDataset(
validation_df, self.preprocessor, bypass_augmentations=True
),
self.wandb_logging["n_preview_samples"],
),
}
)
# Move network to device
self.network.to(self.device)
### Set Up DataLoader, Loss and Optimization ###
dataloader = self._init_train_dataloader(
train_df, batch_size, num_workers, raise_errors
)
# self.opt_net = self._init_opt_net()
######################
# Optimization setup #
######################
# Setup optimizer parameters for each network component
# Note: we re-create bc the user may have changed self.optimizer_cls
# If optimizer already exists, keep the same state dict
# (for instance, user may be resuming training w/saved state dict)
if self.opt_net is not None:
optim_state_dict = self.opt_net.state_dict()
self.opt_net = self._init_optimizer()
self.opt_net.load_state_dict(optim_state_dict)
else:
self.opt_net = self._init_optimizer()
# Set up learning rate cooling schedule
self.scheduler = torch.optim.lr_scheduler.StepLR(
self.opt_net,
step_size=self.lr_update_interval,
gamma=self.lr_cooling_factor,
last_epoch=self.current_epoch - 1,
)
# Note: loss function (self.loss_fn) was initialize at __init__
# can override like model.loss_fn = SomeLossCls()
self.best_score = 0.0
self.best_epoch = 0
### Train ###
for epoch in range(epochs):
# 1 epoch = 1 view of each training file
# loss fn & backpropogation occurs after each batch
### Training ###
self._log(f"\nTraining Epoch {self.current_epoch}")
train_targets, train_scores = self._train_epoch(
dataloader, wandb_session, progress_bar=progress_bar
)
### Evaluate ###
train_score, self.train_metrics[self.current_epoch] = self.eval(
train_targets, train_scores
)
if wandb_session is not None:
# log metrics for this epoch to wandb
wandb_session.log({"training": self.train_metrics[self.current_epoch]})
#### Validation ###
if validation_df is not None and epoch % validation_interval == 0:
self._log("\nValidation.")
validation_scores = self.predict(
validation_df,
batch_size=batch_size,
num_workers=num_workers,
activation_layer="softmax_and_logit"
if self.single_target
else None,
split_files_into_clips=False,
) # returns a dataframe matching validation_df
validation_targets = validation_df.values
validation_scores = validation_scores.values
validation_score, self.valid_metrics[self.current_epoch] = self.eval(
validation_targets, validation_scores
)
score = validation_score
else: # Evaluate model w/train_score if no validation_df given
score = train_score
if wandb_session is not None:
wandb_session.log(
{"validation": self.valid_metrics[self.current_epoch]}
)
### Save ###
if (
self.current_epoch + 1
) % self.save_interval == 0 or epoch == epochs - 1:
self._log("Saving weights, metrics, and train/valid scores.", level=2)
self.save(f"{self.save_path}/epoch-{self.current_epoch}.model")
# if this is the best score, update & save weights to best.model
if score > self.best_score:
self.best_score = score
self.best_epoch = self.current_epoch
self._log("Updating best model", level=2)
self.save(f"{self.save_path}/best.model")
if wandb_session is not None:
wandb_session.log({"epoch": epoch})
self.current_epoch += 1
### Logging ###
self._log("Training complete", level=2)
self._log(
f"\nBest Model Appears at Epoch {self.best_epoch} "
f"with Validation score {self.best_score:.3f}."
)
# warn the user if there were invalid samples (samples that failed to preprocess)
invalid_samples = dataloader.dataset.report(log=invalid_samples_log)
self._log(
f"{len(invalid_samples)} of {len(train_df)} total training "
f"samples failed to preprocess",
level=2,
)
self._log(f"List of invalid samples: {invalid_samples}", level=3)
def save(self, path, save_train_loader=False, save_hooks=False):
"""save model with weights using torch.save()
load from saved file with torch.load(path) or cnn.load_model(path)
Note: saving and loading model objects across OpenSoundscape versions
will not work properly. Instead, use .save_torch_dict and .load_torch_dict
(but note that customizations to preprocessing, training params, etc will
not be retained using those functions).
For maximum flexibilty in further use, save the model with both .save() and
.save_torch_dict()
Args:
path: file path for saved model object
save_train_loader: retrain .train_loader in saved object
[default: False]