if_else_op.md 1.3 KB
Newer Older
Z
zchen0211 已提交
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 M (M<=N) instances, each corresponds to a true element in `cond`.
Z
zchen0211 已提交
2 3

```python
Z
zchen0211 已提交
4 5 6 7 8 9
import paddle as pd

x = var()
y = var()
cond = var()

Z
zchen0211 已提交
10
b = pd.create_ifop(inputs=[x], output_num=1)
Z
zchen0211 已提交
11 12 13 14 15 16
with b.true_block():
    x = b.inputs(0)
    z = operator.add(x, y)
    b.set_output(0, operator.softmax(z))

out = b(cond)
Z
zchen0211 已提交
17 18
```

Z
zchen0211 已提交
19 20
If we want the output still has N instances, we can use IfElseOp with a default value, whose minibatch size must be N:

Z
zchen0211 已提交
21
```python
Z
zchen0211 已提交
22 23 24 25 26 27
import paddle as pd

x = var()
y = var()
cond = var()
default_value = var()
Z
zchen0211 已提交
28
b = pd.create_ifelseop(inputs=[x], output_num=1)
Z
zchen0211 已提交
29 30 31 32 33 34 35 36 37 38 39
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)
Z
zchen0211 已提交
40 41
```

Z
zchen0211 已提交
42 43 44 45 46 47 48 49
If only true_block is set in an IfElseOp, we can have a default value for false as:
```python
import paddle as pd

x = var()
y = var()
cond = var()
default_value = var()
Z
zchen0211 已提交
50
b = pd.create_ifelseop(inputs=[x], output_num=1, default_value)
Z
zchen0211 已提交
51 52 53 54 55 56 57 58 59

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.