繁体   English   中英

如何在 Keras 中实现此自定义损失 function?

[英]How can I implement this custom loss function in Keras?

我正在尝试在我的神经网络上实现自定义损失 function,如果张量是 numpy arrays,则看起来像这样:

def custom_loss(y_true, y_pred):
    activated = y_pred[y_true > 1]
    return np.abs(activated.mean() - activated.std()) / activated.std()

y 的形状为(batch_size, 1) 也就是说,它是每个输入行的标量 output。

obs:这篇文章( Converting Tensor to np.array using K.eval() in Keras 返回 InvalidArgumentError给了我一个初步的方向。

编辑:

这是一个可重现的设置,我正在尝试应用自定义损失 function:

import numpy as np

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers


X = np.random.normal(0, 1, (256, 5))
Y = np.random.normal(0, 1, (256, 1))

model = keras.Sequential([
    layers.Dense(1),
])

model.compile(optimizer='adam', loss=custom_loss)

model.fit(X, Y)

最后一行的.fit()抛出错误AttributeError: 'Tensor' object has no attribute 'mean' ,如果我按照上面的问题定义custom_loss

您是否尝试在 tensorflow 中编写它,因为有梯度问题? 或者这只是如何在 tensorflow 中这样做? - 别担心,我不会给你一个经典的有毒 SO 反应,我会尝试这样的事情(未经测试:但似乎沿着正确的轨道):

def custom_loss(y_true, y_pred):
    activated = tf.boolean_mask(y_pred, tf.where(y_true>1))
    return tf.math.abs(tf.reduce_mean(activated) - tf.math.reduce_std(activated)) / tf.math.reduce_std(activated))

您可能需要在其中使用尺寸,因为所有这些功能都允许指定要使用的尺寸。

此外,当您保存 model 时,您将失去损失 function,除非您对一般损失 function 进行子类化。 这可能比您想要的更详细,但如果您在保存和加载 model 时遇到问题,请告诉我。

这是一个简单的捕获。 您可以按如下方式使用自定义损失

def custom_loss(y_true, y_pred):
    activated = y_pred[y_true > 1]
    return tf.math.abs(tf.reduce_mean(activated) - 
                       tf.math.reduce_std(activated)) / tf.math.reduce_std(activated)

或者如果您想使用tf.boolean_mask(tensor, mask, ..)那么您需要确保mask条件的形状为(None,)1D 如果我们应用tf.where(y_true>1)它将产生一个2D张量,在你的情况下需要重新整形。

def custom_loss(y_true, y_pred):
    activated = tf.boolean_mask(y_pred, tf.reshape(tf.where(y_true>1),[-1]) )
    return tf.math.abs(tf.reduce_mean(activated) - 
                       tf.math.reduce_std(activated)) / tf.math.reduce_std(activated)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM