Keras:将模型对象作为参数传递给损失函数

时间:2018-12-24 06:19:57

标签: python tensorflow machine-learning keras

这个post几乎可以满足我的要求。简而言之,建议的解决方案是:

def custom_loss(y_true, y_pred):
  # Your model exists in global scope global e

  # Get the layers of your model
  layers = [l for l in e.layers]

  # Construct a graph to evaluate your other model on y_pred
  eval_pred = y_pred
  for i in range(len(layers)):
      eval_pred = layers[i](eval_pred)

  # Construct a graph to evaluate your other model on y_true
  eval_true = y_true
  for i in range(len(layers)):
      eval_true = layers[i](eval_true)

  # Now do what you wanted to do with outputs.
  # Note that we are not returning the values, but a tensor.
  return K.mean(K.square(eval_pred - eval_true), axis=-1)

在上面的函数中,e是一个全局参数,它是模型本身,而自定义损失函数使用该模型(全局),而无需用户传递模型。我不是全球争论的忠实拥护者。有没有一种方法可以构造custom_loss函数,使其无需使用全局参数就可以接收模型对象本身。例如,是否可以创建函数custom_loss(y_true, y_pred, e)并删除行global e,以便可以将custom_loss作为模型的损失函数来传递?

1 个答案:

答案 0 :(得分:1)

Keras API不支持该功能。正如documentation所述,损失函数正好采用两个参数:import { createRootNavigator } from "./router"; /**/ const Layout = createRootNavigator(signedIn); y_true

如果您具有这种功能,则必须修改Keras本身。看看: