我想定义一个自定义成本函数
def custom_objective(y_true, y_pred):
....
return L
这不仅取决于y_true
和y_pred
,而且取决于x
所产生的相应的一些特征y_pred
。我想到的唯一方法是“隐藏”中的相关功能y_true
,以便y_true = [usual_y_true, relevant_x_features]
或类似的东西。
实现此功能有两个主要问题:
1)改变形状y_true
意味着我需要填充y_pred
一些垃圾,以使它们的形状相同。我可以通过修改模型的最后一层来实现
2)我像这样使用数据扩充:
datagen = ImageDataGenerator(preprocessing_function=my_augmenter)
在哪里my_augmenter()
应该给我上面x
使用的相关功能的功能custom_objective()
。但是,用
model.fit_generator(datagen.flow(x_train, y_train, batch_size=1), ...)
似乎无法让我访问使用计算的功能my_augmenter
。
我想我可以隐藏增强中的功能,x_train
立即在模型设置中将其复制,然后直接将其输入y_true
或类似的操作中,但是肯定有更好的方法吗?
也许您可以使用以下方法创建一个两部分模型:
因此,假设您已经originalModel
定义了。让我们定义外部模型。
#this model has three inputs:
originalInputs = originalModel.input
yTrueInputs = Input(shape_of_y_train)
featureInputs = Input(shape_of_features)
#the original outputs will become an input for a custom loss layer
originalOutputs = originalModel.output
#this layer contains our custom loss
loss = Lambda(innerLoss)([originalOutputs, yTrueInputs, featureInputs])
#outer model
outerModel = Model([originalInputs, yTrueInputs, featureInputs], loss)
现在,我们的自定义内部损失为:
def innerLoss(x):
y_pred = x[0]
y_true = x[1]
features = x[2]
.... calculate and return loss here ....
现在,对于已经在其中“包含”自定义损失的模型,我们实际上并不需要最终损失函数,但是由于keras要求它,我们将最终损失仅用作return y_pred
:
def finalLoss(true,pred):
return pred
这将使我们能够训练仅通过假人的情况y_true
。
但是,当然,我们还需要一个自定义生成器,否则我们将无法获得功能。
考虑到您已经originalGenerator =datagen.flow(x_train, y_train, batch_size=1)
定义了:
def customGenerator(originalGenerator):
while True: #keras needs infinite generators
x, y = next(originalGenerator)
features = ____extract features here____(x)
yield (x,y,features), y
#the last y will be a dummy output, necessary but not used
如果您想要使批处理订单随机化并使用多重处理的其他功能,也可以class CustomGenerator(keras.utils.Sequence)
遵循以下相同的逻辑。在帮助页面显示了如何。
因此,让我们编译并训练外部模型(这也会训练内部模型,以便您以后可以将其用于预测):
outerModel.compile(optimizer=..., loss=finalLoss)
outerModel.fit_generator(customGenerator(originalGenerator), batchesInOriginalGenerator,
epochs=...)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句