code: def connect_data_and_network(
      self, outputs_collector=None, gradients_collector=None
  ):
      def switch_sampler(for_training):
          with tf.name_scope("train" if for_training else "validation"):
              sampler = self.get_sampler()[0][0 if for_training else -1]
              return sampler.pop_batch_op()
  
      if self.is_training:
          self.patience = self.action_param.patience
          if self.action_param.validation_every_n > 0:
              data_dict = tf.cond(
                  tf.logical_not(self.is_validation),
                  lambda: switch_sampler(for_training=True),
                  lambda: switch_sampler(for_training=False),
              )
          else:
              data_dict = switch_sampler(for_training=True)
  
          image = tf.cast(data_dict["image"], tf.float32)
          net_args = {
              "is_training": self.is_training,
              "keep_prob": self.net_param.keep_prob,
          }
          net_out = self.net(image, **net_args)
  
          with tf.name_scope("Optimiser"):
              optimiser_class = OptimiserFactory.create(
                  name=self.action_param.optimiser
              )
              self.optimiser = optimiser_class.get_instance(
                  learning_rate=self.action_param.lr
              )
          loss_func = LossFunction(
              loss_type=self.action_param.loss_type
          )
  
          crop_layer = CropLayer(
              border=self.regression_param.loss_border
          )
          weight_map = data_dict.get("weight", None)
          weight_map = (
              None if weight_map is None else crop_layer(weight_map)
          )
          data_loss = loss_func(
              prediction=crop_layer(net_out),
              ground_truth=crop_layer(data_dict["output"]),
              weight_map=weight_map,
          )
          reg_losses = tf.get_collection(
              tf.GraphKeys.REGULARIZATION_LOSSES
          )
          if self.net_param.decay > 0.0 and reg_losses:
              reg_loss = tf.reduce_mean(
                  [tf.reduce_mean(reg_loss) for reg_loss in reg_losses]
              )
              loss = data_loss + reg_loss
          else:
              loss = data_loss
  
          # Get all vars
          to_optimise = tf.trainable_variables()
          vars_to_freeze = (
              self.action_param.vars_to_freeze
              or self.action_param.vars_to_restore
          )
          if vars_to_freeze:
              import re
  
              var_regex = re.compile(vars_to_freeze)
              # Only optimise vars that are not frozen
              to_optimise = [
                  v for v in to_optimise if not var_regex.search(v.name)
              ]
              tf.logging.info(
                  "Optimizing %d out of %d trainable variables, "
                  "the other variables are fixed (--vars_to_freeze %s)",
                  len(to_optimise),
                  len(tf.trainable_variables()),
                  vars_to_freeze,
              )
  
          self.total_loss = loss
  
          grads = self.optimiser.compute_gradients(
              loss,
              var_list=to_optimise,
              colocate_gradients_with_ops=True,
          )
          # collecting gradients variables
          gradients_collector.add_to_collection([grads])
  
          # collecting output variables
          outputs_collector.add_to_collection(
              var=self.total_loss,
              name="total_loss",
              average_over_devices=True,
              collection=CONSOLE,
          )
          outputs_collector.add_to_collection(
              var=self.total_loss,
              name="total_loss",
              average_over_devices=True,
              summary_type="scalar",
              collection=TF_SUMMARIES,
          )
          outputs_collector.add_to_collection(
              var=data_loss,
              name="loss",
              average_over_devices=False,
              collection=CONSOLE,
          )
          outputs_collector.add_to_collection(
              var=data_loss,
              name="loss",
              average_over_devices=True,
              summary_type="scalar",
              collection=TF_SUMMARIES,
          )
  
      elif self.is_inference:
          data_dict = switch_sampler(for_training=False)
          image = tf.cast(data_dict["image"], tf.float32)
          net_args = {
              "is_training": self.is_training,
              "keep_prob": self.net_param.keep_prob,
          }
          net_out = self.net(image, **net_args)
          net_out = PostProcessingLayer("IDENTITY")(net_out)
  
          outputs_collector.add_to_collection(
              var=net_out,
              name="window",
              average_over_devices=False,
              collection=NETWORK_OUTPUT,
          )
          outputs_collector.add_to_collection(
              var=data_dict["image_location"],
              name="location",
              average_over_devices=False,
              collection=NETWORK_OUTPUT,
          )
          self.initialise_aggregator()
  
imports: import tensorflow
  from niftynet.application.base_application import BaseApplication
  from niftynet.engine.application_factory import ApplicationNetFactory, InitializerFactory, OptimiserFactory
  from niftynet.engine.application_variables import CONSOLE, NETWORK_OUTPUT, TF_SUMMARIES
  from niftynet.engine.sampler_grid_v2 import GridSampler
  from niftynet.engine.sampler_resize_v2 import ResizeSampler
  from niftynet.engine.sampler_uniform_v2 import UniformSampler
  from niftynet.engine.sampler_weighted_v2 import WeightedSampler
  from niftynet.engine.sampler_balanced_v2 import BalancedSampler
  from niftynet.engine.windows_aggregator_grid import GridSamplesAggregator
  from niftynet.engine.windows_aggregator_resize import ResizeSamplesAggregator
  from niftynet.io.image_reader import ImageReader
  from niftynet.layer.crop import CropLayer
  from niftynet.layer.histogram_normalisation import HistogramNormalisationLayer
  from niftynet.layer.loss_regression import LossFunction
  from niftynet.layer.mean_variance_normalisation import MeanVarNormalisationLayer
  from niftynet.layer.pad import PadLayer
  from niftynet.layer.post_processing import PostProcessingLayer
  from niftynet.layer.rand_flip import RandomFlipLayer
  from niftynet.layer.rand_rotation import RandomRotationLayer
  from niftynet.layer.rand_spatial_scaling import RandomSpatialScalingLayer
  from niftynet.layer.rgb_histogram_equilisation import RGBHistogramEquilisationLayer
  from niftynet.evaluation.regression_evaluator import RegressionEvaluator
  from niftynet.layer.rand_elastic_deform import RandomElasticDeformationLayer
  from niftynet.contrib.csv_reader.csv_reader import CSVReader
  from niftynet.contrib.csv_reader.sampler_resize_v2_csv import ResizeSamplerCSV
  from niftynet.contrib.csv_reader.sampler_grid_v2_csv import GridSamplerCSV
  from niftynet.contrib.csv_reader.sampler_uniform_v2_csv import UniformSamplerCSV
  from niftynet.contrib.csv_reader.sampler_weighted_v2_csv import WeightedSamplerCSV
  from niftynet.contrib.csv_reader.sampler_balanced_v2_csv import BalancedSamplerCSV
label_desc: Use image node_id 13 for calling the RegressionApplication obj's underlying member method code with example usage: obj.connect_data_and_network(outputs_collector, gradients_collector) and returns: sampler