输入张量 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)
关于python - 如何有条件地缩放 Keras Lambda 层中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53167108/