【发布时间】:2024-01-19 13:12:01
【问题描述】:
我的目标是创建一个自定义损失函数,根据y_true、y_pred 和模型输入层的张量计算损失:
import numpy as np
from tensorflow import keras as K
input_shape = (16, 16, 1)
input = K.layers.Input(input_shape)
dense = K.layers.Dense(16)(input)
output = K.layers.Dense(1)(dense)
model = K.Model(inputs=input, outputs=output)
def CustomLoss(y_true, y_pred):
return K.backend.sum(K.backend.abs(y_true - model.input * y_pred))
model.compile(loss=CustomLoss)
model.fit(np.ones(input_shape), np.zeros(input_shape))
但是,此代码失败并显示以下错误消息:
TypeError: Cannot convert a symbolic Keras input/output to a numpy array. This error may indicate that you're trying to pass a symbolic value to a NumPy call, which is not supported. Or, you may be trying to pass Keras symbolic inputs/outputs to a TF API that does not register dispatching, preventing Keras from automatically converting the API call to a lambda layer in the Functional Model.
如何将模型的输入张量传递给损失函数?
Tensorflow 版本:2.4.1
Python 版本:3.8.8
【问题讨论】:
标签: python tensorflow keras deep-learning loss-function