问题描述
输入张量rnn_pv
的形状为(?, 48, 1)
.我想缩放此张量中的每个元素,因此我尝试如下使用Lambda
层:
The input tensor rnn_pv
is of shape (?, 48, 1)
. I want to scale every element in this tensor, so I try to use Lambda
layer as below:
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.
那么实现此功能的正确方法是什么?
So what is the proper way to realize this function ?
推荐答案
您不能在模型定义中使用Python控制流语句(如if-else语句)执行条件操作.相反,您需要使用在Keras后端中定义的方法.由于您使用TensorFlow作为后端,因此可以使用tf.where()
来实现:
You can't use Python control flow statements such as if-else statements to perform conditional operations in the definition of a model. Instead you need to use methods defined in Keras backends. Since you are using TensorFlow as the backend you can use tf.where()
to achieve that:
import tensorflow as tf
scaled = Lambda(lambda x: tf.where(x >= 1000, tf.ones_like(x), x/1000.))(input_tensor)
或者,要支持所有后端,您可以创建一个掩码来做到这一点:
Alternatively, to support all the backends, you can create a mask to do this:
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
方法:
Update: An alternative way to support all the backends is to use K.switch
method:
from keras import backend as K
scaled = Lambda(lambda x: K.switch(x >= 1000., K.ones_like(x), x / 1000.))(input_tensor)
这篇关于如何在Keras Lambda层中有条件地缩放值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!