【发布时间】: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