python - Keras中带有掩码矩阵的自定义损失
问题描述
我正在尝试在 Keras 中使用我自己的损失函数。特别是,作为 y_pred 预测向量和 y_true 真实向量,我想要:
y_pred[i] = y_pred[i] if y_true[i] != 0
y_pred[i] = 0 if y_true[i] == 0
所以我尝试了以下方法:
def myloss(y_true, y_pred):
mask = K.not_equal(y_true, 0)
mask = K.cast(mask, dtype = 'float32')
loss_value = K.mean(K.square(mask*y_pred - y_true), axis = 1)
return loss_value
但我收到此错误:
TypeError:传递给参数“x”的值的 DataType bool 不在允许值列表中:bfloat16、float16、float32、float64、uint8、int8、uint16、int16、int32、int64、complex64、complex128
有人知道如何帮助我吗?
解决方案
您可以尝试使用tf.boolean_mask:
def myloss(y_true, y_pred):
mask = K.not_equal(y_true, 0)
pred_masked = tf.boolean_mask(y_pred - y_true, mask)
loss_value = K.mean(K.square(pred_masked), axis = 1)
return loss_value
推荐阅读
- sql - vb6/vba ado 在一系列日期上左连接
- vue.js - v-for key 属性或方法未在实例上定义,但在渲染期间引用
- javascript - 请我希望在我的 javascript 数组上使用 reduce 方法
- php - PHP:在 WordPress 中点击链接时通过 AJAX 下载文件
- javascript - setInterval 用于运行 if 语句不起作用的函数
- r - 使用 dplyr 包中的 select + unlist 和使用美元符号有什么区别?
- lua - 动态类型语言的编译器如何处理非局部变量的变化?
- javascript - jQuery FadeIn() 等不起作用,浏览器认为它们根本不起作用
- python - 如果发生异常,删除 JSON 文件
- go - 如何锁定地图并修复数据竞争