【发布时间】:2020-02-21 19:02:03
【问题描述】:
我正在使用 Keras 开发一个神经网络,可以将英语句子翻译成一种自定义语言。为此,我想创建一个自定义损失函数,它对每个句子进行预测并评估它是否符合自定义语言的语法规则,如果不符合标准损失函数的价值。
如何在每个 epoch 之后而不是在编译期间评估张量?
下面是我的自定义损失函数。由于在模型编译期间还没有批次,y_pred 的形状为 (None, x, y) 并且无法评估以获得预测。我的想法是在编译期间分配一个标准损失函数,当批次到达时计算自定义损失。不幸的是,从未达到自定义损失。
def custom_loss(tokenizer, punishment_rate):
def compile_loss(y_true, y_pred):
shape = K.int_shape(y_pred)
#standard loss function
loss = K.sparse_categorical_crossentropy(y_true, y_pred)
if shape[0] is not None:
#THIS is never reached and that's the problem
prediction = logits_to_text(K.eval(y_pred), tokenizer)
#test if prediction complies to grammar rules
compileable = compiles(prediction) ^ 1
compile_error = compileable * punishment_rate
loss = K.sparse_categorical_crossentropy(y_true, y_pred, axis=-1) * (1 + compile_error)
return loss
return compile_loss
是否有任何解决方法可以仅在填充批次时评估张量?或者,在模型编译后通过回调更改损失函数,而不必重新编译模型?
【问题讨论】:
标签: python-3.x machine-learning keras nlp loss-function