docstr: Trains the supplied model with the supplied parameters.
docstr_tok: ["Trains","the","supplied","model","with","the","supplied","parameters","."]
code: def train(self):
      """
      Trains the supplied model with the supplied parameters.
      """
      try:
          (
              epoch_counter,
              validation_metric_per_epoch,
          ) = self._restore_checkpoint()
      except RuntimeError:
          traceback.print_exc()
          raise ConfigurationError(
              "Could not recover training from the checkpoint.  Did you mean to output to "
              "a different serialization directory or delete the existing serialization "
              "directory?"
          )
  
      self._enable_gradient_clipping()
      self._enable_activation_logging()
  
      logger.info("Beginning training.")
  
      train_metrics = {}
      val_metrics = {}
      best_epoch_val_metrics = {}
      epochs_trained = 0
      training_start_time = time.time()
      for epoch in range(epoch_counter, self._num_epochs):
          epoch_start_time = time.time()
          train_metrics = self._train_epoch(epoch)
  
          if self._validation_data is not None:
              with torch.no_grad():
                  # We have a validation set, so compute all the metrics on it.
                  val_loss, num_batches = self._validation_loss()
                  val_metrics = self._get_metrics(
                      val_loss, num_batches, reset=True
                  )
  
                  # Check validation metric for early stopping
                  this_epoch_val_metric = val_metrics[
                      self._validation_metric
                  ]
  
                  # Check validation metric to see if it's the best so far
                  is_best_so_far = self._is_best_so_far(
                      this_epoch_val_metric, validation_metric_per_epoch
                  )
                  if is_best_so_far:
                      best_epoch_val_metrics = val_metrics.copy()
                  validation_metric_per_epoch.append(
                      this_epoch_val_metric
                  )
                  if self._should_stop_early(
                      validation_metric_per_epoch
                  ):
                      logger.info(
                          "Ran out of patience.  Stopping training."
                      )
                      break
  
          else:
              # No validation set, so just assume it's the best so far.
              is_best_so_far = True
              val_metrics = {}
              best_epoch_val_metrics = {}
              this_epoch_val_metric = None
  
          self._save_checkpoint(
              epoch, validation_metric_per_epoch, is_best=is_best_so_far
          )
          self._metrics_to_tensorboard(
              epoch, train_metrics, val_metrics=val_metrics
          )
          self._metrics_to_console(train_metrics, val_metrics)
  
          if self._learning_rate_scheduler:
              # The LRScheduler API is agnostic to whether your schedule requires a validation metric -
              # if it doesn't, the validation metric passed here is ignored.
              self._learning_rate_scheduler.step(
                  this_epoch_val_metric, epoch
              )
  
          epoch_elapsed_time = time.time() - epoch_start_time
          logger.info(
              "Epoch duration: %s",
              time.strftime(
                  "%H:%M:%S", time.gmtime(epoch_elapsed_time)
              ),
          )
  
          if epoch < self._num_epochs - 1:
              training_elapsed_time = time.time() - training_start_time
              estimated_time_remaining = training_elapsed_time * (
                  (self._num_epochs - epoch_counter)
                  / float(epoch - epoch_counter + 1)
                  - 1
              )
              formatted_time = unicode(
                  datetime.timedelta(
                      seconds=int(estimated_time_remaining)
                  )
              )
              logger.info(
                  "Estimated training time remaining: %s",
                  formatted_time,
              )
  
          epochs_trained += 1
  
      training_elapsed_time = time.time() - training_start_time
      metrics = {
          "training_duration": time.strftime(
              "%H:%M:%S", time.gmtime(training_elapsed_time)
          ),
          "training_start_epoch": epoch_counter,
          "training_epochs": epochs_trained,
      }
      for key, value in list(train_metrics.items()):
          metrics["training_" + key] = value
      for key, value in list(val_metrics.items()):
          metrics["validation_" + key] = value
  
      if validation_metric_per_epoch:
          # We may not have had validation data, so we need to hide this behind an if.
          if self._validation_metric_decreases:
              best_validation_metric = min(validation_metric_per_epoch)
          else:
              best_validation_metric = max(validation_metric_per_epoch)
          metrics.update(
              dict(
                  ("best_validation_{k}", v)
                  for k, v in list(best_epoch_val_metrics.items())
              )
          )
          metrics["best_epoch"] = [
              i
              for i, value in enumerate(validation_metric_per_epoch)
              if value == best_validation_metric
          ][-1]
      return metrics
  
imports: from __future__ import with_statement
  from __future__ import division
  from __future__ import absolute_import
  import logging
  import os
  import shutil
  import time
  import re
  import datetime
  import traceback
  import torch
  import torch.optim.lr_scheduler
  from torch.nn.parallel import replicate, parallel_apply
  from torch.nn.parallel.scatter_gather import scatter_kwargs, gather
  from allennlp.common import Params
  from allennlp.common.checks import ConfigurationError
  from allennlp.common.util import peak_memory_mb, gpu_memory_mb
  from allennlp.common.tqdm import Tqdm
  from allennlp.data.instance import Instance
  from allennlp.data.iterators.data_iterator import DataIterator
  from allennlp.models.model import Model
  from allennlp.nn import util
  from allennlp.training.learning_rate_schedulers import LearningRateScheduler
  from allennlp.training.optimizers import Optimizer
label_desc: Use image node_id 15 for calling the Trainer obj's underlying member method code with example usage: obj.train() and returns: metrics