docstr: Trains a summarizer or resumes training of a previously initialized summarizer.
  
  Args:
      summarizer: Model to train, can be either a freshly created model or a loaded model.
      train_data: Data to train the model on.
      val_data (optional): Validation data.
      num_epochs: Number of epochs to train.
      scorers (optional): Dictionary with {score_name, scorer} to add validation scores to the logs.
      callbacks (optional): Additional custom callbacks.
docstr_tok: ["Trains","a","summarizer","or","resumes","training","of","a","previously","initialized","summarizer",".","Args",":","summarizer",":","Model","to","train",",","can","be","either","a","freshly","created","model","or","a","loaded","model",".","train_data",":","Data","to","train","the","model","on",".","val_data","(","optional",")",":","Validation","data",".","num_epochs",":","Number","of","epochs","to","train",".","scorers","(","optional",")",":","Dictionary","with","{","score_name",",","scorer","}","to","add","validation","scores","to","the","logs",".","callbacks","(","optional",")",":","Additional","custom","callbacks","."]
code: def train(
      self,
      summarizer: Summarizer,
      train_data: Iterable[Tuple[str, str]],
      val_data: Iterable[Tuple[str, str]] = None,
      num_epochs=2500,
      scorers: Dict[str, Scorer] = None,
      callbacks: List[tf.keras.callbacks.Callback] = None,
  ) -> None:
      """
      Trains a summarizer or resumes training of a previously initialized summarizer.
  
      Args:
          summarizer: Model to train, can be either a freshly created model or a loaded model.
          train_data: Data to train the model on.
          val_data (optional): Validation data.
          num_epochs: Number of epochs to train.
          scorers (optional): Dictionary with {score_name, scorer} to add validation scores to the logs.
          callbacks (optional): Additional custom callbacks.
      """
      if (
          summarizer.preprocessor is None
          or summarizer.vectorizer is None
      ):
          self.logger.info(
              "training a bare model, preprocessing data to init model..."
          )
          self._init_model(summarizer, train_data)
      else:
          self.logger.info("training an already initialized model...")
      vectorize_train = self._vectorize_data(
          preprocessor=summarizer.preprocessor,
          vectorizer=summarizer.vectorizer,
          bucket_generator=self.bucket_generator,
      )
      vectorize_val = self._vectorize_data(
          preprocessor=summarizer.preprocessor,
          vectorizer=summarizer.vectorizer,
          bucket_generator=None,
      )
      train_gen, val_gen = self._create_dataset_generators(summarizer)
      train_dataset = train_gen(lambda: vectorize_train(train_data))
      val_dataset = val_gen(lambda: vectorize_val(val_data))
  
      train_callbacks = callbacks or []
      if val_data is not None:
          train_callbacks.extend(
              [
                  EvaluationCallback(
                      summarizer=summarizer,
                      scorers=scorers or {},
                      val_data=val_data,
                      print_num_examples=self.num_print_predictions,
                  ),
                  ValidationCallback(
                      summarizer=summarizer,
                      val_dataset=val_dataset,
                      loss_function=self.loss_function,
                      batch_size=self.batch_size,
                  ),
              ]
          )
      loss_monitor = "loss_val" if val_data is not None else "loss"
      train_callbacks.append(
          ModelCheckpointCallback(
              file_path=self.model_save_path,
              summarizer=summarizer,
              monitor=loss_monitor,
              mode="min",
          )
      )
  
      if self.tensorboard_dir is not None:
          tb_callback = TensorboardCallback(
              log_dir=self.tensorboard_dir
          )
          train_callbacks.append(tb_callback)
      logs = {}
      epoch_count, batch_count, train_losses = 0, 0, []
      train_step = summarizer.new_train_step(
          self.loss_function, self.batch_size, apply_gradients=True
      )
      while epoch_count < num_epochs:
          for train_batch in train_dataset.take(-1):
              batch_count += 1
              current_loss = train_step(*train_batch)
              train_losses.append(current_loss)
              logs["loss"] = float(sum(train_losses)) / len(
                  train_losses
              )
              if batch_count % self.steps_to_log == 0:
                  self.logger.info(
                      "epoch {epoch}, batch {batch}, "
                      "logs: {logs}".format(
                          epoch=epoch_count,
                          batch=batch_count,
                          logs=logs,
                      )
                  )
              if batch_count % self.steps_per_epoch == 0:
                  train_losses.clear()
                  for callback in train_callbacks:
                      callback.on_epoch_end(epoch_count, logs=logs)
                  epoch_count += 1
                  if epoch_count >= num_epochs:
                      break
  
          self.logger.info(
              "finished iterating over dataset, total batches: {}".format(
                  batch_count
              )
          )
          if batch_count == 0:
              raise ValueError(
                  "Iterating over the dataset yielded zero batches!"
              )
  
imports: import datetime
  import logging
  import os
  import tempfile
  from collections import Counter
  from typing import Tuple, List, Iterable, Callable, Dict, Union
  import tensorflow
  import yaml
  from headliner.callbacks.evaluation_callback import EvaluationCallback
  from headliner.callbacks.model_checkpoint_callback import ModelCheckpointCallback
  from headliner.callbacks.tensorboard_callback import TensorboardCallback
  from headliner.callbacks.validation_callback import ValidationCallback
  from headliner.embeddings import read_embedding, embedding_to_matrix
  from headliner.evaluation.scorer import Scorer
  from headliner.losses import masked_crossentropy
  from headliner.model.bert_summarizer import BertSummarizer
  from headliner.model.summarizer import Summarizer
  from headliner.preprocessing.bucket_generator import BucketGenerator
  from headliner.preprocessing.dataset_generator import DatasetGenerator
  from headliner.preprocessing.keras_tokenizer import KerasTokenizer
  from headliner.preprocessing.preprocessor import Preprocessor
  from headliner.preprocessing.vectorizer import Vectorizer
  from headliner.utils.logger import get_logger
label_desc: Use image node_id 3 for calling the Trainer obj's underlying member method code with example usage: obj.train(summarizer, train_data, val_data, num_epochs, scorers, callbacks) without return types