Help us understand the problem. What is going on with this article?

# Kerasで分岐・結合を持つNNを素早く書く

More than 1 year has passed since last update.

# 環境

Python 3.5.2
Keras 2.0.4
tensorflow-gpu 1.1.0

# 分岐も簡単に書きたい

Sequentialモデルは

```from keras.models import Sequential
from keras.layers import InputLayer, Dense, Activation
model = Sequential()
#...
```

```from keras.layers import Input, Dense
input = Input((32,))
x = Dense(32, activation='relu')(input)
x = Dense(16, activation='relu')(x)
#...
```

initのカッコとcallのカッコが並んでいたり、右から左へ積んでいたり、

Sequentialモデルのようにサクッと書きたい。

ということで

# 関数定義

```def build(input, *nodes):
x = input
for node in nodes:
if callable(node):
x = node(x)
elif isinstance(node, list):
x = [build(x, branch) for branch in node]
elif isinstance(node, tuple):
x = build(x, *node)
else:
x = node
return x
```

この関数に突っ込みます。

# 使用例

## 分岐→和→分岐→積

```from keras.models import Model
from keras.layers import Input, Dense, Add, Multiply
def example_1():
input = Input((10,))
output = build(
input,
Dense(10),
[Dense(11, activation='relu'), Dense(11, activation='relu')],
[Dense(12, activation='relu'), Dense(12, activation='relu')],
Multiply(),
)
model = Model(input, output)
```

## 2入力2出力

```from keras.models import Model
from keras.layers import Input, Dense, Embedding, LSTM, Concatenate
def example_multi_input_and_multi_output():
main_input = Input(shape=(100,), dtype='int32', name='main_input')
auxiliary_input = Input(shape=(5,), name='aux_input')
outputs = build(
main_input,
Embedding(output_dim=512, input_dim=10000, input_length=100),
LSTM(32),
[Dense(1, activation='sigmoid', name='aux_output'),
([auxiliary_input, lambda x: x],
Concatenate(),
Dense(64, activation='relu'),
Dense(64, activation='relu'),
Dense(64, activation='relu'),
Dense(1, activation='sigmoid', name='main_output')
)
]
)
model = Model([main_input, auxiliary_input], outputs)
```

## ResNet

```def example_residual_connection():
input = Input(shape=(256, 256, 3))
output = build(
input,
Activation('relu'),
lambda x: x],
Activation('relu')
)
model = Model(input, output)
```
Why do not you register as a user and use Qiita more conveniently?
1. We will deliver articles that match you
By following users and tags, you can catch up information on technical fields that you are interested in as a whole
2. you can read useful information later efficiently
By "stocking" the articles you like, you can search right away