代码之家  ›  专栏  ›  技术社区  ›  yanachen

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

  •  2
  • yanachen  · 技术社区  · 7 年前

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

    那么,实现这一功能的正确途径是什么呢?

    1 回复  |  直到 7 年前
        1
  •  7
  •   today    7 年前

    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)