if_else_op.md.txt 1.1 KB
Newer Older
1
IfOp should have only one branch. An IfOp operator takes a `cond` variable whose value must be a vector of N boolean elements. Its return value has N instances. If cond[i] == True, input instance input[i] will go through true_block() and generate output[i]; otherwise it will produce output from false_bloack().
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

```python
import paddle as pd

x = var()
y = var()
cond = var()
default_value = var()
b = pd.create_ifelseop(inputs=[x], output_num=1)
with b.true_block():
    x = b.inputs(0)
    z = operator.add(x, y)
    b.set_output(0, operator.softmax(z))

with b.false_block():
    x = b.inputs(0)
    z = layer.fc(x)
    b.set_output(0, operator.softmax(z))

out = b(cond)
```

24
If only true_block is set in an IfElseOp, a special case is that we can have a default value for false as:
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
```python
import paddle as pd

x = var()
y = var()
cond = var()
default_value = var()
b = pd.create_ifelseop(inputs=[x], output_num=1, default_value)

with b.true_block():
    x = b.inputs(0)
    z = operator.add(x, y)
    b.set_output(0, operator.softmax(z))

out = b(cond)
```
where default_value is a list of vars for `cond` == False.