【问题标题】:How use properly tensorflow functions within the model如何在模型中正确使用 tensorflow 函数
【发布时间】:2021-03-18 15:05:45
【问题描述】:

我正在使用 TensorFlow 2 和 tensorflow.keras.layers 的功能 API 来构建模型。

我有一个形状为 [batch_size, length, dim] 的输入张量 (in_1),我想沿 length 维度计算平均值并获得输出张量 (out_1),形状为 [batch_size, dim]

我应该使用哪一个来做到这一点? (就输出形状和训练而言,所有这些选项都有效)

        out_1 = Lambda(lambda x: tf.math.reduce_mean(x, axis=1))(in_1)
        out_1 = Lambda(lambda x: tf.keras.backend.mean(x, axis=1))(in_1)
        out_1 = tf.math.reduce_mean(in_1, axis=1)

最后一个会自动创建一个TensorFlowOpLayer,这是应该避免的吗?

还有其他方法吗?

tf.math.reduce_mean 和 tf.keras.backend.mean 有什么区别,应该用哪个?

我知道应该在 Lambda 层内调用自定义函数,但是对于 TensorFlow 函数(例如 tf.math.reduce_mean)是否也可以“一举”处理张量?如果我需要指定参数(例如轴),我应该如何调用它们?

【问题讨论】:

    标签: python tensorflow keras model tensor


    【解决方案1】:

    首先,对于tf.keras.backend.meantf.math.reduce_mean 之间的区别:没有。您可以查看the source code 的 keras 后端版本,它仅使用reduce_mean(来自math_ops,但在内部与tf.math 中公开的版本相同)。恕我直言,这在他们合并 Keras 的 TF 重新设计中有点失败:Keras 现在包含在 TF 中,但 Keras 在“后端”中也使用 TF,所以你基本上每个操作都有两次:一旦 TF 版本,而曾经的Keras版本,毕竟也只是使用了TF版本。

    无论如何,对于使用Lambda 与否的区别:它也(真的)不重要。这是一个最小的例子:

    inp = tf.keras.Input((10,))
    layer = tf.reduce_mean(inp, axis=-1)
    
    model = tf.keras.Model(inp, layer)
    
    print(model.layers)
    

    给出输出

    [<tensorflow.python.keras.engine.input_layer.InputLayer at 0x7f1a651500b8>,
     <tensorflow.python.keras.engine.base_layer.TensorFlowOpLayer at 0x7f1a9912d8d0>]
    

    我们可以看到reduce_mean 操作被自动转换为TensorFlowOpLayer。现在,这在技术上可能与 Lambda 层不同,但我怀疑这会产生任何实际差异。我想这适用于Sequential 模型,您需要提供层列表,因此可能需要Lambda

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-14
      • 1970-01-01
      • 2020-04-06
      • 2018-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-31
      相关资源
      最近更新 更多