tensorflow - 我的损失自定义函数是否像我认为的那样做?
问题描述
我有一个带有自定义损失函数的 Keras 模型(如下所示)。预期的行为是,当地面实况的第一个数字(第 4 等级)为正时,网络应尝试逼近所有 8 个参数。否则,它应该只尝试近似第一个参数(并为其他参数输出任何内容)。换句话说,当真集的第一个参数为 0 或负数时,其余参数无关紧要。我做对了吗?我可以使用这样的 tf slice 吗?
我注意到参数 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
解决方案
答案似乎是 Keras.losses.MeanSquaredError 中的一些意外(至少对我而言)行为。我最终只是在普通的张量流中实现了我的损失。
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 是等价的,但事实并非如此。重新发明轮子 FTW!
推荐阅读
- xml - 如何在 1 列下返回字符串和数值
- python - Python 和 Selenium:在不使用关键字的情况下识别“表中的表”中的元素
- javascript - 使用 axios post 请求发送 formData 无法正常工作
- python - Beautifulsoup:找不到标签
- python - Statsmodels:当 H0 不为零时检索 p 值
- scala - 如何根据优先级验证规则验证 DataFrame Row?
- pandas - 熊猫中运行日期的填充
- java - 为什么java没有直接的内存管理工具?
- java - 在更深的嵌套项上使用 indexOn 的问题
- servicestack - 我必须将 ServiceStack 与 Kephas 集成在一起。如何让它们与依赖注入一起玩?