Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
jantic
GitHub Repository: jantic/deoldify
Path: blob/master/fastai/callbacks/csv_logger.py
781 views
1
"A `Callback` that saves tracked metrics into a persistent file."
2
#Contribution from devforfu: https://nbviewer.jupyter.org/gist/devforfu/ea0b3fcfe194dad323c3762492b05cae
3
from ..torch_core import *
4
from ..basic_data import DataBunch
5
from ..callback import *
6
from ..basic_train import Learner, LearnerCallback
7
from time import time
8
from fastprogress.fastprogress import format_time
9
10
__all__ = ['CSVLogger']
11
12
class CSVLogger(LearnerCallback):
13
"A `LearnerCallback` that saves history of metrics while training `learn` into CSV `filename`."
14
def __init__(self, learn:Learner, filename: str = 'history', append: bool = False):
15
super().__init__(learn)
16
self.filename,self.path,self.append = filename,self.learn.path/f'{filename}.csv',append
17
self.add_time = True
18
19
def read_logged_file(self):
20
"Read the content of saved file"
21
return pd.read_csv(self.path)
22
23
def on_train_begin(self, **kwargs: Any) -> None:
24
"Prepare file with metric names."
25
self.path.parent.mkdir(parents=True, exist_ok=True)
26
self.file = self.path.open('a') if self.append else self.path.open('w')
27
self.file.write(','.join(self.learn.recorder.names[:(None if self.add_time else -1)]) + '\n')
28
29
def on_epoch_begin(self, **kwargs:Any)->None:
30
if self.add_time: self.start_epoch = time()
31
32
def on_epoch_end(self, epoch: int, smooth_loss: Tensor, last_metrics: MetricsList, **kwargs: Any) -> bool:
33
"Add a line with `epoch` number, `smooth_loss` and `last_metrics`."
34
last_metrics = ifnone(last_metrics, [])
35
stats = [str(stat) if isinstance(stat, int) else '#na#' if stat is None else f'{stat:.6f}'
36
for name, stat in zip(self.learn.recorder.names, [epoch, smooth_loss] + last_metrics)]
37
if self.add_time: stats.append(format_time(time() - self.start_epoch))
38
str_stats = ','.join(stats)
39
self.file.write(str_stats + '\n')
40
41
def on_train_end(self, **kwargs: Any) -> None:
42
"Close the file."
43
self.file.close()
44
45