【问题标题】:Tensorflow: Custom loss function leads to op outside of function building code errorTensorflow:自定义损失函数导致函数构建代码错误之外的操作
【发布时间】:2020-06-04 00:41:41
【问题描述】:

我正在使用 Tensorflow 编写一个 NN 模型来逼近正弦函数,我想使用 w.r.t 的二阶导数。到我的模型的损失函数中的输入。

我的代码还没有包含导数,但我只是在损失函数中添加了输入张量(作为第一步)并使用this 答案作为第一种方法。

我的代码目前看起来像这样

import tensorflow as tf
import numpy as np

from tensorflow import keras
from numpy import random

# --- Settings
x_min = 0
x_max = 2*np.pi

n_train = 64
n_test = 64

# --- Generate dataset
x_train = random.uniform(x_min, x_max, n_train)
y_train = np.sin(x_train)

x_test = random.uniform(x_min, x_max, n_test)
y_test = np.sin(x_test)

# --- Create model
model = keras.Sequential()

model.add(keras.layers.Dense(64, activation="tanh", input_dim=1))
model.add(keras.layers.Dense(64, activation="tanh"))

model.add(keras.layers.Dense(1, activation="tanh"))

def custom_loss_wrapper(input_tensor):

    def custom_loss(y_true, y_pred):
        return keras.losses.mean_squared_error(y_true, y_pred) + keras.backend.mean(input_tensor)

    return custom_loss

# --- Configure learning process
model.compile(
        optimizer=keras.optimizers.Adam(0.01),
        loss=custom_loss_wrapper(model.input),
        metrics=['MeanSquaredError'])

# --- Train from dataset
model.fit(x_train, y_train, epochs=5, batch_size=32, validation_data=(x_test, y_test))

model.evaluate(x_test, y_test)

我的自定义损失函数只是计算均方误差并添加输入值。这应该不是问题,但我收到错误

TypeError: An op outside of the function building code is being passed
a "Graph" tensor. It is possible to have Graph tensors
leak out of the function building context by including a
tf.init_scope in your function building code.
For example, the following function will fail:
  @tf.function
  def has_init_scope():
    my_constant = tf.constant(1.)
    with tf.init_scope():
      added = my_constant * 2
The graph tensor has name: dense_input:0

有人知道为什么会这样吗?

【问题讨论】:

标签: python tensorflow keras neural-network loss-function


【解决方案1】:

由于 TensorFlow 2.0 及更高版本默认运行在 Eager 模式下, Tensorflow op 将检查输入是否为 "tensorflow.python.framework.ops.EagerTensor" 类型,并且由于实现了 Keras, 急切模式的输入将是 "tensorflow.python.framework.ops.Tensor",这会引发错误

TypeError: An op outside of the function building code is being passed
a "Graph" tensor. It is possible to have Graph tensors
leak out of the function building context by including a
tf.init_scope in your function building code.
For example, the following function will fail:
  @tf.function
  def has_init_scope():
    my_constant = tf.constant(1.)
    with tf.init_scope():
      added = my_constant * 2

您可以通过明确告诉 TensorFlow 在 Keras 的渴望模式下运行来将输入类型更改为 EagerTensor。 将此设置为 true 将解决问题

tf.config.experimental_run_functions_eagerly(True)

【讨论】:

  • 好的,但是是否可以将“tensorflow.python.framework.ops.Tensor”传递给“custom_loss_wrapper”而不处于急切模式并失去性能?我需要将 keras.Input 传递给我的损失函数。它与这里的问题类似,我希望避免使用串联方法。 stackoverflow.com/questions/57704771/…
猜你喜欢
  • 1970-01-01
  • 2019-12-08
  • 2018-10-28
  • 2017-12-29
  • 1970-01-01
  • 1970-01-01
  • 2021-02-22
  • 2019-03-10
  • 2018-12-28
相关资源
最近更新 更多