# 浅谈keras中的Merge层(实现层的相加、相减、相乘实例)

【题目】keras中的Merge层（实现层的相加、相减、相乘）

Merge层

`Example`

```import keras

input1 = keras.layers.Input(shape=(16,))
x1 = keras.layers.Dense(8, activation='relu')(input1)
input2 = keras.layers.Input(shape=(32,))
x2 = keras.layers.Dense(8, activation='relu')(input2)

model = keras.models.Model(inputs=[input1, input2], outputs=out)```

`SubStract`

keras.layers.Subtract()

Example

```import keras

input1 = keras.layers.Input(shape=(16,))
x1 = keras.layers.Dense(8, activation='relu')(input1)
input2 = keras.layers.Input(shape=(32,))
x2 = keras.layers.Dense(8, activation='relu')(input2)
# Equivalent to subtracted = keras.layers.subtract([x1, x2])
subtracted = keras.layers.Subtract()([x1, x2])

out = keras.layers.Dense(4)(subtracted)
model = keras.models.Model(inputs=[input1, input2], outputs=out)```

`Multiply`

keras.layers.Multiply()

keras如何操作某一层的值（如让某一层的值取反加1等）？keras如何将某一层的神经元拆分以便进一步操作（如取输入的向量的第一个元素乘别的层）？keras如何重用某一层的值（如输入层和输出层乘积作为最终输出）？

Keras当中，任何的操作都是以网络层为单位，操作的实现都是新添一层，不管是加减一个常数还是做乘法，或者是对两层的简单拼接。

AttributeError: 'NoneType' object has no attribute '_inbound_nodes'

TypeError: 'Tensor' object is not callable

Lamda层怎么用？官方文档给了这样一个例子。

```# add a x -> x^2 layer
model.add(Lambda(lambda x: x ** 2))

# add a layer that returns the concatenation
# of the positive part of the input and
# the opposite of the negative part

def antirectifier(x):
x -= K.mean(x, axis=1, keepdims=True)
x = K.l2_normalize(x, axis=1)
pos = K.relu(x)
neg = K.relu(-x)
return K.concatenate([pos, neg], axis=1)

def antirectifier_output_shape(input_shape):
shape = list(input_shape)
assert len(shape) == 2 # only valid for 2D tensors
shape[-1] *= 2
return tuple(shape)

output_shape=antirectifier_output_shape))
```

L1 = F(L0);

L1 = Lambda( lambda L0:F(L0) ) (L0)