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)