在 Keras 中实现自定义损失函数时,我需要tf.Variable
与我的输入数据的批量大小的形状(y_true, y_pred)
.
def custom_loss(y_true, y_pred):
counter = tf.Variable(tf.zeros(K.shape(y_true)[0], dtype=tf.float32))
...
但是,这会产生错误:
You must feed a value for placeholder tensor 'dense_17_target' with dtype float and shape [?,?]
如果我将batch_size固定为一个值:
def custom_loss(y_true, y_pred):
counter = tf.Variable(tf.zeros(batch_size, dtype=tf.float32))
...
这样|training_set| % batch_size
and |val_set| % batch_size
等于零,一切正常。
是否有任何建议,为什么根据输入的形状分配批量大小的变量(y_true
and y_pred
)不起作用?
SOLUTION
我找到了一个令人满意且有效的解决方案。
我用可能的最大batch_size(在模型构建时指定)初始化了变量,并使用了K.shape(y_true)[0]
仅用于切片变量。这样它就完美地工作了。这里是代码:
def custom_loss(y_true, y_pred):
counter = tf.Variable(tf.zeros(batch_size, dtype=tf.float32))
...
true_counter = counter[:K.shape(y_true)[0]]
...