code: def cosine_loss(
      prediction, ground_truth, weight_map=None, to_complete=True
  ):
      """
      Cosine loss between predicted and ground_truth vectors. The predicted and
       targeted vectors should be unit vectors
      :param prediction:
      :param ground_truth:
      :param weight_map:
      :param to_complete: if the unit vector is to be completed
      :return:
      """
      if to_complete:
          prediction_complete = tf.reshape(
              tf.sqrt(
                  1
                  - tf.minimum(
                      tf.reduce_sum(tf.square(prediction), -1), 1
                  )
              ),
              [tf.shape(prediction)[0], 1],
          )
          ground_truth_complete = tf.reshape(
              tf.sqrt(
                  1
                  - tf.minimum(
                      tf.reduce_sum(tf.square(ground_truth), -1), 1
                  )
              ),
              [tf.shape(prediction)[0], 1],
          )
  
          pred_vect = tf.concat([prediction, prediction_complete], -1)
  
          gt_vect = tf.concat([ground_truth, ground_truth_complete], -1)
      else:
          pred_vect = prediction
          gt_vect = ground_truth
  
      if weight_map is None:
          weight_map = tf.ones([tf.shape(prediction)[0]])
      else:
          weight_map = tf.reshape(weight_map, [tf.shape(prediction)[0]])
  
      pred_vect = pred_vect / tf.maximum(
          tf.norm(pred_vect, ord="euclidean", axis=-1, keep_dims=True),
          0.00001,
      )
      gt_vect = gt_vect / tf.maximum(
          tf.norm(gt_vect, ord="euclidean", axis=-1, keep_dims=True),
          0.00001,
      )
      loss_init = 1 - tf.reduce_sum(gt_vect * pred_vect, -1)
      weighted_loss = loss_init * weight_map
      loss = tf.reduce_sum(weighted_loss) / tf.reduce_sum(weight_map)
  
      return loss
  
file_path: NiftyNet/niftynet/layer/loss_regression.py
imports: from __future__ import absolute_import, print_function, division
  import tensorflow
  from niftynet.engine.application_factory import LossRegressionFactory
  from niftynet.layer.base_layer import Layer
label_desc: Use image node_id 7 for calling a global function with example usage: cosine_loss(prediction, ground_truth, weight_map, to_complete) and returns: loss