1. Lambda:将均值为0的输入数据的正与负部分级联。Lambda用来编写不需要训练的层。
import keras.backend as K
from keras.layers.core import Lambda
from keras.models import Sequential
import numpy as np
np.random.seed(19931221)
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)
input_data=np.random.randint(0,10,(3,2))
x1 = input_data-np.mean(input_data, axis=1, keepdims=True)
model = Sequential()
model.add(Lambda(antirectifier, output_shape=antirectifier_output_shape,input_shape=(2,)))
res=model.predict(input_data)
当Lambda作为第一层时,要指定input_shape