手动训练循环替代方案
我唯一能想到的是手动训练循环,您可以自己获取权重。
有一个权重张量和一个不可变的批量大小:
weights = K.variable(np.zeros((batch_size,)))
在您的自定义损失中使用它们:
def custom_loss(true, pred):
return someCalculation(true, pred, weights)
对于“生成器”:
for e in range(epochs):
for s in range(steps_per_epoch):
x, y, w = next(generator) #or generator.next(), not sure
K.set_value(weights, w)
model.train_on_batch(x, y)
For a keras.utils.Sequence
:
for e in range(epochs):
for s in range(len(generator)):
x,y,w = generator[s]
K.set_value(weights, w)
model.train_on_batch(x,y)
我知道这个答案不是最佳的,因为它不会并行化从生成器获取数据,因为它发生在fit_generator
。但这是我能想到的最好的简单解决方案。 Keras 没有公开权重,它们会自动应用在一些隐藏的源代码中。
让模型计算权重替代方案
如果可以计算权重x
and y
,您可以将此任务委托给损失函数本身。
这有点hacky,但可能有效:
input1 = Input(shape1)
input2 = Input(shape2)
# .... model creation .... #
model = Model([input1, input2], outputs)
让损失者能够获得input1
and input2
:
def custom_loss(y_true, y_pred):
w = calculate_weights(input1, input2, y_pred)
# .... rest of the loss .... #
这里的问题是您是否可以根据输入将权重计算为张量。