具有 min(y, p) 和 max(y,p) 的自定义损失函数

数据挖掘 张量流 损失函数
2022-02-17 06:38:47

我在张量流中创建一个神经网络,需要最小化以下损失函数: 其中表示真实值,表示预测值。由于损失函数不可微,因此在使用梯度下降时会成为一个问题。max(y,p)min(y,p)yp

更新,现在我正在尝试实现:
p>yloss=log(p)log(y)
p<yloss=log(y)log(p)
p=yloss=log(y)log(y)=log(p)log(p)

这是我的代码:

def custom_loss(y_true, pred):
    if pred > y_true:
        custom_loss = K.log(pred) - K.log(y_true)
    elif pred < y_true:
        custom_loss = K.log(y_true) - K.log(pred)
    else:
        custom_loss = K.log(pred)-K.log(pred)

    return custom_loss


if __name__ == '__main__':
    run = 1

    X = np.load("vectors_normal_2way.npy")

    with open("target2.pickle", "rb") as file:
        target_dict = pickle.load(file)

    target_strings = [*target_dict]

    Y = np.array([])

    for target_value in target_strings:
        Y = np.append(Y, target_dict.get(target_value))

    for i in range(run):
        X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2)
        model = get_model()
        start = time.time()
        model.fit(X_train, Y_train, verbose = 1, epochs = 1, batch_size = 32)
        end_time = time.time()-start
        pred = model.predict(X_test)[:, 0]

但我收到以下错误:

tensorflow.python.framework.errors_impl.InvalidArgumentError:  The second input must be a scalar, but it has shape [32]
     [[{{node gradient_tape/custom_loss/cond/StatelessIf/gradient_tape/custom_loss/weighted_loss/Mul/_17}}]] [Op:__inference_train_function_1040]
 

当我有 batch_size = 1 时代码可以运行

1个回答

损失函数计算提供给它的所有数据的误差。对于神经网络,这是小批量的平均值。您的代码可能只处理标量(因此在 batch=1 时工作),它应该处理向量。

K看起来您正在使用 tf.Keras 文档提供了自定义损失函数的示例。它有助于子类tf.keras.losses.Loss期望call()包含使用 y_true、y_pred 进行损失计算的逻辑的方法。

class CustomLoss(Loss):

  def call(self, y_true, y_pred):
    pass