一、switch
keras.backend.switch(condition, then_expression, else_expression)
根据一个标量值在两个操作之间切换。
请注意,then_expression
和 else_expression
都应该是相同尺寸的符号张量。
参数
- condition: 张量 (
int
或bool
)。 - then_expression: 张量或返回张量的可调用函数。
- else_expression: 张量或返回张量的可调用函数。
返回
选择的张量。
switch接口,顾名思义,就是一个if/else条件判断语句。不过要求输入和输出都必须是张量。
二、 example
import keras.backend as K
pred = K.placeholder([], dtype='bool')
count = K.variable(0)
x = K.switch(
condition=pred,
then_expression=lambda: K.update_add(count, 0),
else_expression=lambda: K.update_add(count, 1)
)
f = K.function(inputs=[pred], outputs=[x])
print(f([True]))
print(f([False]))
# print
[0.0]
[1.0]