Keras 后端自定义损失函数
Keras backend Custom Loss Function
我正在尝试计算 (tp+tn)/total_samples
作为我的自定义损失函数。我知道如何在列表和列表理解中执行此操作,但我想我无法将 y_true
和 y_pred
转换为列表。
到目前为止我写的代码是:
def CustomLossFunction(y_true, y_pred):
y_true_mask_less_zero = K.less(y_true, 0)
y_true_mask_greater_zero = K.greater(y_true, 0)
y_pred_mask_less_zero = K.less(y_pred, 0)
y_pred_mask_greater_zero = K.greater(y_pred, 0)
t_zeros = K.equal(y_pred_mask_less_zero, y_true_mask_less_zero)
t_ones = K.equal(y_pred_mask_greater_zero, y_true_mask_greater_zero)
现在我需要将 t_zeros 和 t_ones 中的 TRUE 总数相加并将它们除以样本总数
我在这一行遇到错误:
sum_of_true_negatives = K.sum(t_zeros)
Value passed to parameter 'input' has DataType bool not in list of allowed values: float32, float64, int32, uint8, int16
问题:
- “(tp+tn)/total_samples”是否有任何内置损失函数
- 如果不是那么如何使用 Keras 后端计算?
你必须cast
你的布尔张量在计算之前浮动。
但是一个警告,所以你不要浪费你的时间:
This loss function will not work because it's not differentiable. You can't simply discard the "continuity" existing in y_pred
like that. (You will get errors like "None values not supported" or "An operation has None for gradient")
使用一些已有的标准函数进行分类,如binary_crossentropy
或categorical_crossentropy
。
铸造:
t_zeros = K.cast(t_zeros, K.floatx())
t_ones = K.cast(t_ones, K.floatx())
我正在尝试计算 (tp+tn)/total_samples
作为我的自定义损失函数。我知道如何在列表和列表理解中执行此操作,但我想我无法将 y_true
和 y_pred
转换为列表。
到目前为止我写的代码是:
def CustomLossFunction(y_true, y_pred):
y_true_mask_less_zero = K.less(y_true, 0)
y_true_mask_greater_zero = K.greater(y_true, 0)
y_pred_mask_less_zero = K.less(y_pred, 0)
y_pred_mask_greater_zero = K.greater(y_pred, 0)
t_zeros = K.equal(y_pred_mask_less_zero, y_true_mask_less_zero)
t_ones = K.equal(y_pred_mask_greater_zero, y_true_mask_greater_zero)
现在我需要将 t_zeros 和 t_ones 中的 TRUE 总数相加并将它们除以样本总数
我在这一行遇到错误:
sum_of_true_negatives = K.sum(t_zeros)
Value passed to parameter 'input' has DataType bool not in list of allowed values: float32, float64, int32, uint8, int16
问题:
- “(tp+tn)/total_samples”是否有任何内置损失函数
- 如果不是那么如何使用 Keras 后端计算?
你必须cast
你的布尔张量在计算之前浮动。
但是一个警告,所以你不要浪费你的时间:
This loss function will not work because it's not differentiable. You can't simply discard the "continuity" existing in
y_pred
like that. (You will get errors like "None values not supported" or "An operation has None for gradient")
使用一些已有的标准函数进行分类,如binary_crossentropy
或categorical_crossentropy
。
铸造:
t_zeros = K.cast(t_zeros, K.floatx())
t_ones = K.cast(t_ones, K.floatx())