title: How to use trained model inside custom loss function in tensorflow?
body: <p>I am trying to use an already NN-based Trained model inside the custom loss function in tensorflow. But I am getting an error while using this custom loss function inside another model. Can someone help me to figure out what’s the mistake that I am doing while designing this custom loss function.</p>
  <p><strong>The custom loss function code is the following</strong></p>
  <pre><code>def custom_loss_function(y_true, y_pred):
      
      model1= tf.keras.models.load_model('Loss_DT_Model')
      test_pred = model1.predict(y_pred)
      
      test_pred_revert = tf.math.argmax(test_pred, axis=1)
      
      acc_matrix = tf.keras.metrics.Accuracy()
      acc_matrix.update_state(y_true, test_pred_revert)
      accuracy_score = acc_matrix.result()
  
      return tf.squeez(test_pred)
  </code></pre>
  <p><strong>The error that I get at runtime is as follows</strong></p>
  <pre><code>
  RuntimeError: in user code:
  
      C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\keras\engine\training.py:806 train_function  *
          return step_function(self, iterator)
      C:\Users\Hufsa Khan\Desktop\Loss_function_DT_code\xxxxxxxxxxx.py:184 custom_loss_function  *
          model1= load_model('Loss_DT_Model')
      C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\keras\saving\save.py:187 load_model  **
          return saved_model_load.load(filepath, compile, options)
      C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\keras\saving\saved_model\load.py:140 load
          sess = backend.get_session()  # Variables are initialized by this call.
      C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\keras\backend.py:627 get_session
          session = _get_session(op_input_list)
      C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\keras\backend.py:587 _get_session
          raise RuntimeError('Cannot get session inside Tensorflow graph function.')
  
      RuntimeError: Cannot get session inside Tensorflow graph function.
  </code></pre>