如何在张量流中的自定义损失函数中使用经过训练的模型?

How to use trained model inside custom loss function in tensorflow?

我正在尝试在 tensorflow 的自定义损失函数中使用已经基于神经网络的训练模型。但是在另一个模型中使用此自定义损失函数时出现错误。谁能帮我弄清楚我在设计这个自定义损失函数时犯了什么错误。

自定义损失函数代码如下

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)

运行时报错如下


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.

您可以尝试在损失函数之外加载模型并仅传递权重。要将额外参数传递给自定义损失函数,您可以将其包装在另一个函数中,如下所述:https://medium.com/@Bloomore/how-to-write-a-custom-loss-function-with-additional-arguments-in-keras-5f193929f7a0