Add a line with `epoch` number, `smooth_loss` and `last_metrics`.
14504
def on_epoch_end(self, epoch: int, smooth_loss: Tensor, last_metrics: MetricsList, **kwargs: Any) -> bool:
        ""
        last_metrics = ifnone(last_metrics, [])
        stats = [str(stat) if isinstance(stat, int) else '#na#' if stat is None else f'{stat:.6f}'
                 for name, stat in zip(self.learn.recorder.names, [epoch, smooth_loss] + last_metrics)]
        if self.add_time: stats.append(format_time(time() - self.start_epoch))
        str_stats = ','.join(stats)
        self.file.write(str_stats + '\n')
422420
def _after_n_epoch(self, epoch_id: int, **_) -> None:
        
        SaveEvery.save_model(model=self._model, name_suffix=str(epoch_id), on_failure=self._on_save_failure)
954205
def add_metric(self, labels, count_value, sum_value, timestamp=None):
        
        self.samples.append(Sample(self.name + '_count', dict(zip(self._labelnames, labels)), count_value, timestamp))
        self.samples.append(Sample(self.name + '_sum', dict(zip(self._labelnames, labels)), sum_value, timestamp))
660709
def _add_mxnet_ctc_loss(pred, seq_len, label):
    
    pred_ctc = mx.sym.Reshape(data=pred, shape=(-4, seq_len, -1, 0))

    loss = mx.sym.contrib.ctc_loss(data=pred_ctc, label=label)
    ctc_loss = mx.sym.MakeLoss(loss)

    softmax_class = mx.symbol.SoftmaxActivation(data=pred)
    softmax_loss = mx.sym.MakeLoss(softmax_class)
    softmax_loss = mx.sym.BlockGrad(softmax_loss)
    return mx.sym.Group([softmax_loss, ctc_loss])
669463
def on_epoch_end(self, last_metrics:MetricsList, iteration:int, **kwargs)->None:
        ""
        self._write_metrics(iteration=iteration, last_metrics=last_metrics)
1162067
def on_step_end(self, step, logs):
        
        if self.info_names is None:
            self.info_names = logs['info'].keys()
        values = [('reward', logs['reward'])]
        if KERAS_VERSION > '2.1.3':
            self.progbar.update((self.step % self.interval) + 1, values=values)
        else:
            self.progbar.update((self.step % self.interval) + 1, values=values, force=True)
        self.step += 1
        self.metrics.append(logs['metrics'])
        if len(self.info_names) > 0:
            self.infos.append([logs['info'][k] for k in self.info_names])
138924
def run(self, epochs):
        
        best_loss = sys.maxsize
        for epoch in trange(epochs):
            iter_no = 0

            ## train
            sum_losses, len_losses = self.train_batch(self.train_dataloader)

            if iter_no % 20 == 0:
                current_loss = sum_losses / len_losses
                print("[Train] epoch:{e} iter:{i} loss:{l:.4f}".format(e=epoch,
                                                                       i=iter_no,
                                                                       l=current_loss))

            ## validating
            sum_val_losses, len_val_losses = self.infer_batch(self.valid_dataloader)

            current_val_loss = sum_val_losses / len_val_losses
            print("[Vaild] epoch:{e} iter:{i} loss:{l:.4f}".format(e=epoch,
                                                                   i=iter_no,
                                                                   l=current_val_loss))

            if best_loss > current_val_loss:
                self.save_model(epoch, current_val_loss)
                best_loss = current_val_loss

            iter_no += 1
388079
def on_epoch_end(self, n_epochs:int, last_metrics:MetricsList, **kwargs)->bool:
        ""
        if last_metrics is not None and np.any(last_metrics):
            rec = self.learn.recorder
            iters = range_of(rec.losses)
            val_iter = np.array(rec.nb_batches).cumsum()
            x_bounds = (0, (n_epochs - len(rec.nb_batches)) * rec.nb_batches[-1] + len(rec.losses))
            y_bounds = (0, max((max(Tensor(rec.losses)), max(Tensor(rec.val_losses)))))
            rec.pbar.update_graph([(iters, rec.losses), (val_iter, rec.val_losses)], x_bounds, y_bounds)
        return {}
710514
def infer_last_epoch_num(data_dir):
  """"""
  names = os.listdir(data_dir)
  epochs_str = [re.findall(pattern=r".*\.(-?\d+)$", string=name)
                for name in names]
  epochs_str = sum(epochs_str, [])
  return max([int(epoch_str) for epoch_str in epochs_str])
1030838
def update_metric(self, metric, labels, pre_sliced=False):
        """"""
        for current_exec, (texec, islice) in enumerate(zip(self.train_execs, self.slices)):
            if not pre_sliced:
                labels_slice = [label[islice] for label in labels]
            else:
                labels_slice = labels[current_exec]
            metric.update(labels_slice, texec.outputs)
46326
def add_line(self, line, source, *lineno):
        """"""
        self.result.append(line, source, *lineno)
1316914
def update(self,iiter,H,Y,eta,loss):
        """"""
        if iiter <= self.niter_trace+1:
            self.H[iiter] = H
            self.Y[iiter] = Y
        elif iiter >self.niter - self.niter_trace + 1:
            self.H[self.ltrace+iiter-self.niter-1] = H
            self.Y[self.ltrace+iiter-self.niter-1] = Y

        self.etas[iiter] = eta
        self.loss[iiter] = loss
        if self.loss[iiter] < self.lmin:
            self.Yh = Y
            self.lmin = self.loss[iiter]
            self.miniter = iiter if not iiter == -1 else self.niter + 1
1187787
def _prep_smooth(t, y, dy, span, t_out, span_out, period):
    """"""

    # If period is provided, sort by phases. Otherwise sort by t
    if period:
        t = t % period
        if t_out is not None:
            t_out = t_out % period

    t, y, dy = validate_inputs(t, y, dy, sort_by=t)

    if span_out is not None:
        if t_out is None:
            raise ValueError("Must specify t_out when span_out is given")
        if span is not None:
            raise ValueError("Must specify only one of span, span_out")
        span, t_out = np.broadcast_arrays(span_out, t_out)
        indices = np.searchsorted(t, t_out)
    elif span is None:
        raise ValueError("Must specify either span_out or span")
    else:
        indices = None

    return t, y, dy, span, t_out, span_out, indices
966754
def add_model(self, metric_value, model_id):
        
        if self.verbose:
            logger.info("Saving model.")

        # Update best_model text file
        ret = {"model_id": model_id, "metric_value": metric_value}
        self.history.append(ret)
        if model_id == self.get_best_model_id():
            file = open(os.path.join(self.path, "best_model.txt"), "w")
            file.write("best model: " + str(model_id))
            file.close()
        return ret
347587
def on_backward_begin(self, last_loss, last_output, **kwargs):
        ""
        last_loss = last_loss.detach().cpu()
        if self.gen_mode:
            self.smoothenerG.add_value(last_loss)
            self.glosses.append(self.smoothenerG.smooth)
            self.last_gen = last_output.detach().cpu()
        else:
            self.smoothenerC.add_value(last_loss)
            self.closses.append(self.smoothenerC.smooth)
845552
def add_metric(self, value, rank=None):
        
        self.conditions.append(
            dict(metric=value, type='metric', rank=rank))
1130802
def add_line(self, sentences, line_number=None):
        
        self.bytes += self.line(sentences, line_number)