python - Eager Execution 函数的输入不能是 Keras 符号张量

标签 python tensorflow keras deep-learning eager-execution

我正在尝试在 tf.Keras (TensorFlow 2.0.0rc0) 中为具有稀疏注释数据的 3-D U-Net 实现样本和像素相关的相关损失权重 (Cicek 2016, arxiv:1606.06650)。

这是我的代码:

import numpy as np
import tensorflow as tf
from tensorflow.keras import layers, losses, models

# disabling eager execution makes this example work:
# tf.python.framework_ops.disable_eager_execution()


def get_loss_fcn(w):
    def loss_fcn(y_true, y_pred):
        loss = w * losses.mse(y_true, y_pred)
        return loss
    return loss_fcn


data_x = np.random.rand(5, 4, 1)
data_w = np.random.rand(5, 4)
data_y = np.random.rand(5, 4, 1)

x = layers.Input([4, 1])
w = layers.Input([4])
y = layers.Activation('tanh')(x)
model = models.Model(inputs=[x, w], outputs=y)
loss = get_loss_fcn(model.input[1])

# using another loss makes it work, too:
# loss = 'mse'

model.compile(loss=loss)
model.fit((data_x, data_w), data_y)

print('Done.')

禁用急切执行时运行良好,但 TensorFlow 2 的要点之一是默认情况下具有急切执行。正如您所看到的,我和该目标之间的障碍是自定义损失函数(使用 'mse' 作为损失也可以消除该错误):

  File "MWE.py", line 30, in <module>
    model.fit((data_x, data_w), data_y)
[...]
tensorflow.python.eager.core._SymbolicException: Inputs to eager execution function cannot be Keras symbolic tensors, but found [<tf.Tensor 'input_2:0' shape=(None, 4) dtype=float32>]

我该怎么做才能使这种结构能够立即执行?

我的一个想法是将 w 连接到输出 y 并将 y_pred 分离到原始 y_pred > 和 w 在损失函数中,但这是我想避免的黑客行为。不过,它可以使用 # HERE 标记的更改:

import numpy as np
import tensorflow as tf
from tensorflow.keras import layers, losses, models


# HERE
def loss_fcn(y_true, y_pred):
    w = y_pred[:, :, -1]  # HERE
    y_pred = y_pred[:, :, :-1]  # HERE
    loss = w * losses.mse(y_true, y_pred)
    return loss


data_x = np.random.rand(5, 4, 1)
data_w = np.random.rand(5, 4, 1)  # HERE
data_y = np.random.rand(5, 4, 1)

x = layers.Input([4, 1])
w = layers.Input([4, 1])  # HERE
y = layers.Activation('tanh')(x)
output = layers.Concatenate()([y, w])  # HERE
model = models.Model(inputs=[x, w], outputs=output)  # HERE
loss = loss_fcn  # HERE

model.compile(loss=loss)
model.fit((data_x, data_w), data_y)

print('Done.')

还有其他想法吗?

最佳答案

一种替代解决方案是将权重作为附加输出特征而不是输入特征传递。

这使模型完全不受任何与权重相关的影响,并且权重仅出现在损失函数和 .fit() 调用中:

import numpy as np
import tensorflow as tf
from tensorflow.keras import layers, losses, models

data_x = 2 * np.ones((7, 11, 15, 3), dtype=float)
data_y = 5 * np.ones((7, 9, 13, 5), dtype=float)

x = layers.Input(data_x.shape[1:])
y = layers.Conv2D(5, kernel_size=3)(x)
model = models.Model(inputs=x, outputs=y)


def loss(y_true, y_pred):
    (y_true, w) = tf.split(y_true, num_or_size_splits=[-1, 1], axis=-1)
    loss = tf.squeeze(w, axis=-1) * losses.mse(y_true, y_pred)

    tf.print(tf.math.reduce_mean(y_true), "== 5")
    tf.print(tf.math.reduce_mean(w), "== 3")

    return loss


model.compile(loss=loss)

data_w = 3 * np.ones((7, 9, 13, 1), dtype=float)
data_yw = np.concatenate((data_y, data_w), axis=-1)
model.fit(data_x, data_yw)

还有一个缺点是,在 numpy.stack() 中合并 yw 时,您需要操作(可能)大型数组,因此,更多类似 TensorFlow 的内容将受到赞赏。

关于python - Eager Execution 函数的输入不能是 Keras 符号张量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57704771/

相关文章:

python - 通过 django 搜索表格模板的数据。不能不显示下一页>

python - 禁止 : 403 User not authorized even though the user is logged in

python - Tensorflow 导入错误

tensorflow - 如何查找卡住模型的输入和输出节点

python - 在Keras中执行最新的 "Lookahead Optimizer"论文?

python - 如何关闭 Python 正在使用的 mp3 文件?

python - 是否可以在类里面不使用 "self"?

tensorflow - 为什么 MobileNetV2 仅在移动设备上比 MobileNetV1 快?

loops - Keras Tensorflow 完全重置

python - "ImportError: DLL load failed: The specified procedure could not be found"- 而使用 Keras 在 Python 中使用 CNN 进行数字识别