How do implement a cross correlation as loss function? I would like to use the normalized crosscorrelation coefficient NCC as a loss function in order to compare a output matrix A with a reference matrix B.
NCC=Sum_{ij} (A_{ij}-)(B_{ij}-)/(||A||*||B||)
with ||X||=SQRT(Sum_{ij} X_{ij}*X_{ij}) and  is the arithmetic mean
I tried to use the following Code as Lossfunction, but It does not work as I expected- I get an "TypeError: 'Tensor' object does not support item assignment"-Error warning.
Any hint helping to solve that problem will be very much appreciated
   def Loss_InvCrossCorr(ref,gen):
      batchsize=ref.shape[0]
      ref_mn=(tf.reduce_mean(ref, [1,2])) # Calculation of the mean for all reference sample of each batch
      gen_mn=tf.reduce_mean(gen, [1,2]) # Calculation of the mean for all generated samples of each batch
      ref_nrm=tf.sqrt(tf.reduce_sum((ref*ref),[1,2])) # Calculation of    the norm=sqrt(Sum_ij(Aij*Aij)  for all reference samples of each batch
      gen_nrm=tf.sqrt(tf.reduce_sum((gen*gen),[1,2])) # Calculation of the norm=sqrt(Sum_ij(Aij*Aij)  for all generated samples of each batch
      for i in range(batchsize):
         ref[i,:,:,0]=(ref[i,:,:,0]-ref_mn[i])/ref_nrm[i] 
         gen[i,:,:,0]=(gen[i,:,:,0]-gen_mn[i])/gen_nrm[i]
      return (-tf.reduce_sum((ref*gen)))


You're getting that error because of ref[i,:,:,0]=. In tensorflow, you can't do such an assignment via indexing. And you don't really need to do that as you can directly do the operations on the tensors.
If A and B are 4D such that the first dimension is the batch size, then you could rewrite your code as
import tensorflow as tf

def compute_loss(A, B):
  meanA = tf.reduce_mean(A, axis=(1,2), keepdims=True)
  meanB = tf.reduce_mean(B, axis=(1,2), keepdims=True)
  nA = tf.sqrt(tf.reduce_sum(tf.square(A), axis=(1,2), keepdims=True))
  nB = tf.sqrt(tf.reduce_sum(tf.square(B), axis=(1,2), keepdims=True))
  return -tf.reduce_sum((A-meanA)/nA*(B-meanB)/nB)

You can test this with
A = tf.random.normal((16,4,4,1))
B = tf.random.normal((16,4,4,1))
print(compute_loss(A, B))

