【问题标题】:Create a custom loss function in keras incorperating a feature from the dataset在 keras 中创建自定义损失函数,合并数据集中的特征
【发布时间】:2021-03-18 12:05:33
【问题描述】:

我想为 Keras 深度学习回归模型创建自定义损失函数。对于自定义损失函数,我想使用数据集中的一个特征,但我没有使用该特定特征作为模型的输入。

我的数据如下所示:

X  |  Y  | feature
---|-----|--------
x1 | y1  | f1
x2 | y2  | f2

模型的输入是 X,我想使用模型预测 Y。我想要类似以下的东西作为损失函数:

def custom_loss(feature):
    def loss(y_true, y_pred):
        root_mean__square(y_true - y_pred) + std(y_pred - feature)
    return loss

我不能像上面那样使用包装函数,因为特征值取决于训练和测试批次,因此无法在模型编译时传递给自定义损失函数。如何使用数据集中的附加功能来创建自定义损失函数?

编辑:

我根据this thread 上的回答做了以下事情。当我使用此模型进行预测时,它是对“Y”还是 Y 和附加特征的组合进行预测?我想确定,因为 model.fit() 将 'Y' 和 'feature' 作为 y 进行训练,但 model.predict() 只给出一个输出。如果预测是 Y 和附加特征的组合,我怎样才能只提取 Y?

    def custom_loss(data, y_pred):

        y_true = data[:, 0]
        feature = data[:, 1]
        return K.mean(K.square((y_pred - y_true) + K.std(y__pred - feature)))

    def create_model():
        # create model
        model = Sequential()
        model.add(Dense(5, input_dim=1, activation="relu"))
        model.add(Dense(1, activation="linear"))

    (train, test) = train_test_split(df, test_size=0.3, random_state=42)

    model = models.create_model(train["X"].shape[1])
    opt = Adam(learning_rate=1e-2, decay=1e-3/200)
    model.compile(loss=custom_loss, optimizer=opt)


    model.fit(train["X"], train[["Y", "feature"]], validation_data=(test["X"], test[["Y", "feature"]]), batch_size = 8, epochs=90)

    predY = model.predict(test["X"]) # what does the model predict here?

【问题讨论】:

  • 您可以通过Input 层将feature 作为单独的输入传递给您的模型。在初始化Model( inputs, outputs ) 时将这个张量传递给outputs= 参数。因此,y_pred 将包含模型的实际预测以及额外的 feature 作为张量。
  • @ShubhamPanchal 如何访问自定义损失函数中的功能?

标签: python tensorflow keras


【解决方案1】:

您还可以通过以下方式将 .add_loss 与简单的 mse 损失一起使用:

input = Input(size)
output = YourLayers(input)
model = Model(input, output)
model.add_loss(std(tf.gather(input, feature_idx, axis=1) - output))
model.compile(loss='mse', optimizer=opt)

顺便说一句,奇怪的是你的正则化器是方差的平方,而你的损失是 mse。也许您希望它们像人们通常所做的那样处于相同的平方尺度(方差和 mse)上(考虑任何 L2 收缩,例如 Ridge 回归)。

【讨论】:

    【解决方案2】:

    首先检查你的输入 Y in fit 函数的数据结构,看看它是否与你关注的线程中的答案具有相同的结构,如果你做的事情完全正确,那么它应该可以解决你的问题。

    当我使用此模型进行预测时,它会预测“Y”还是 Y 和附加特征的组合?

    模型将具有与您定义的完全相同的输出形状,在您的情况下,因为模型输出是Dense(1, activation="linear"),所以它的输出形状为y_pred.shape == (batchsize, 1),仅此而已,您可以确定这一点,使用打印出来tf.print(y_pred)自己看看

    我也不知道是不是你的打字错误,你的 custom_loss 函数的最后一行应该是:

    return K.mean(K.square((y_pred - y_true) + K.std(y_pred - feature)))
    

    而不是

    return K.mean(K.square((y_pred - y_true) + K.std(y__pred - feature)))
    

    【讨论】:

      猜你喜欢
      • 2019-01-18
      • 2020-01-24
      • 2021-02-22
      • 2020-12-19
      • 2017-12-18
      • 2020-03-27
      • 1970-01-01
      • 2020-02-20
      • 2018-11-12
      相关资源
      最近更新 更多