如何有条件地缩放 Keras Lambda 层中的值?

How to conditionally scale values in Keras Lambda layer?

输入张量 rnn_pv 的形状为 (?, 48, 1)。我想缩放这个张量中的每个元素,所以我尝试使用 Lambda 层,如下所示:

rnn_pv_scale = Lambda(lambda x: 1 if x >=1000 else x/1000.0 )(rnn_pv)

但是出现错误:

TypeError: Using a `tf.Tensor` as a Python `bool` is not allowed. Use `if t is not None:` instead of `if t:` to test if a tensor is defined, and use TensorFlow ops such as tf.cond to execute subgraphs conditioned on the value of a tensor.

那么实现这个功能的正确方法是什么?

您不能使用 Python 控制流语句(例如 if-else 语句)在模型定义中执行条件操作。相反,您需要使用 Keras 后端中定义的方法。由于您使用 TensorFlow 作为后端,您可以使用 tf.where() 来实现:

import tensorflow as tf

scaled = Lambda(lambda x: tf.where(x >= 1000, tf.ones_like(x), x/1000.))(input_tensor)

或者,要支持所有后端,您可以创建一个掩码来执行此操作:

from keras import backend as K

def rescale(x):
    mask = K.cast(x >= 1000., dtype=K.floatx())
    return mask + (x/1000.0) * (1-mask)

#...
scaled = Lambda(rescale)(input_tensor)

更新: 支持所有后端的另一种方法是使用 K.switch 方法:

from keras import backend as K

scaled = Lambda(lambda x: K.switch(x >= 1000., K.ones_like(x), x / 1000.))(input_tensor)