我有一个带有自定义损失函数的Keras模型(如下所示)。预期行为是,当基本事实的第一个数字(第4阶)为正时,网络应尝试近似所有8个参数。否则,它应该只尝试近似第一个参数(并只为其他参数输出任何内容)。换句话说,当true集的第一个参数为0或负数时,其余参数应该无关紧要。我做得对吗?我可以使用像这样的tf切片吗?
我注意到参数1-7普遍比我预期的更接近于0。就像函数在任何地方都在做MSE。
def custom_loss(y_true, y_pred):
truthiness = tf.greater(y_true[:, :, :, 0], tf.constant(0.0))
loss = tf.where(
truthiness,
tf.keras.losses.MeanSquaredError()(y_true[:, :, :, 0:8], y_pred[:, :, :, 0:8]),
tf.keras.losses.MeanSquaredError()(y_true[:, :, :, 0], y_pred[:, :, :, 0]),
)
return loss发布于 2020-08-15 06:03:16
答案似乎是Keras.losses.MeanSquaredError中的一些意想不到的行为(至少对我来说)。我最终只是在普通的tensorflow中实现了我的损失。
truthiness = tf.cast(tf.greater(y_true[:, :, :, 0], tf.constant(0.0)), dtype=tf.float32)
falsyness = tf.cast(tf.less_equal(y_true[:, :, :, 0], tf.constant(0.0)), dtype=tf.float32)
loss = tf.reduce_sum(tf.square(y_true[:, :, :, 0] - y_pred[:, :, :, 0])) + \
tf.multiply(
truthiness,
tf.reduce_sum(tf.square(y_true[:, :, :, 1:8] - y_pred[:, :, :, 1:8])),
)
loss_2 = tf.multiply(truthiness, tf.keras.losses.MeanSquaredError()(y_true[:, :, :, 0:8], y_pred[:, :, :, 0:8])) + \
tf.multiply(falsyness, tf.keras.losses.MeanSquaredError()(y_true[:, :, :, 0], y_pred[:, :, :, 0]))我期望loss和loss_2是等同的,但它们不是。
https://stackoverflow.com/questions/63405028
复制相似问题