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

标签 python tensorflow machine-learning keras tensor

输入张量 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/

相关文章:

python - 如何从 float 列表中获取 python 中整数的最大公约数?

python - len(set()) 的解释

c - 如何提高 C 中文件操作的性能

machine-learning - 甘斯生成元的损失函数

python - 如何通过 python 以编程方式提取 Azure IP 范围 json 文件?

python - 在 `tf.estimator` 中,如何在训练结束时(不是每次迭代时)将变量设置为 `tf.assign` ?

python - 为什么 validation_freq 不适用于 Keras 模型拟合?

tensorflow - 如何理解transformer中的masked multi-head attention

python - 没有 tf.keras.backend 的 lambda 层函数定义(Python Keras 包)

machine-learning - Caffe - prototxt 中的 num_output 给出了奇怪的行为